Initial commit

This commit is contained in:
Bassem Girgis
2018-12-20 17:34:07 -06:00
parent 7a2d899662
commit 81b4b9e273
34743 changed files with 5940233 additions and 0 deletions

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,782 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>SWIG and Android</title>
<link rel="stylesheet" type="text/css" href="style.css">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body bgcolor="#FFFFFF">
<H1><a name="Android">19 SWIG and Android</a></H1>
<!-- INDEX -->
<div class="sectiontoc">
<ul>
<li><a href="#Android_overview">Overview</a>
<li><a href="#Android_examples">Android examples</a>
<ul>
<li><a href="#Android_examples_intro">Examples introduction</a>
<li><a href="#Android_example_simple">Simple C example</a>
<li><a href="#Android_example_class">C++ class example</a>
<li><a href="#Android_examples_other">Other examples</a>
</ul>
<li><a href="#Android_stl">C++ STL</a>
</ul>
</div>
<!-- INDEX -->
<p>
This chapter describes SWIG's support of Android.
</p>
<H2><a name="Android_overview">19.1 Overview</a></H2>
<p>
The Android chapter is fairly short as support for Android is the same as for Java, where the Java Native Interface (JNI) is
used to call from Android Java into C or C++ compiled code.
Everything in the <a href="Java.html#Java">Java chapter</a> applies to generating code for access from Android Java code.
This chapter contains a few Android specific notes and examples.
</p>
<H2><a name="Android_examples">19.2 Android examples</a></H2>
<H3><a name="Android_examples_intro">19.2.1 Examples introduction</a></H3>
<p>
The examples require the <a href="http://developer.android.com/sdk/index.html">Android SDK</a> and <a href="http://developer.android.com/tools/sdk/ndk/index.html">Android NDK</a> which can be installed as per instructions in the links.
The Eclipse version is not required for these examples as just the command line tools are used (shown for Linux as the host, but Windows will be very similar, if not identical in most places).
Add the SDK tools and NDK tools to your path and create a directory somewhere for your Android projects (adjust PATH as necessary to where you installed the tools):
</p>
<div class="shell">
<pre>
$ export PATH=$HOME/android/android-sdk-linux_x86/tools:$HOME/android/android-sdk-linux_x86/platform-tools:$HOME/android/android-ndk-r6b:$PATH
$ mkdir AndroidApps
$ cd AndroidApps
</pre>
</div>
<p>
The examples use a target id of 1. This might need changing depending on your setup.
After installation of the Android SDK, the available target ids can be viewed by running the command below.
Please adjust the id to suit your target device.
</p>
<div class="shell">
<pre>
$ android list targets
</pre>
</div>
<p>
The following examples are shipped with SWIG under the Examples/android directory and include a Makefile to build and install each example.
</p>
<H3><a name="Android_example_simple">19.2.2 Simple C example</a></H3>
<p>
This simple C example shows how to call a C function as well as read and modify a global variable.
First we'll create and build a pure Java Android app. Afterwards the JNI code will be generated by SWIG and built into the app.
First create and build an app called <tt>SwigSimple</tt> in a subdirectory called <tt>simple</tt> using the commands below.
Adjust the <tt>--target</tt> id as mentioned earlier in the <a href="Android.html#Android_examples_intro">Examples introduction</a>.
<a href="http://developer.android.com/guide/developing/projects/projects-cmdline.html">Managing Projects from the Command Line</a> on the Android developer's site is a useful reference for these steps.
</p>
<div class="shell">
<pre>
$ android create project --target 1 --name SwigSimple --path ./simple --activity SwigSimple --package org.swig.simple
$ cd simple
$ ant debug
</pre>
</div>
<p>
Modify <tt>src/org/swig/simple/SwigSimple.java</tt> from the default to:
</p>
<div class="code">
<pre>
package org.swig.simple;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.ScrollView;
import android.text.method.ScrollingMovementMethod;
public class SwigSimple extends Activity
{
TextView outputText = null;
ScrollView scroller = null;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
outputText = (TextView)findViewById(R.id.OutputText);
outputText.setText("Press 'Run' to start...\n");
outputText.setMovementMethod(new ScrollingMovementMethod());
scroller = (ScrollView)findViewById(R.id.Scroller);
}
public void onRunButtonClick(View view)
{
outputText.append("Started...\n");
nativeCall();
outputText.append("Finished!\n");
// Ensure scroll to end of text
scroller.post(new Runnable() {
public void run() {
scroller.fullScroll(ScrollView.FOCUS_DOWN);
}
});
}
/** Calls into C/C++ code */
public void nativeCall()
{
// TODO
}
}
</pre>
</div>
<p>
The above simply adds a <i>Run</i> button and scrollable text view as the GUI aspects of the program.
The associated resources need to be created, modify <tt>res/layout/main.xml</tt> as follows:
</p>
<div class="code">
<pre>
&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
&gt;
&lt;Button
android:id="@+id/RunButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Run..."
android:onClick="onRunButtonClick"
/&gt;
&lt;ScrollView
android:id="@+id/Scroller"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
&gt;
&lt;TextView
android:id="@+id/OutputText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/&gt;
&lt;/ScrollView&gt;
&lt;/LinearLayout&gt;
</pre>
</div>
<p>
Rebuild the project with your changes:
</p>
<div class="shell">
<pre>
$ ant debug
</pre>
</div>
<p>
Although there are no native function calls in the code, yet, you may want to check that this simple pure
Java app runs before adding in the native calls.
First, set up your Android device for hardware debugging, see <a href="http://developer.android.com/guide/developing/device.html">Using hardware devices</a> on the Android developer's site.
When complete your device should be listed in those attached, something like:
</p>
<div class="shell">
<pre>
$ adb devices
List of devices attached
A32-6DBE0001-9FF80000-015D62C3-02018028 device
</pre>
</div>
<p>
This means you are now ready to install the application...
</p>
<div class="shell">
<pre>
$ adb install bin/SwigSimple-debug.apk
95 KB/s (4834 bytes in 0.049s)
pkg: /data/local/tmp/SwigSimple-debug.apk
Success
</pre>
</div>
<p>
The newly installed 'SwigSimple' app will be amongst all your other applications on the home screen. Run the app and it will show a <i>Run</i> button text box below it.
Press the <i>Run</i> button to see the simple text output.
</p>
<p>
The application can be uninstalled like any other application and in fact must be uninstalled before installing an updated version. Uninstalling is quite easy too from your host computer:
</p>
<div class="shell">
<pre>
$ adb uninstall org.swig.simple
Success
</pre>
</div>
<p>
Now that you have a pure Java Android app working, let's add some JNI code generated from SWIG.
</p>
<p>
First create a <tt>jni</tt> subdirectory and then create some C source code in <tt>jni/example.c</tt>:
</p>
<div class="code">
<pre>
/* File : example.c */
/* A global variable */
double Foo = 3.0;
/* Compute the greatest common divisor of positive integers */
int gcd(int x, int y) {
int g;
g = y;
while (x &gt; 0) {
g = x;
x = y % x;
y = g;
}
return g;
}
</pre>
</div>
<p>
Create a SWIG interface file for this C code, <tt>jni/example.i</tt>:
</p>
<div class="code">
<pre>
/* File : example.i */
%module example
%inline %{
extern int gcd(int x, int y);
extern double Foo;
%}
</pre>
</div>
<p>
Invoke SWIG as follows:
</p>
<div class="shell">
<pre>
$ swig -java -package org.swig.simple -outdir src/org/swig/simple -o jni/example_wrap.c jni/example.i
</pre>
</div>
<p>
SWIG generates the following files:
</p>
<ul>
<li><tt>src/org/swig/simple/exampleJNI.java</tt></li>
<li><tt>src/org/swig/simple/example.java</tt></li>
<li><tt>jni/example_wrap.c</tt></li>
</ul>
<p>
Next we need to create a standard Android NDK build system file <tt>jni/Android.mk</tt>:
</p>
<div class="code">
<pre>
# File: Android.mk
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_MODULE := example
LOCAL_SRC_FILES := example_wrap.c example.c
include $(BUILD_SHARED_LIBRARY)
</pre>
</div>
<p>
See the <a href="http://developer.android.com/sdk/ndk/index.html">Android NDK documentation</a> for more on the NDK build system and getting started with the NDK.
A simple invocation of ndk-build will compile the .c files and generate a shared object/system library. Output will be similar to:
</p>
<div class="shell">
<pre>
$ ndk-build
Compile thumb : example &lt;= example_wrap.c
Compile thumb : example &lt;= example.c
SharedLibrary : libexample.so
Install : libexample.so =&gt; libs/armeabi/libexample.so
</pre>
</div>
<p>
Now that the C JNI layer has been built, we can write Java code to call into the this layer.
Modify the <tt>nativeCall</tt> method in <tt>src/org/swig/simple/SwigSimple.java</tt> to call the JNI code as follows and add the static constructor to load the system library containing the compiled JNI C code:
</p>
<div class="code">
<pre>
/** Calls into C/C++ code */
public void nativeCall()
{
// Call our gcd() function
int x = 42;
int y = 105;
int g = example.gcd(x, y);
outputText.append("The greatest common divisor of " + x + " and " + y + " is " + g + "\n");
// Manipulate the Foo global variable
// Output its current value
double foo = example.getFoo();
outputText.append("Foo = " + foo + "\n");
// Change its value
example.setFoo(3.1415926);
// See if the change took effect
outputText.append("Foo = " + example.getFoo() + "\n");
// Restore value
example.setFoo(foo);
}
/** static constructor */
static {
System.loadLibrary("example");
}
</pre>
</div>
<p>
Compile the Java code as usual, uninstall the old version of the app if still installed and re-install the new app:
</p>
<div class="shell">
<pre>
$ ant debug
$ adb uninstall org.swig.simple
$ adb install bin/SwigSimple-debug.apk
</pre>
</div>
<p>
Run the app again and this time you will see the output pictured below, showing the result of calls into the C code:
</p>
<center><img src="android-simple.png" alt="Android screenshot of SwigSimple example"></center>
<H3><a name="Android_example_class">19.2.3 C++ class example</a></H3>
<p>
The steps for calling C++ code are almost identical to those in the previous C code example.
All the steps required to compile and use a simple hierarchy of classes for shapes are shown in this example.
</p>
<p>
First create an Android project called <tt>SwigClass</tt> in a subdirectory called <tt>class</tt>.
The steps below create and build a the JNI C++ app.
Adjust the <tt>--target</tt> id as mentioned earlier in the <a href="Android.html#Android_examples_intro">Examples introduction</a>.
</p>
<div class="shell">
<pre>
$ android create project --target 1 --name SwigClass --path ./class --activity SwigClass --package org.swig.classexample
$ cd class
</pre>
</div>
<p>
Now create a <tt>jni</tt> subdirectory and then create a C++ header file <tt>jni/example.h</tt> which defines our
hierarchy of shape classes:
</p>
<div class="code">
<pre>
/* File : example.h */
class Shape {
public:
Shape() {
nshapes++;
}
virtual ~Shape() {
nshapes--;
}
double x, y;
void move(double dx, double dy);
virtual double area() = 0;
virtual double perimeter() = 0;
static int nshapes;
};
class Circle : public Shape {
private:
double radius;
public:
Circle(double r) : radius(r) { }
virtual double area();
virtual double perimeter();
};
class Square : public Shape {
private:
double width;
public:
Square(double w) : width(w) { }
virtual double area();
virtual double perimeter();
};
</pre>
</div>
<p>
and create the implementation in the <tt>jni/example.cpp</tt> file:
</p>
<div class="code">
<pre>
/* File : example.cpp */
#include "example.h"
#define M_PI 3.14159265358979323846
/* Move the shape to a new location */
void Shape::move(double dx, double dy) {
x += dx;
y += dy;
}
int Shape::nshapes = 0;
double Circle::area() {
return M_PI*radius*radius;
}
double Circle::perimeter() {
return 2*M_PI*radius;
}
double Square::area() {
return width*width;
}
double Square::perimeter() {
return 4*width;
}
</pre>
</div>
<p>
Create a SWIG interface file for this C++ code in <tt>jni/example.i</tt>:
</p>
<div class="code">
<pre>
/* File : example.i */
%module example
%{
#include "example.h"
%}
/* Let's just grab the original header file here */
%include "example.h"
</pre>
</div>
<p>
Invoke SWIG as follows, note that the -c++ option is required for C++ code:
</p>
<div class="shell">
<pre>
$ swig -c++ -java -package org.swig.classexample -outdir src/org/swig/classexample -o jni/example_wrap.cpp jni/example.i
</pre>
</div>
<p>
SWIG generates the following files:
</p>
<ul>
<li><tt>src/org/swig/classexample/Square.java</tt></li>
<li><tt>src/org/swig/classexample/exampleJNI.java</tt></li>
<li><tt>src/org/swig/classexample/example.java</tt></li>
<li><tt>src/org/swig/classexample/Circle.java</tt></li>
<li><tt>src/org/swig/classexample/Shape.java</tt></li>
<li><tt>jni/example_wrap.cpp</tt></li>
</ul>
<p>
Next we need to create an Android NDK build system file for compiling the C++ code <tt>jni/Android.mk</tt>.
The <tt>-frtti</tt> compiler flag isn't strictly needed for this example, but is needed for any code that uses C++ RTTI:
</p>
<div class="code">
<pre>
# File: Android.mk
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_MODULE := example
LOCAL_SRC_FILES := example_wrap.cpp example.cpp
LOCAL_CFLAGS := -frtti
include $(BUILD_SHARED_LIBRARY)
</pre>
</div>
<p>
A simple invocation of ndk-build will compile the .cpp files and generate a shared object/system library. Output will be similar to:
</p>
<div class="shell">
<pre>
$ ndk-build
Compile++ thumb : example &lt;= example_wrap.cpp
Compile++ thumb : example &lt;= example.cpp
StaticLibrary : libstdc++.a
SharedLibrary : libexample.so
Install : libexample.so =&gt; libs/armeabi/libexample.so
</pre>
</div>
<p>
Now that the C JNI layer has been built, we can write Java code to call into this layer.
Modify <tt>src/org/swig/classexample/SwigClass.java</tt> from the default to:
</p>
<div class="code">
<pre>
package org.swig.classexample;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.ScrollView;
import android.text.method.ScrollingMovementMethod;
public class SwigClass extends Activity
{
TextView outputText = null;
ScrollView scroller = null;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
outputText = (TextView)findViewById(R.id.OutputText);
outputText.setText("Press 'Run' to start...\n");
outputText.setMovementMethod(new ScrollingMovementMethod());
scroller = (ScrollView)findViewById(R.id.Scroller);
}
public void onRunButtonClick(View view)
{
outputText.append("Started...\n");
nativeCall();
outputText.append("Finished!\n");
// Ensure scroll to end of text
scroller.post(new Runnable() {
public void run() {
scroller.fullScroll(ScrollView.FOCUS_DOWN);
}
});
}
/** Calls into C/C++ code */
public void nativeCall()
{
// ----- Object creation -----
outputText.append( "Creating some objects:\n" );
Circle c = new Circle(10);
outputText.append( " Created circle " + c + "\n");
Square s = new Square(10);
outputText.append( " Created square " + s + "\n");
// ----- Access a static member -----
outputText.append( "\nA total of " + Shape.getNshapes() + " shapes were created\n" );
// ----- Member data access -----
// Notice how we can do this using functions specific to
// the 'Circle' class.
c.setX(20);
c.setY(30);
// Now use the same functions in the base class
Shape shape = s;
shape.setX(-10);
shape.setY(5);
outputText.append( "\nHere is their current position:\n" );
outputText.append( " Circle = (" + c.getX() + " " + c.getY() + ")\n" );
outputText.append( " Square = (" + s.getX() + " " + s.getY() + ")\n" );
// ----- Call some methods -----
outputText.append( "\nHere are some properties of the shapes:\n" );
Shape[] shapes = {c, s};
for (int i=0; i&lt;shapes.length; i++)
{
outputText.append( " " + shapes[i].toString() + "\n" );
outputText.append( " area = " + shapes[i].area() + "\n" );
outputText.append( " perimeter = " + shapes[i].perimeter() + "\n" );
}
// Notice how the area() and perimeter() functions really
// invoke the appropriate virtual method on each object.
// ----- Delete everything -----
outputText.append( "\nGuess I'll clean up now\n" );
// Note: this invokes the virtual destructor
// You could leave this to the garbage collector
c.delete();
s.delete();
outputText.append( Shape.getNshapes() + " shapes remain\n" );
outputText.append( "Goodbye\n" );
}
/** static constructor */
static {
System.loadLibrary("example");
}
}
</pre>
</div>
<p>
Note the static constructor and the interesting JNI code is in the <tt>nativeCall</tt> method.
The remaining code deals with the GUI aspects which are identical to the previous C simple example. Modify <tt>res/layout/main.xml</tt> to contain the xml for the 'Run' button and scrollable text view:
</p>
<div class="code">
<pre>
&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
&gt;
&lt;Button
android:id="@+id/RunButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Run..."
android:onClick="onRunButtonClick"
/&gt;
&lt;ScrollView
android:id="@+id/Scroller"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
&gt;
&lt;TextView
android:id="@+id/OutputText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/&gt;
&lt;/ScrollView&gt;
&lt;/LinearLayout&gt;
</pre>
</div>
<p>
Compile the Java code as usual, uninstall the old version of the app if installed and re-install the new app:
</p>
<div class="shell">
<pre>
$ ant debug
$ adb uninstall org.swig.classexample
$ adb install bin/SwigClass-debug.apk
</pre>
</div>
<p>
Run the app to see the result of calling the C++ code from Java:
</p>
<center><img src="android-class.png" alt="Android screenshot of SwigClass example"></center>
<H3><a name="Android_examples_other">19.2.4 Other examples</a></H3>
<p>
The Examples/android directory contains further examples which can be run and installed in a similar manner to the previous two examples.
</p>
<p>
Note that the 'extend' example is demonstrates the directors feature.
Normally C++ exception handling and the STL is not available by default in the version of g++ shipped with Android, but this example turns these features on as described in the next section.
</p>
<H2><a name="Android_stl">19.3 C++ STL</a></H2>
<p>
Should the C++ Standard Template Library (STL) be required, an <tt>Application.mk</tt> file needs to be created
in the same directory as the <tt>Android.mk</tt> directory containing information about the STL to use.
See the NDK documentation in the $NDKROOT/docs folder especially CPLUSPLUS-SUPPORT.html.
Below is an example of the <tt>Application.mk</tt> file to make the STLport static library available for use:
</p>
<div class="code">
<pre>
# File: Application.mk
APP_STL := gnustl_static
</pre>
</div>
</body>
</html>

View File

@@ -0,0 +1,497 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Argument Handling</title>
<link rel="stylesheet" type="text/css" href="style.css">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body bgcolor="#ffffff">
<H1><a name="Arguments">10 Argument Handling</a></H1>
<!-- INDEX -->
<div class="sectiontoc">
<ul>
<li><a href="#Arguments_nn2">The typemaps.i library</a>
<ul>
<li><a href="#Arguments_nn3">Introduction</a>
<li><a href="#Arguments_nn4">Input parameters</a>
<li><a href="#Arguments_nn5">Output parameters</a>
<li><a href="#Arguments_nn6">Input/Output parameters</a>
<li><a href="#Arguments_nn7">Using different names</a>
</ul>
<li><a href="#Arguments_nn8">Applying constraints to input values</a>
<ul>
<li><a href="#Arguments_nn9">Simple constraint example</a>
<li><a href="#Arguments_nn10">Constraint methods</a>
<li><a href="#Arguments_nn11">Applying constraints to new datatypes</a>
</ul>
</ul>
</div>
<!-- INDEX -->
<p>
In Chapter 3, SWIG's treatment of basic datatypes and pointers was
described. In particular, primitive types such as <tt>int</tt> and
<tt>double</tt> 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.
</p>
<H2><a name="Arguments_nn2">10.1 The typemaps.i library</a></H2>
<p>
This section describes the <tt>typemaps.i</tt> library file--commonly used to
change certain properties of argument conversion.
</p>
<H3><a name="Arguments_nn3">10.1.1 Introduction</a></H3>
<p>
Suppose you had a C function like this:
</p>
<div class="code"><pre>
void add(double a, double b, double *result) {
*result = a + b;
}
</pre></div>
<p>
From reading the source code, it is clear that the function is storing
a value in the <tt>double *result</tt> parameter. However, since SWIG
does not examine function bodies, it has no way to know that this is
the underlying behavior.
</p>
<p>
One way to deal with this is to use the
<tt>typemaps.i</tt> library file and write interface code like this:
</p>
<div class="code"><pre>
// Simple example using typemaps
%module example
%include "typemaps.i"
%apply double *OUTPUT { double *result };
%inline %{
extern void add(double a, double b, double *result);
%}
</pre></div>
<p>
The <tt>%apply</tt> directive tells SWIG that you are going to apply
a special type handling rule to a type. The "<tt>double *OUTPUT</tt>" specification is the
name of a rule that defines how to return an output value from an argument of type
<tt>double *</tt>. This rule gets applied to all of the datatypes
listed in curly braces-- in this case "<tt>double *result</tt>".</p>
<p>
When the resulting module is created, you can now use the function
like this (shown for Python):
</p>
<div class="targetlang"><pre>
&gt;&gt;&gt; a = add(3, 4)
&gt;&gt;&gt; print a
7
&gt;&gt;&gt;
</pre></div>
<p>
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 <tt>double
*</tt> object and pass it to the function somehow.
</p>
<p>
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:
</p>
<div class="code"><pre>
%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);
%}
...
</pre></div>
<p>
In this case, the <tt>double *OUTPUT</tt> rule is applied to all of the functions that follow.
</p>
<p>
Typemap transformations can even be extended to multiple return values.
For example, consider this code:
</p>
<div class="code">
<pre>
%include "typemaps.i"
%apply int *OUTPUT { int *width, int *height };
// Returns a pair (width, height)
void getwinsize(int winid, int *width, int *height);
</pre>
</div>
<p>
In this case, the function returns multiple values, allowing it to be used like this:
</p>
<div class="targetlang"><pre>
&gt;&gt;&gt; w, h = genwinsize(wid)
&gt;&gt;&gt; print w
400
&gt;&gt;&gt; print h
300
&gt;&gt;&gt;
</pre>
</div>
<p>
It should also be noted that although the <tt>%apply</tt> 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:
</p>
<div class="code"><pre>
// 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);
</pre></div>
<p>
Typemaps stay in effect until they are explicitly deleted or redefined to something
else. To clear a typemap, the <tt>%clear</tt> directive should be used. For example:
</p>
<div class="code">
<pre>
%clear double *result; // Remove all typemaps for double *result
</pre>
</div>
<H3><a name="Arguments_nn4">10.1.2 Input parameters</a></H3>
<p>
The following typemaps instruct SWIG that a pointer really only holds a single
input value:
</p>
<div class="code"><pre>
int *INPUT
short *INPUT
long *INPUT
unsigned int *INPUT
unsigned short *INPUT
unsigned long *INPUT
double *INPUT
float *INPUT
</pre></div>
<p>
When used, it allows values to be passed instead of pointers. For example, consider this
function:
</p>
<div class="code"><pre>
double add(double *a, double *b) {
return *a+*b;
}
</pre></div>
<p>
Now, consider this SWIG interface:
</p>
<div class="code"><pre>
%module example
%include "typemaps.i"
...
%{
extern double add(double *, double *);
%}
extern double add(double *INPUT, double *INPUT);
</pre></div>
<p>
When the function is used in the scripting language interpreter, it will work like this:
</p>
<div class="targetlang"><pre>
result = add(3, 4)
</pre></div>
<H3><a name="Arguments_nn5">10.1.3 Output parameters</a></H3>
<p>
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.
</p>
<div class="code"><pre>
int *OUTPUT
short *OUTPUT
long *OUTPUT
unsigned int *OUTPUT
unsigned short *OUTPUT
unsigned long *OUTPUT
double *OUTPUT
float *OUTPUT
</pre></div>
<p>
These methods can be used as shown in an earlier example. For example, if you have this C function :</p>
<div class="code"><pre>
void add(double a, double b, double *c) {
*c = a+b;
}
</pre></div>
<p>
A SWIG interface file might look like this :</p>
<div class="code"><pre>
%module example
%include "typemaps.i"
...
%inline %{
extern void add(double a, double b, double *OUTPUT);
%}
</pre></div>
<p>
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).
</p>
<p>
If the function also returns a value, it is returned along with the argument. For example,
if you had this:
</p>
<div class="code"><pre>
extern int foo(double a, double b, double *OUTPUT);
</pre></div>
<p>
The function will return two values like this:
</p>
<div class="targetlang">
<pre>
iresult, dresult = foo(3.5, 2)
</pre>
</div>
<H3><a name="Arguments_nn6">10.1.4 Input/Output parameters</a></H3>
<p>
When a pointer serves as both an input and output value you can use
the following typemaps :</p>
<div class="code"><pre>
int *INOUT
short *INOUT
long *INOUT
unsigned int *INOUT
unsigned short *INOUT
unsigned long *INOUT
double *INOUT
float *INOUT
</pre></div>
<p>
A C function that uses this might be something like this:</p>
<div class="code"><pre>
void negate(double *x) {
*x = -(*x);
}
</pre></div>
<p>
To make x function as both and input and output value, declare the
function like this in an interface file :</p>
<div class="code"><pre>
%module example
%include "typemaps.i"
...
%{
extern void negate(double *);
%}
extern void negate(double *INOUT);
</pre></div>
<p>
Now within a script, you can simply call the function normally :</p>
<div class="targetlang"><pre>
a = negate(3); # a = -3 after calling this
</pre></div>
<p>
One subtle point of the <tt>INOUT</tt> 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 <tt>INOUT</tt> rule returns the modified value as a new object
rather than directly overwriting the value of the original input object.
</p>
<p>
<b>Compatibility note :</b> The <tt>INOUT</tt> rule used to be known as <tt>BOTH</tt> in earlier versions of
SWIG. Backwards compatibility is preserved, but deprecated.
</p>
<H3><a name="Arguments_nn7">10.1.5 Using different names</a></H3>
<p>
As previously shown, the <tt>%apply</tt> directive can be used to apply the <tt>INPUT</tt>, <tt>OUTPUT</tt>, and
<tt>INOUT</tt> typemaps to different argument names. For example:
</p>
<div class="code"><pre>
// 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};
</pre></div>
<p>
To clear a rule, the <tt>%clear</tt> directive is used:
</p>
<div class="code"><pre>
%clear double *result;
%clear Int32 *in, long *x;
</pre></div>
<p>
Typemap declarations are lexically scoped so a typemap takes effect from the point of definition to the end of the
file or a matching <tt>%clear</tt> declaration.
</p>
<H2><a name="Arguments_nn8">10.2 Applying constraints to input values</a></H2>
<p>
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 <tt>constraints.i</tt> library file.
</p>
<H3><a name="Arguments_nn9">10.2.1 Simple constraint example</a></H3>
<p>
The constraints library is best illustrated by the following interface
file :</p>
<div class="code"><pre>
// 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
</pre></div>
<p>
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.</p>
<H3><a name="Arguments_nn10">10.2.2 Constraint methods</a></H3>
<p>
The following constraints are currently available</p>
<div class="code"><pre>
POSITIVE Any number &gt; 0 (not zero)
NEGATIVE Any number &lt; 0 (not zero)
NONNEGATIVE Any number &gt;= 0
NONPOSITIVE Any number &lt;= 0
NONZERO Nonzero number
NONNULL Non-NULL pointer (pointers only).
</pre></div>
<H3><a name="Arguments_nn11">10.2.3 Applying constraints to new datatypes</a></H3>
<p>
The constraints library only supports the primitive C datatypes, but it
is easy to apply it to new datatypes using <tt>%apply</tt>. For
example :</p>
<div class="code"><pre>
// Apply a constraint to a Real variable
%apply Number POSITIVE { Real in };
// Apply a constraint to a pointer type
%apply Pointer NONNULL { Vector * };
</pre></div>
<p>
The special types of "Number" and "Pointer" can be applied to any
numeric and pointer variable type respectively. To later remove a
constraint, the <tt>%clear</tt> directive can be used :</p>
<div class="code"><pre>
%clear Real in;
%clear Vector *;
</pre></div>
</body>
</html>

View File

@@ -0,0 +1,474 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>ccache-swig(1) manpage</title>
<link rel="stylesheet" type="text/css" href="style.css">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body bgcolor="#ffffff">
<H1><a name="CCache">17 Using SWIG with ccache - ccache-swig(1) manpage</a></H1>
<!-- INDEX -->
<div class="sectiontoc">
<ul>
<li><a href="#CCache_nn2">NAME</a>
<li><a href="#CCache_nn3">SYNOPSIS</a>
<li><a href="#CCache_nn4">DESCRIPTION</a>
<li><a href="#CCache_nn5">OPTIONS SUMMARY</a>
<li><a href="#CCache_nn6">OPTIONS</a>
<li><a href="#CCache_nn7">INSTALLATION</a>
<li><a href="#CCache_nn8">EXTRA OPTIONS</a>
<li><a href="#CCache_nn9">ENVIRONMENT VARIABLES</a>
<li><a href="#CCache_nn10">CACHE SIZE MANAGEMENT</a>
<li><a href="#CCache_nn11">CACHE COMPRESSION</a>
<li><a href="#CCache_nn12">HOW IT WORKS</a>
<li><a href="#CCache_nn13">USING CCACHE WITH DISTCC</a>
<li><a href="#CCache_nn14">SHARING A CACHE</a>
<li><a href="#CCache_nn15">HISTORY</a>
<li><a href="#CCache_nn16">DIFFERENCES FROM COMPILERCACHE</a>
<li><a href="#CCache_nn17">CREDITS</a>
<li><a href="#CCache_nn18">AUTHOR</a>
</ul>
</div>
<!-- INDEX -->
<p>
<H2><a name="CCache_nn2">17.1 NAME</a></H2>
<p>
ccache-swig - a fast compiler cache
<p>
<H2><a name="CCache_nn3">17.2 SYNOPSIS</a></H2>
<p>
ccache-swig [OPTION]
<p>
ccache-swig &lt;compiler&gt; [COMPILER OPTIONS]
<p>
&lt;compiler&gt; [COMPILER OPTIONS]
<p>
<H2><a name="CCache_nn4">17.3 DESCRIPTION</a></H2>
<p>
ccache-swig is a compiler cache. It speeds up re-compilation of C/C++/SWIG code
by caching previous compiles and detecting when the same compile is
being done again. ccache-swig is ccache plus support for SWIG. ccache
and ccache-swig are used interchangeably in this document.
<p>
<H2><a name="CCache_nn5">17.4 OPTIONS SUMMARY</a></H2>
<p>
Here is a summary of the options to ccache-swig.
<p>
<pre>
-s show statistics summary
-z zero statistics
-c run a cache cleanup
-C clear the cache completely
-F &lt;n&gt; set maximum files in cache
-M &lt;n&gt; set maximum size of cache (use G, M or K)
-h this help page
-V print version number
</pre>
<p>
<H2><a name="CCache_nn6">17.5 OPTIONS</a></H2>
<p>
These options only apply when you invoke ccache as "ccache-swig". When
invoked as a compiler none of these options apply. In that case your
normal compiler options apply and you should refer to your compilers
documentation.
<p>
<dl>
<p><dt><strong><strong>-h</strong></strong><dd> Print a options summary page
<p>
<p><dt><strong><strong>-s</strong></strong><dd> Print the current statistics summary for the cache. The
statistics are stored spread across the subdirectories of the
cache. Using "ccache-swig -s" adds up the statistics across all
subdirectories and prints the totals.
<p>
<p><dt><strong><strong>-z</strong></strong><dd> Zero the cache statistics.
<p>
<p><dt><strong><strong>-V</strong></strong><dd> Print the ccache version number
<p>
<p><dt><strong><strong>-c</strong></strong><dd> Clean the cache and re-calculate the cache file count and
size totals. Normally the -c option should not be necessary as ccache
keeps the cache below the specified limits at runtime and keeps
statistics up to date on each compile. This option is mostly useful
if you manually modify the cache contents or believe that the cache
size statistics may be inaccurate.
<p>
<p><dt><strong><strong>-C</strong></strong><dd> Clear the entire cache, removing all cached files.
<p>
<p><dt><strong><strong>-F &lt;maxfiles&gt;</strong></strong><dd> This sets the maximum number of files allowed in
the cache. The value is stored inside the cache directory and applies
to all future compiles. Due to the way the value is stored the actual
value used is always rounded down to the nearest multiple of 16.
<p>
<p><dt><strong><strong>-M &lt;maxsize&gt;</strong></strong><dd> This sets the maximum cache size. You can specify
a value in gigabytes, megabytes or kilobytes by appending a G, M or K
to the value. The default is gigabytes. The actual value stored is
rounded down to the nearest multiple of 16 kilobytes.
<p>
</dl>
<p>
<H2><a name="CCache_nn7">17.6 INSTALLATION</a></H2>
<p>
There are two ways to use ccache. You can either prefix your compile
commands with "ccache-swig" or you can create a symbolic link between
ccache-swig and the names of your compilers. The first method is most
convenient if you just want to try out ccache or wish to use it for
some specific projects. The second method is most useful for when you
wish to use ccache for all your compiles.
<p>
To install for usage by the first method just copy ccache-swig to somewhere
in your path.
<p>
To install for the second method do something like this:
<pre>
cp ccache-swig /usr/local/bin/
ln -s /usr/local/bin/ccache-swig /usr/local/bin/gcc
ln -s /usr/local/bin/ccache-swig /usr/local/bin/g++
ln -s /usr/local/bin/ccache-swig /usr/local/bin/cc
ln -s /usr/local/bin/ccache-swig /usr/local/bin/swig
</pre>
This will work as long as /usr/local/bin comes before the path to gcc
(which is usually in /usr/bin). After installing you may wish to run
"which gcc" to make sure that the correct link is being used.
<p>
Note! Do not use a hard link, use a symbolic link. A hardlink will
cause "interesting" problems.
<p>
<H2><a name="CCache_nn8">17.7 EXTRA OPTIONS</a></H2>
<p>
When run as a compiler front end ccache usually just takes the same
command line options as the compiler you are using. The only exception
to this is the option '--ccache-skip'. That option can be used to tell
ccache that the next option is definitely not a input filename, and
should be passed along to the compiler as-is.
<p>
The reason this can be important is that ccache does need to parse the
command line and determine what is an input filename and what is a
compiler option, as it needs the input filename to determine the name
of the resulting object file (among other things). The heuristic
ccache uses in this parse is that any string on the command line that
exists as a file is treated as an input file name (usually a C
file). By using --ccache-skip you can force an option to not be
treated as an input file name and instead be passed along to the
compiler as a command line option.
<p>
<H2><a name="CCache_nn9">17.8 ENVIRONMENT VARIABLES</a></H2>
<p>
ccache uses a number of environment variables to control operation. In
most cases you won't need any of these as the defaults will be fine.
<p>
<dl>
<p>
<p><dt><strong><strong>CCACHE_DIR</strong></strong><dd> the CCACHE_DIR environment variable specifies
where ccache will keep its cached compiler output. The default is
"$HOME/.ccache".
<p>
<p><dt><strong><strong>CCACHE_TEMPDIR</strong></strong><dd> the CCACHE_TEMPDIR environment variable specifies
where ccache will put temporary files. The default is the same as
CCACHE_DIR. Note that the CCACHE_TEMPDIR path must be on the same
filesystem as the CCACHE_DIR path, so that renames of files between
the two directories can work.
<p>
<p><dt><strong><strong>CCACHE_LOGFILE</strong></strong><dd> If you set the CCACHE_LOGFILE environment
variable then ccache will write some log information on cache hits
and misses in that file. This is useful for tracking down problems.
<p>
<p><dt><strong><strong>CCACHE_VERBOSE</strong></strong><dd> If you set the CCACHE_VERBOSE environment
variable then ccache will display on stdout all the compiler invocations
that it makes. This can useful for debugging unexpected problems.
<p>
<p><dt><strong><strong>CCACHE_PATH</strong></strong><dd> You can optionally set CCACHE_PATH to a colon
separated path where ccache will look for the real compilers. If you
don't do this then ccache will look for the first executable matching
the compiler name in the normal PATH that isn't a symbolic link to
ccache itself.
<p>
<p><dt><strong><strong>CCACHE_CC</strong></strong><dd> You can optionally set CCACHE_CC to force the name
of the compiler to use. If you don't do this then ccache works it out
from the command line.
<p>
<p><dt><strong><strong>CCACHE_PREFIX</strong></strong><dd> This option adds a prefix to the command line
that ccache runs when invoking the compiler. Also see the section
below on using ccache with distcc.
<p>
<p><dt><strong><strong>CCACHE_DISABLE</strong></strong><dd> If you set the environment variable
CCACHE_DISABLE then ccache will just call the real compiler,
bypassing the cache completely.
<p>
<p><dt><strong><strong>CCACHE_READONLY</strong></strong><dd> the CCACHE_READONLY environment variable
tells ccache to attempt to use existing cached object files, but not
to try to add anything new to the cache. If you are using this because
your CCACHE_DIR is read-only, then you may find that you also need to
set CCACHE_TEMPDIR as otherwise ccache will fail to create the
temporary files.
<p>
<p><dt><strong><strong>CCACHE_CPP2</strong></strong><dd> If you set the environment variable CCACHE_CPP2
then ccache will not use the optimisation of avoiding the 2nd call to
the pre-processor by compiling the pre-processed output that was used
for finding the hash in the case of a cache miss. This is primarily a
debugging option, although it is possible that some unusual compilers
will have problems with the intermediate filename extensions used in
this optimisation, in which case this option could allow ccache to be
used.
<p>
<p><dt><strong><strong>CCACHE_NOCOMPRESS</strong></strong><dd> If you set the environment variable
CCACHE_NOCOMPRESS then there is no compression used on files that go
into the cache. However, this setting has no effect on how files are
retrieved from the cache, compressed results will still be usable.
<p>
<p><dt><strong><strong>CCACHE_NOSTATS</strong></strong><dd> If you set the environment variable
CCACHE_NOSTATS then ccache will not update the statistics files on
each compile.
<p>
<p><dt><strong><strong>CCACHE_NLEVELS</strong></strong><dd> The environment variable CCACHE_NLEVELS allows
you to choose the number of levels of hash in the cache directory. The
default is 2. The minimum is 1 and the maximum is 8.
<p>
<p><dt><strong><strong>CCACHE_HARDLINK</strong></strong><dd> If you set the environment variable
CCACHE_HARDLINK then ccache will attempt to use hard links from the
cache directory when creating the compiler output rather than using a
file copy. Using hard links is faster, but can confuse programs like
'make' that rely on modification times. Hard links are never made for
compressed cache files.
<p>
<p><dt><strong><strong>CCACHE_RECACHE</strong></strong><dd> This forces ccache to not use any cached
results, even if it finds them. New results are still cached, but
existing cache entries are ignored.
<p>
<p><dt><strong><strong>CCACHE_UMASK</strong></strong><dd> This sets the umask for ccache and all child
processes (such as the compiler). This is mostly useful when you wish
to share your cache with other users. Note that this also affects the
file permissions set on the object files created from your
compilations.
<p>
<p><dt><strong><strong>CCACHE_HASHDIR</strong></strong><dd> This tells ccache to hash the current working
directory when calculating the hash that is used to distinguish two
compiles. This prevents a problem with the storage of the current
working directory in the debug info of a object file, which can lead
ccache to give a cached object file that has the working directory in
the debug info set incorrectly. This option is off by default as the
incorrect setting of this debug info rarely causes problems. If you
strike problems with gdb not using the correct directory then enable
this option.
<p>
<p><dt><strong><strong>CCACHE_UNIFY</strong></strong><dd> If you set the environment variable CCACHE_UNIFY
then ccache will use the C/C++ unifier when hashing the pre-processor
output if -g is not used in the compile. The unifier is slower than a
normal hash, so setting this environment variable loses a little bit
of speed, but it means that ccache can take advantage of not
recompiling when the changes to the source code consist of
reformatting only. Note that using CCACHE_UNIFY changes the hash, so
cached compiles with CCACHE_UNIFY set cannot be used when
CCACHE_UNIFY is not set and vice versa. The reason the unifier is off
by default is that it can give incorrect line number information in
compiler warning messages.
<p>
<p><dt><strong><strong>CCACHE_EXTENSION</strong></strong><dd> Normally ccache tries to automatically
determine the extension to use for intermediate C pre-processor files
based on the type of file being compiled. Unfortunately this sometimes
doesn't work, for example when using the aCC compiler on HP-UX. On
systems like this you can use the CCACHE_EXTENSION option to override
the default. On HP-UX set this environment variable to "i" if you use
the aCC compiler.
<p>
<p><dt><strong><strong>CCACHE_STRIPC</strong></strong><dd> If you set the environment variable
CCACHE_STRIPC then ccache will strip the -c option when invoking
the preprocessor. This option is primarily for the Sun Workshop
C++ compiler as without this option an unwarranted warning is displayed:
CC: Warning: "-E" redefines product from "object" to "source (stdout)"
when -E and -c is used together.
<p>
<p><dt><strong><strong>CCACHE_SWIG</strong></strong><dd> When using SWIG as the compiler and it does not
have 'swig' in the executable name, then the CCACHE_SWIG environment
variable needs to be set in order for ccache to work correctly with
SWIG. The use of CCACHE_CPP2 is also recommended for SWIG due to some
preprocessor quirks, however, use of CCACHE_CPP2 can often be skipped
-- check your generated code with and without this option set. Known
problems are using preprocessor directives within %inline blocks and
the use of '#pragma SWIG'.
<p>
</dl>
<p>
<H2><a name="CCache_nn10">17.9 CACHE SIZE MANAGEMENT</a></H2>
<p>
By default ccache has a one gigabyte limit on the cache size and no
maximum number of files. You can set a different limit using the
"ccache -M" and "ccache -F" options, which set the size and number of
files limits.
<p>
When these limits are reached ccache will reduce the cache to 20%
below the numbers you specified in order to avoid doing the cache
clean operation too often.
<p>
<H2><a name="CCache_nn11">17.10 CACHE COMPRESSION</a></H2>
<p>
By default on most platforms ccache will compress all files it puts
into the cache
using the zlib compression. While this involves a negligible
performance slowdown, it significantly increases the number of files
that fit in the cache. You can turn off compression setting the
CCACHE_NOCOMPRESS environment variable.
<p>
<H2><a name="CCache_nn12">17.11 HOW IT WORKS</a></H2>
<p>
The basic idea is to detect when you are compiling exactly the same
code a 2nd time and use the previously compiled output. You detect
that it is the same code by forming a hash of:
<p>
<ul>
<li> the pre-processor output from running the compiler with -E
<li> the command line options
<li> the real compilers size and modification time
<li> any stderr output generated by the compiler
</ul>
<p>
These are hashed using md4 (a strong hash) and a cache file is formed
based on that hash result. When the same compilation is done a second
time ccache is able to supply the correct compiler output (including
all warnings etc) from the cache.
<p>
ccache has been carefully written to always produce exactly the same
compiler output that you would get without the cache. If you ever
discover a case where ccache changes the output of your compiler then
please let me know.
<p>
<H2><a name="CCache_nn13">17.12 USING CCACHE WITH DISTCC</a></H2>
<p>
distcc is a very useful program for distributing compilation across a
range of compiler servers. It is often useful to combine distcc with
ccache, so that compiles that are done are sped up by distcc, but that
ccache avoids the compile completely where possible.
<p>
To use distcc with ccache I recommend using the CCACHE_PREFIX
option. You just need to set the environment variable CCACHE_PREFIX to
'distcc' and ccache will prefix the command line used with the
compiler with the command 'distcc'.
<p>
<H2><a name="CCache_nn14">17.13 SHARING A CACHE</a></H2>
<p>
A group of developers can increase the cache hit rate by sharing a
cache directory. The hard links however cause unwanted side effects,
as all links to a cached file share the file's modification timestamp.
This results in false dependencies to be triggered by timestamp-based
build systems whenever another user links to an existing
file. Typically, users will see that their libraries and binaries are
relinked without reason. To share a cache without side effects, the
following conditions need to be met:
<p>
<ul>
<li> Use the same <strong>CCACHE_DIR</strong> environment variable setting
<li> Unset the <strong>CCACHE_HARDLINK</strong> environment variable
<li> Make sure everyone sets the CCACHE_UMASK environment variable
to 002, this ensures that cached files are accessible to everyone in
the group.
<li> Make sure that all users have write permission in the entire
cache directory (and that you trust all users of the shared cache).
<li> Make sure that the setgid bit is set on all directories in the
cache. This tells the filesystem to inherit group ownership for new
directories. The command "chmod g+s `find $CCACHE_DIR -type d`" might
be useful for this.
<li> Set <strong>CCACHE_NOCOMPRESS</strong> for all users, if there are users with
versions of ccache that do not support compression.
</ul>
<p>
<H2><a name="CCache_nn15">17.14 HISTORY</a></H2>
<p>
ccache was inspired by the compilercache shell script script written
by Erik Thiele and I would like to thank him for an excellent piece of
work. See
<a href="http://www.erikyyy.de/compilercache/">http://www.erikyyy.de/compilercache/</a>
for the Erik's scripts.
ccache-swig is a port of the original ccache with support added for use
with SWIG.
<p>
I wrote ccache because I wanted to get a bit more speed out of a
compiler cache and I wanted to remove some of the limitations of the
shell-script version.
<p>
<H2><a name="CCache_nn16">17.15 DIFFERENCES FROM COMPILERCACHE</a></H2>
<p>
The biggest differences between Erik's compilercache script and ccache
are:
<ul>
<li> ccache is written in C, which makes it a bit faster (calling out to
external programs is mostly what slowed down the scripts).
<li> ccache can automatically find the real compiler
<li> ccache keeps statistics on hits/misses
<li> ccache can do automatic cache management
<li> ccache can cache compiler output that includes warnings. In many
cases this gives ccache a much higher cache hit rate.
<li> ccache can handle a much wider ranger of compiler options
<li> ccache avoids a double call to cpp on a cache miss
</ul>
<p>
<H2><a name="CCache_nn17">17.16 CREDITS</a></H2>
<p>
Thanks to the following people for their contributions to ccache
<ul>
<li> Erik Thiele for the original compilercache script
<li> Luciano Rocha for the idea of compiling the pre-processor output
to avoid a 2nd cpp pass
<li> Paul Russell for many suggestions and the debian packaging
</ul>
<p>
<H2><a name="CCache_nn18">17.17 AUTHOR</a></H2>
<p>
ccache was written by Andrew Tridgell
<a href="http://samba.org/~tridge/">http://samba.org/~tridge/</a>.
ccache was adapted to create ccache-swig for use with SWIG by William Fulton.
<p>
If you wish to report a problem or make a suggestion then please email
the SWIG developers on the swig-devel mailing list, see
<a href="http://www.swig.org/mail.html">http://www.swig.org/mail.html</a>
<p>
ccache is released under the GNU General Public License version 2 or
later. Please see the file COPYING for license details.
<p>
</body>
</html>

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,597 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>SWIG and Chicken</title>
<link rel="stylesheet" type="text/css" href="style.css">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body bgcolor="#ffffff">
<H1><a name="Chicken">21 SWIG and Chicken</a></H1>
<!-- INDEX -->
<div class="sectiontoc">
<ul>
<li><a href="#Chicken_nn2">Preliminaries</a>
<ul>
<li><a href="#Chicken_nn3">Running SWIG in C mode</a>
<li><a href="#Chicken_nn4">Running SWIG in C++ mode</a>
</ul>
<li><a href="#Chicken_nn5">Code Generation</a>
<ul>
<li><a href="#Chicken_nn6">Naming Conventions</a>
<li><a href="#Chicken_nn7">Modules</a>
<li><a href="#Chicken_nn8">Constants and Variables</a>
<li><a href="#Chicken_nn9">Functions</a>
<li><a href="#Chicken_nn10">Exceptions</a>
</ul>
<li><a href="#Chicken_nn11">TinyCLOS</a>
<li><a href="#Chicken_nn12">Linkage</a>
<ul>
<li><a href="#Chicken_nn13">Static binary or shared library linked at compile time</a>
<li><a href="#Chicken_nn14">Building chicken extension libraries</a>
<li><a href="#Chicken_nn15">Linking multiple SWIG modules with TinyCLOS</a>
</ul>
<li><a href="#Chicken_nn16">Typemaps</a>
<li><a href="#Chicken_nn17">Pointers</a>
<ul>
<li><a href="#Chicken_collection">Garbage collection</a>
</ul>
<li><a href="#Chicken_nn18">Unsupported features and known problems</a>
<ul>
<li><a href="#Chicken_nn19">TinyCLOS problems with Chicken version &lt;= 1.92</a>
</ul>
</ul>
</div>
<!-- INDEX -->
<p>
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 <i>Revised^5 Report on Scheme</i>. Its main
attributes are that it
</p>
<ol>
<li>generates portable C code</li>
<li>includes a customizable interpreter</li>
<li>links to C libraries with a simple Foreign Function Interface</li>
<li>supports full tail-recursion and first-class continuations</li>
</ol>
<p>
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
<strong>support for C++</strong> -- object-oriented code is
difficult to wrap by hand in CHICKEN -- and its <strong>typed
pointer representation</strong>, essential for C and C++
libraries involving structures or classes.
</p>
<H2><a name="Chicken_nn2">21.1 Preliminaries</a></H2>
<p>
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
<strong>greater than or equal to 1.89</strong>.
To use a chicken version between 1.40 and 1.89, see the <a href="#Chicken_collection">Garbage collection</a>
section below.
</p>
<p>
You may want to look at any of the examples in Examples/chicken/
directory for the basic steps to run SWIG CHICKEN.
</p>
<H3><a name="Chicken_nn3">21.1.1 Running SWIG in C mode</a></H3>
<p>
To run SWIG CHICKEN in C mode, use
the -chicken option.
</p>
<div class="shell">
<pre>% swig -chicken example.i</pre>
</div>
<p>
To allow the wrapper to take advantage of future CHICKEN code
generation improvements, part of the wrapper is direct CHICKEN
function calls (<tt>example_wrap.c</tt>) and part is CHICKEN
Scheme (<tt>example.scm</tt>). 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 <tt>csc</tt>.
</p>
<div class="shell">
<pre>
% chicken example.scm -output-file oexample.c
</pre>
</div>
<p>
So for the C mode of SWIG CHICKEN, <tt>example_wrap.c</tt> and
<tt>oexample.c</tt> are the files that must be compiled to
object files and linked into your project.
</p>
<H3><a name="Chicken_nn4">21.1.2 Running SWIG in C++ mode</a></H3>
<p>
To run SWIG CHICKEN in C++ mode, use
the -chicken -c++ option.
</p>
<div class="shell">
<pre>% swig -chicken -c++ example.i</pre>
</div>
<p>
This will generate <tt>example_wrap.cxx</tt> and
<tt>example.scm</tt>. 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 <tt>csc</tt>.
</p>
<div class="shell">
<pre>% chicken example.scm -output-file oexample.c</pre>
</div>
<p>
So for the C++ mode of SWIG CHICKEN, <tt>example_wrap.cxx</tt>
and <tt>oexample.c</tt> are the files that must be compiled to
object files and linked into your project.
</p>
<H2><a name="Chicken_nn5">21.2 Code Generation</a></H2>
<H3><a name="Chicken_nn6">21.2.1 Naming Conventions</a></H3>
<p>
Given a C variable, function or constant declaration named
<tt>Foo_Bar</tt>, the declaration will be available
in CHICKEN as an identifier ending with
<tt>Foo-Bar</tt>. That is, an underscore is converted
to a dash.
</p>
<p>
You may control what the CHICKEN identifier will be by using the
<tt>%rename</tt> SWIG directive in the SWIG interface file.
</p>
<H3><a name="Chicken_nn7">21.2.2 Modules</a></H3>
<p>
The name of the module must be declared one of two ways:
<ul>
<li>Placing <tt>%module example</tt> in the SWIG interface
file.</li>
<li>Using <tt>-module example</tt> on the SWIG command
line.</li>
</ul>
<p>
The generated example.scm file then exports <code>(declare (unit modulename))</code>.
If you do not want SWIG to export the <code>(declare (unit modulename))</code>, pass
the -nounit option to SWIG.
<p>
CHICKEN will be able to access the module using the <code>(declare
(uses <i>modulename</i>))</code> CHICKEN Scheme form.
</p>
<H3><a name="Chicken_nn8">21.2.3 Constants and Variables</a></H3>
<p>
Constants may be created using any of the four constructs in
the interface file:
</p>
<ol>
<li><code>#define MYCONSTANT1 ...</code></li>
<li><code>%constant int MYCONSTANT2 = ...</code></li>
<li><code>const int MYCONSTANT3 = ...</code></li>
<li><code>enum { MYCONSTANT4 = ... };</code></li>
</ol>
<p>
In all cases, the constants may be accessed from within CHICKEN
using the form <tt>(MYCONSTANT1)</tt>; that is, the constants
may be accessed using the read-only parameter form.
</p>
<p>
Variables are accessed using the full parameter form.
For example, to set the C variable "int my_variable;", use the
Scheme form <tt>(my-variable 2345)</tt>. To get the C variable,
use <tt>(my-variable)</tt>.
</p>
<p>
The <tt>%feature("constasvar")</tt> 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
<tt>(set! MYCONSTANT1 (MYCONSTANT1))</tt>. See
<a href="Customization.html#Customization_features">Features and the %feature directive</a>
for info on how to apply the %feature.
</p>
<H3><a name="Chicken_nn9">21.2.4 Functions</a></H3>
<p>
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 <tt>(sqrt 2345.0)</tt>. A <code>void</code> return
value will give C_SCHEME_UNDEFINED as a result.
</p>
<p>
A function may return more than one value by using the
<code>OUTPUT</code> specifier (see Lib/chicken/typemaps.i).
They will be returned as multiple values using <code>(values)</code> 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 <code>(call-with-values)</code>.
</p>
<H3><a name="Chicken_nn10">21.2.5 Exceptions</a></H3>
<p>The SWIG chicken module has support for exceptions thrown from
C or C++ code to be caught in scheme.
See <a href="Customization.html#Customization_exception">Exception handling with %exception</a>
for more information about declaring exceptions in the interface file.
</p>
<p>Chicken supports both the <code>SWIG_exception(int code, const char *msg)</code> interface
as well as a <code>SWIG_ThrowException(C_word val)</code> function for throwing exceptions from
inside the %exception blocks. <code>SWIG_exception</code> will throw a list consisting of the code
(as an integer) and the message. Both of these will throw an exception using <code>(abort)</code>,
which can be handled by <code>(handle-exceptions)</code>. See
the Chicken manual on Exceptions
and <a href="http://srfi.schemers.org/srfi-12/srfi-12.html">SFRI-12</a>. Since the exception values are thrown
directly, if <code>(condition-case)</code> is used to catch an exception the exception will come through in the <code>val ()</code> case.
</p>
<p>The following simple module</p>
<div class="code"><pre>
%module exception_test
%inline %{
void test_throw(int i) throws (int) {
if (i == 1) throw 15;
}
%}
</pre></div>
<p>could be run with</p>
<div class="targetlang"><pre>
(handle-exceptions exvar
(if (= exvar 15)
(print "Correct!")
(print "Threw something else " exvar))
(test-throw 1))
</pre></div>
<H2><a name="Chicken_nn11">21.3 TinyCLOS</a></H2>
<p>
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."
</p>
<p>
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.
</p>
<p>
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 &lt;Foo&gt;, and each member variable
is allocated a slot. Member functions are exported as generic functions.
<p>
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:"
<p>
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.
</p>
<H2><a name="Chicken_nn12">21.4 Linkage</a></H2>
<p>
Please refer to <em>CHICKEN - A practical and portable Scheme
system - User's manual</em> for detailed help on how to link
object files to create a CHICKEN Scheme program. Briefly, to
link object files, be sure to add <tt>`chicken-config
-extra-libs -libs`</tt> or <tt>`chicken-config -shared
-extra-libs -libs`</tt>to your linker options. Use the
<tt>-shared</tt> option if you want to create a dynamically
loadable module. You might also want to use the much simpler
<tt>csc</tt> or <tt>csc.bat</tt>.
</p>
<p>Each scheme file that is generated
by SWIG contains <code>(declare (uses <i>modname</i>))</code>. This means that to load the
module from scheme code, the code must include <code>(declare (uses <i>modname</i>))</code>.
</p>
<H3><a name="Chicken_nn13">21.4.1 Static binary or shared library linked at compile time</a></H3>
<p>We can easily use csc to build a static binary.</p>
<div class="shell">
<pre>
$ swig -chicken example.i
$ csc -v example.scm example_impl.c example_wrap.c test_script.scm -o example
$ ./example
</pre>
</div>
<p>Similar to the above, any number of <tt>module.scm</tt> files could be compiled
into a shared library, and then that shared library linked when compiling the
main application.</p>
<div class="shell">
<pre>
$ swig -chicken example.i
$ csc -sv example.scm example_wrap.c example_impl.c -o example.so
</pre>
</div>
<p>The <tt>example.so</tt> file can then linked with <tt>test_script.scm</tt> when it
is compiled, in which case <tt>test_script.scm</tt> must have <code>(declare (uses example))</code>.
Multiple SWIG modules could have been linked into <tt>example.so</tt> and each
one accessed with a <code>(declare (uses ... ))</code>.
</p>
<div class="shell">
<pre>
$ csc -v test_script.scm -lexample
</pre>
</div>
<p>An alternative is that the test_script.scm can have the code <code>(load-library 'example "example.so")</code>,
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 <tt>csi</tt>.
</p>
<H3><a name="Chicken_nn14">21.4.2 Building chicken extension libraries</a></H3>
<p>Building a shared library like in the above section only works if the library
is linked at compile time with a script containing <code>(declare (uses ...))</code> or is
loaded explicitly with <code>(load-library 'example "example.so")</code>. It is
not the format that CHICKEN expects for extension libraries and eggs. The problem is the
<code>(declare (unit <i>modname</i>))</code> inside the <tt>modname.scm</tt> file. There are
two possible solutions to this.</p>
<p>First, SWIG accepts a <tt>-nounit</tt> argument, in which case the <code>(declare (unit <i>modname</i>))</code>
is not generated. Then, the <tt>modname.scm</tt> and <tt>modname_wrap.c</tt> files <b>must</b> be compiled into
their own shared library.</p>
<div class="shell">
<pre>
$ csc -sv modname.scm modname_wrap.c modname_impl.c -o modname.so
</pre>
</div>
<p>This library can then be loaded by scheme code with the <code>(require 'modname)</code> function.
See the
Loading-extension-libraries in the eval unit inside the CHICKEN manual for more information.</p>
<p>Another alternative is to run SWIG normally and create a scheme file that contains <code>(declare (uses <i>modname</i>))</code>
and then compile that file into the shared library as well. For example, inside the <tt>mod_load.scm</tt> file,</p>
<div class="targetlang">
<pre>
(declare (uses mod1))
(declare (uses mod2))
</pre>
</div>
<p>Which would then be compiled with</p>
<div class="shell">
<pre>
$ 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
</pre>
</div>
<p>Then the extension library can be loaded with <code>(require 'mod)</code>. As we can see here,
<tt>mod_load.scm</tt> 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
<code>%import</code></p>
<p>In either method, the files that are compiled into the shared library could also be
packaged into an egg. The <tt>mod1_wrap.c</tt> and <tt>mod2_wrap.c</tt> 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.</p>
<p>See the <tt>Examples/chicken/egg</tt> directory in the SWIG source for an example that builds
two eggs, one using the first method and one using the second method.</p>
<H3><a name="Chicken_nn15">21.4.3 Linking multiple SWIG modules with TinyCLOS</a></H3>
<p>Linking together multiple modules that share type information using the <code>%import</code>
directive while also using <tt>-proxy</tt> is more complicated. For example, if <tt>mod2.i</tt> imports <tt>mod1.i</tt>, then the
<tt>mod2.scm</tt> file contains references to symbols declared in <tt>mod1.scm</tt>,
and thus a <code>(declare (uses <i>mod1</i>))</code> or <code>(require '<i>mod1</i>)</code> must be exported
to the top of <tt>mod2.scm</tt>. By default, when SWIG encounters an <code>%import "modname.i"</code> directive,
it exports <code>(declare (uses <i>modname</i>))</code> into the scm file. This works fine unless mod1 was compiled with
the <tt>-nounit</tt> argument or was compiled into an extension library with other modules under a different name.</p>
<p>One option is to override the automatic generation of <code>(declare (uses mod1))</code>
by passing the <tt>-noclosuses</tt> option to SWIG when compiling <tt>mod2.i</tt>.
SWIG then provides the <code>%insert(closprefix) %{ %}</code> directive. Any scheme code inside that directive is inserted into the
generated .scm file, and if <tt>mod1</tt> was compiled with <tt>-nounit</tt>, the directive should contain <code>(require 'mod1)</code>.
This option allows for mixed loading as well, where some modules are imported with <code>(declare (uses <i>modname</i>))</code>
(which means they were compiled without -nounit) and some are imported with <code>(require 'modname)</code>.</p>
<p>The other option is to use the second idea in the above section. Compile all the modules normally, without any
<code>%insert(closprefix)</code>, <tt>-nounit</tt>, or <tt>-noclosuses</tt>. Then the modules will import each other correctly
with <code>(declare (uses ...))</code>.
To create an extension library or an egg, just create a <tt>module_load.scm</tt> file that <code>(declare (uses ...))</code>
all the modules.</p>
<H2><a name="Chicken_nn16">21.5 Typemaps</a></H2>
<p>
The Chicken module handles all types via typemaps. This information is
read from <code>Lib/chicken/typemaps.i</code> and
<code>Lib/chicken/chicken.swg</code>.
</p>
<H2><a name="Chicken_nn17">21.6 Pointers</a></H2>
<p>
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.
</p>
<p>
To construct a Scheme object from a C pointer, the wrapper code
calls the function
<code>SWIG_NewPointerObj(void *ptr, swig_type_info *type, int owner)</code>,
The function that calls <code>SWIG_NewPointerObj</code> must have a variable declared
<code>C_word *known_space = C_alloc(C_SIZEOF_SWIG_POINTER);</code>
It is ok to call <code>SWIG_NewPointerObj</code> more than once,
just make sure known_space has enough space for all the created pointers.
</p>
<p>
To get the pointer represented by a CHICKEN tagged pointer, the
wrapper code calls the function
<code>SWIG_ConvertPtr(C_word s, void **result, swig_type_info *type, int flags)</code>,
passing a pointer to a struct representing the expected pointer
type. flags is either zero or SWIG_POINTER_DISOWN (see below).
</p>
<H3><a name="Chicken_collection">21.6.1 Garbage collection</a></H3>
<p>If the owner flag passed to <code>SWIG_NewPointerObj</code> is 1, <code>NewPointerObj</code> 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 <code>%newobject</code> directive must be specified for functions whose return values
should be garbage collected. See
<a href="Customization.html#Customization_ownership">Object ownership and %newobject</a> for more information.
</p>
<p>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 <code>DISOWN</code> input typemap.
After applying this typemap (see the <a href="Typemaps.html#Typemaps">Typemaps chapter</a> 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 <code>SWIG_POINTER_DISOWN</code> flag to <code>SWIG_ConvertPtr</code>.
<b>Warning:</b> 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.
</p>
<p>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 <code>-nocollection</code> 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.
</p>
<H2><a name="Chicken_nn18">21.7 Unsupported features and known problems</a></H2>
<ul>
<li>No director support.</li>
<li>No support for c++ standard types like std::vector.</li>
<li>The TinyCLOS wrappers for overloaded functions will not work correctly when using
<a href="SWIGPlus.html#SWIGPlus_default_args">%feature(compactdefaultargs)</a>.</li>
</ul>
<H3><a name="Chicken_nn19">21.7.1 TinyCLOS problems with Chicken version &lt;= 1.92</a></H3>
<p>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</p>
<div class="code">
<pre>
class Foo {};
int foo(int a, Foo *b);
int foo(int a);
</pre></div>
<p>will produce scheme code</p>
<div class="targetlang">
<pre>
(define-method (foo (arg0 &lt;top&gt;) (arg1 &lt;Foo&gt;)) (<i>call primitive function</i>))
(define-method (foo (arg0 &lt;top&gt;)) (<i>call primitive function</i>))
</pre></div>
<p>Using unpatched TinyCLOS, the second <code>(define-method)</code> will replace the first one,
so calling <code>(foo 3 f)</code> will produce an error.</p>
<p>There are three solutions to this. The easist is to upgrade to the latest Chicken version. Otherwise, the
file <tt>Lib/chicken/tinyclos-multi-generic.patch</tt> 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 <tt>Lib/chicken/multi-generic.scm</tt>
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.</p>
</body>
</html>

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,275 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Contract Checking</title>
<link rel="stylesheet" type="text/css" href="style.css">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body bgcolor="#ffffff">
<H1><a name="Contract">13 Contracts</a></H1>
<!-- INDEX -->
<div class="sectiontoc">
<ul>
<li><a href="#Contract_nn2">The %contract directive</a>
<li><a href="#Contract_nn3">%contract and classes</a>
<li><a href="#Contract_nn4">Constant aggregation and %aggregate_check</a>
<li><a href="#Contract_nn5">Notes</a>
</ul>
</div>
<!-- INDEX -->
<p>
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.
</p>
<p>
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.
</p>
<H2><a name="Contract_nn2">13.1 The %contract directive</a></H2>
<p>
Contracts are added to a declaration using the %contract directive. Here
is a simple example:
</p>
<div class="code">
<pre>
%contract sqrt(double x) {
require:
x &gt;= 0;
ensure:
sqrt &gt;= 0;
}
...
double sqrt(double);
</pre>
</div>
<p>
In this case, a contract is being added to the <tt>sqrt()</tt> function.
The <tt>%contract</tt> directive must always appear before the declaration
in question. Within the contract there are two sections, both of which
are optional. The <tt>require:</tt>
section specifies conditions that must hold before the function is called.
Typically, this is used to check argument values. The <tt>ensure:</tt> 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.
</p>
<p>
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).
</p>
<p>
Once a contract has been specified, it modifies the behavior of the
resulting module. For example:
</p>
<div class="shell">
<pre>
&gt;&gt;&gt; example.sqrt(2)
1.4142135623730951
&gt;&gt;&gt; example.sqrt(-2)
Traceback (most recent call last):
File "&lt;stdin&gt;", line 1, in ?
RuntimeError: Contract violation: require: (arg1&gt;=0)
&gt;&gt;&gt;
</pre>
</div>
<H2><a name="Contract_nn3">13.2 %contract and classes</a></H2>
<p>
The <tt>%contract</tt> directive can also be applied to class methods and constructors. For example:
</p>
<div class="code">
<pre>
%contract Foo::bar(int x, int y) {
require:
x &gt; 0;
ensure:
bar &gt; 0;
}
%contract Foo::Foo(int a) {
require:
a &gt; 0;
}
class Foo {
public:
Foo(int);
int bar(int, int);
};
</pre>
</div>
<p>
The way in which <tt>%contract</tt> is applied is exactly the same as the <tt>%feature</tt> directive.
Thus, any contract that you specified for a base class will also be attached to inherited methods. For example:
</p>
<div class="code">
<pre>
class Spam : public Foo {
public:
int bar(int, int); // Gets contract defined for Foo::bar(int, int)
};
</pre>
</div>
<p>
In addition to this, separate contracts can be applied to both the base class and a derived class. For example:
</p>
<div class="code">
<pre>
%contract Foo::bar(int x, int) {
require:
x &gt; 0;
}
%contract Spam::bar(int, int y) {
require:
y &gt; 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
};
</pre>
</div>
<p>
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 <tt>Spam::bar</tt> must be positive.
</p>
<H2><a name="Contract_nn4">13.3 Constant aggregation and %aggregate_check</a></H2>
<p>
Consider an interface file that contains the following code:
</p>
<div class="code">
<pre>
#define UP 1
#define DOWN 2
#define RIGHT 3
#define LEFT 4
void move(SomeObject *, int direction, int distance);
</pre>
</div>
<p>
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:
</p>
<div class="code">
<pre>
%aggregate_check(int, check_direction, UP, DOWN, LEFT, RIGHT);
</pre>
</div>
<p>
This merely defines a utility function of the form
</p>
<div class="code">
<pre>
int check_direction(int x);
</pre>
</div>
<p>
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:
</p>
<div class="code">
<pre>
%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);
</pre>
</div>
<p>
Alternatively, it can be used in typemaps and other directives. For example:
</p>
<div class="code">
<pre>
%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);
</pre>
</div>
<p>
Regrettably, there is no automatic way to perform similar checks with enums values. Maybe in a future
release.
</p>
<H2><a name="Contract_nn5">13.4 Notes</a></H2>
<p>
Contract support was implemented by Songyan (Tiger) Feng and first appeared
in SWIG-1.3.20.
</p>
</body>
</html>

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,458 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>SWIG and D</title>
<link rel="stylesheet" type="text/css" href="style.css">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body bgcolor="#FFFFFF">
<H1><a name="D">22 SWIG and D</a></H1>
<!-- INDEX -->
<div class="sectiontoc">
<ul>
<li><a href="#D_introduction">Introduction</a>
<li><a href="#D_command_line_invocation">Command line invocation</a>
<li><a href="#D_typemaps">Typemaps</a>
<ul>
<li><a href="#D_typemap_name_comparison">C# &lt;-&gt; D name comparison</a>
<li><a href="#D_ctype_imtype_dtype">ctype, imtype, dtype</a>
<li><a href="#D_in_out_directorin_direcetorout">in, out, directorin, directorout</a>
<li><a href="#D_din_dout_ddirectorin_ddirectorout">din, dout, ddirectorin, ddirectorout</a>
<li><a href="#D_typecheck_typemaps">typecheck typemaps</a>
<li><a href="#D_code_injection_typemaps">Code injection typemaps</a>
<li><a href="#D_special_variables">Special variable macros</a>
</ul>
<li><a href="#D_features">D and %feature</a>
<li><a href="#D_pragmas">Pragmas</a>
<li><a href="#D_exceptions">D Exceptions</a>
<li><a href="#D_directors">D Directors</a>
<li><a href="#D_other_features">Other features</a>
<ul>
<li><a href="#D_nspace">Extended namespace support (nspace)</a>
<li><a href="#D_native_pointer_support">Native pointer support</a>
<li><a href="#D_operator_overloading">Operator overloading</a>
<li><a href="#D_test_suite">Running the test-suite</a>
</ul>
<li><a href="#D_typemap_examples">D Typemap examples</a>
<li><a href="#D_planned_features">Work in progress and planned features</a>
</ul>
</div>
<!-- INDEX -->
<H2><a name="D_introduction">22.1 Introduction</a></H2>
<p>From the <a href="http://www.digitalmars.com/d/">D Programming Language</a> web site: <em>D is a systems programming language. Its focus is on combining the power and high performance of C and C++ with the programmer productivity of modern languages like Ruby and Python. [...] The D language is statically typed and compiles directly to machine code.</em> As such, it is not very surprising that D is able to directly <a href="http://www.digitalmars.com/d/1.0/interfaceToC.html">interface with C libraries</a>. Why would a SWIG module for D be needed then in the first place?</p>
<p>Well, besides the obvious downside that the C header files have to be manually converted to D modules for this to work, there is one major inconvenience with this approach: D code usually is on a higher abstraction level than C, and many of the features that make D interesting are simply not available when dealing with C libraries, requiring you e.g. to manually convert strings between pointers to <tt>\0</tt>-terminated char arrays and D char arrays, making the algorithms from the D2 standard library unusable with C arrays and data structures, and so on.</p>
<p>While these issues can be worked around relatively easy by hand-coding a thin wrapper layer around the C library in question, there is another issue where writing wrapper code per hand is not feasible: C++ libraries. D did not support interfacing to C++ in version 1 at all, and even if <tt>extern(C++)</tt> has been added to D2, the support is still very limited, and a custom wrapper layer is still required in many cases. </p>
<p>To help addressing these issues, the SWIG C# module has been forked to support D. Is has evolved quite a lot since then, but there are still many similarities, so if you do not find what you are looking for on this page, it might be worth having a look at the chapter on <a href="CSharp.html#CSharp">C#</a> (and also on <a href="Java.html#Java">Java</a>, since the C# module was in turn forked from it).</p>
<H2><a name="D_command_line_invocation">22.2 Command line invocation</a></H2>
<p>To activate the D module, pass the <tt>-d</tt> option to SWIG at the command line. The same standard command line switches as with any other language module are available, plus the following D specific ones:</p>
<dl>
<dt><tt>-d2</tt></dt>
<dd>
<p>By default, SWIG generates code for D1/Tango. Use the <tt>-d2</tt> flag to target D2/Phobos instead.</p>
</dd>
<dt><a name="D_splitproxy"></a><tt>-splitproxy</tt></dt>
<dd>
<p>By default, SWIG generates two D modules: the <em>proxy</em> module, named like the source module (either specified via the <tt>%module</tt> directive or via the <tt>module</tt> command line switch), which contains all the proxy classes, functions, enums, etc., and the <em>intermediary</em> module (named like the proxy module, but suffixed with <tt>_im</tt>), which contains all the <tt>extern(C)</tt> function declarations and other private parts only used internally by the proxy module.</p>
<p>If the split proxy mode is enabled by passing this switch at the command line, all proxy classes and enums are emitted to their own D module instead. The main proxy module only contains free functions and constants in this case.</p>
</dd>
<dt><tt>-package &lt;pkg&gt;</tt></dt>
<dd>
<p>By default, the proxy D modules and the intermediary D module are written to the root package. Using this option, you can specify another target package instead.</p>
</dd>
<dt><tt>-wrapperlibrary &lt;wl&gt;</tt></dt>
<dd>
<p>The code SWIG generates to dynamically load the C/C++ wrapper layer looks for a library called <tt>$module_wrap</tt> by default. With this switch, you can override the name of the file the wrapper code loads at runtime (the <tt>lib</tt> prefix and the suffix for shared libraries are appended automatically, depending on the OS).</p>
<p>This might especially be useful if you want to invoke SWIG several times on separate modules, but compile the resulting code into a single shared library.</p>
</dd>
</dl>
<H2><a name="D_typemaps">22.3 Typemaps</a></H2>
<H3><a name="D_typemap_name_comparison">22.3.1 C# &lt;-&gt; D name comparison</a></H3>
<p>If you already know the SWIG C# module, you might find the following name comparison table useful:</p>
<div class="diagram"><pre>
ctype &lt;-&gt; ctype
imtype &lt;-&gt; imtype
cstype &lt;-&gt; dtype
csin &lt;-&gt; din
csout &lt;-&gt; dout
csdirectorin &lt;-&gt; ddirectorin
csdirectorout &lt;-&gt; ddirectorout
csinterfaces &lt;-&gt; dinterfaces
csinterfaces_derived &lt;-&gt; dinterfaces_derived
csbase &lt;-&gt; dbase
csclassmodifiers &lt;-&gt; dclassmodifiers
cscode &lt;-&gt; dcode
csimports &lt;-&gt; dimports
csbody &lt;-&gt; dbody
csfinalize &lt;-&gt; ddestructor
csdestruct &lt;-&gt; ddispose
csdestruct_derived &lt;-&gt; ddispose_derived
</pre></div>
<H3><a name="D_ctype_imtype_dtype">22.3.2 ctype, imtype, dtype</a></H3>
<p>Mapping of types between the C/C++ library, the C/C++ library wrapper exposing the C functions, the D wrapper module importing these functions and the D proxy code.</p>
<p>The <tt>ctype</tt> typemap is used to determine the types to use in the C wrapper functions. The types from the <tt>imtype</tt> typemap are used in the extern(C) declarations of these functions in the intermediary D module. The <tt>dtype</tt> typemap contains the D types used in the D proxy module/class.</p>
<H3><a name="D_in_out_directorin_direcetorout">22.3.3 in, out, directorin, directorout</a></H3>
<p>Used for converting between the types for C/C++ and D when generating the code for the wrapper functions (on the C++ side).</p>
<p>The code from the <tt>in</tt> typemap is used to convert arguments to the C wrapper function to the type used in the wrapped code (<tt>ctype</tt>-&gt;original C++ type), the <tt>out</tt> typemap is utilized to convert values from the wrapped code to wrapper function return types (original C++ type-&gt;<tt>ctype</tt>).</p>
<p>The <tt>directorin</tt> typemap is used to convert parameters to the type used in the D director callback function, its return value is processed by <tt>directorout</tt> (see below).</p>
<H3><a name="D_din_dout_ddirectorin_ddirectorout">22.3.4 din, dout, ddirectorin, ddirectorout</a></H3>
<p>Typemaps for code generation in D proxy and type wrapper classes.</p>
<p><a name="D_din"></a>The <tt>din</tt> typemap is used for converting function parameter types from the type used in the proxy module or class to the type used in the intermediary D module (the <a href="D.html#D_dinput">$dinput</a> macro is replaced). To inject further parameter processing code before or after the call to the intermediary layer, the <tt>pre</tt>, <tt>post</tt> and <tt>terminator</tt> attributes can be used (please refer to the <a href="CSharp.html#CSharp_date_marshalling">C# date marshalling example</a> for more information on these).</p>
<p><a name="D_dout"></a>The <tt>dout</tt> typemap is used for converting function return values from the return type used in the intermediary D module to the type returned by the proxy function. The <tt>$excode</tt> special variable in <tt>dout</tt> typemaps is replaced by the <tt>excode</tt> typemap attribute code if the method can throw any exceptions from unmanaged code, otherwise by nothing (the <a href="D.html#D_imcall"><tt>$imcall</tt> and <tt>$owner</tt></a> macros are replaced).</p>
<p><a name="D_ddirectorinout"></a>The code from the <tt>ddirectorin</tt> and <tt>ddirectorout</tt> typemaps is used for conversion in director callback functions. Arguments are converted to the type used in the proxy class method they are calling by using the code from <tt>ddirectorin</tt>, the proxy class method return value is converted to the type the C++ code expects via the <tt>ddirectorout</tt> typemap (the <a href="D.html#D_dpcall"><tt>$dcall</tt> and <tt>$winput</tt></a> macros are replaced).</p>
<p>The full chain of type conversions when a director callback is invoked looks like this:</p>
<div class="diagram"><pre>
type CPPClass::method(type a)
&uarr; &darr;
&lt;directorout&gt; &lt;directorin&gt;
&uarr; &darr;
ctype methodCallback(ctype a) C++
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
imtype methodCallback(imtype a) D
&uarr; &darr;
&lt;ddirectorout&gt; &lt;ddirectorin&gt;
&uarr; &darr;
dtype DClass.method(dtype a)</pre></div>
<H3><a name="D_typecheck_typemaps">22.3.5 typecheck typemaps</a></H3>
<p>Because, unlike many scripting languages supported by SWIG, D does not need any dynamic dispatch helper to access an overloaded function, the purpose of these is merely to issue a warning for overloaded C++ functions that cannot be overloaded in D (as more than one C++ type maps to a single D type).</p>
<H3><a name="D_code_injection_typemaps">22.3.6 Code injection typemaps</a></H3>
<p>These typemaps are used for generating the skeleton of proxy classes for C++ types.</p>
<p>By overriding <tt>dbase</tt>, <tt>dinterfaces</tt> or <tt>dinterfaces_derived</tt>, the inheritance chain of the generated proxy class for a type can be modified. <tt>dclassmodifiers</tt> allows you to add any custom modifiers around the class keyword.</p>
<p>Using <tt>dcode</tt> and <tt>dimports</tt>, you can specify additional D code which will be emitted into the class body respectively the imports section of the D module the class is written to.</p>
<p><a name="D_class_code_typemaps"></a><tt>dconstructor</tt>, <tt>ddestructor</tt>, <tt>ddispose</tt> and <tt>ddispose_derived</tt> are used to generate the class constructor, destructor and <tt>dispose()</tt> method, respectively. The auxiliary code for handling the pointer to the C++ object is stored in <tt>dbody</tt> and <tt>dbody_derived</tt>. You can override them for specific types.</p>
<p>
Code can also be injected into the D proxy class using <tt>%proxycode</tt>.
</p>
<H3><a name="D_special_variables">22.3.7 Special variable macros</a></H3>
<p>The standard SWIG special variables are available for use within typemaps as described in the <a href="Typemaps.html#Typemaps">Typemaps documentation</a>, for example <tt>$1</tt>, <tt>$input</tt>, <tt>$result</tt> etc.</p>
<p>When generating D wrappers, a few additional macros are available:</p>
<dl>
<dt><tt>$dclassname</tt> (C#: <tt>$csclassname</tt>)</dt>
<dd>
<p>This special variable works similar to <a href="Typemaps.html#Typemaps_special_variables"><tt>$n_type</tt></a> in that it returns the name of a type - it expands to the D proxy class name of the type being wrapped. If the type does not have an associated proxy class, it expands to the type wrapper class name, for example, <tt>SWIGTYPE_p_p_SomeCppClass</tt> is generated when wrapping <tt>SomeCppClass **</tt>.</p>
<p>There are two other variants available, <tt>$&amp;dclassname</tt> and <tt>$*dclassname</tt>. The former adds a level of indirection, while the latter removes one. For instance, when wrapping <tt>Foo **</tt>, <tt>$*dclassname</tt> would be replaced by the proxy class name corresponding to <tt>Foo *</tt>.</p>
</dd>
<dt><tt>$dclazzname</tt> (C#: <tt>$csclazzname</tt>)</dt>
<dd>
<p>This special variable expands the fully qualified C++ class into the package name, if used by the <a href="SWIGPlus.html#SWIGPlus_nspace"><tt>nspace</tt> feature</a>, and the proxy class name, mangled for use as a function name. For example, <tt>Namespace1::Namespace2::Klass</tt> is expanded into <tt>Namespace1_Namespace2_Klass_</tt>.</p>
<p>This special variable might be useful for calling certain functions in the wrapper layer (e.g. upcast wrappers) which are mangled like this.</p>
</dd>
<dt><tt>$null</tt></dt>
<dd><p>In code inserted into the generated C/C++ wrapper functions, this variable is replaced by either <tt>0</tt> or nothing at all, depending on whether the function has a return value or not. It can be used to bail out early e.g. in case of errors (<tt>return $null;</tt>).</p></dd>
<dt><a name="D_dinput"></a><tt>$dinput</tt> (C#: <tt>$csinput</tt>)</dt>
<dd>
<p>This variable is used in <tt><a href="D.html#D_din">din</a></tt> typemaps and is replaced by the expression which is to be passed to C/C++.</p>
<p>For example, this input</p>
<div class="code"><pre>
%typemap(din) SomeClass * "SomeClass.getCPointer($dinput)"
%inline %{
class SomeClass {};
void foo(SomeClass *arg);
%}</pre></div>
<p>leads to the following D proxy code being generated:</p>
<div class="targetlang"><pre>
void foo(SomeClass arg) {
example_im.foo(SomeClass.getCPointer(arg));
}</pre></div></dd>
<dt><a name="D_imcall"></a><tt>$imcall</tt> and <tt>$owner</tt> (C#: <tt>$imcall</tt>)</dt>
<dd>
<p>These variables are used in <tt><a href="D.html#D_dout">dout</a></tt> typemaps. <tt>$imcall</tt> contains the call to the intermediary module which provides the value to be used, and <tt>$owner</tt> signals if the caller is responsible for managing the object lifetime (that is, if the called method is a constructor or has been marked via <tt>%newobject</tt>).</p>
<p>Consider the following example:</p>
<div class="code"><pre>
%typemap(dout) SomeClass * {
return new SomeClass($imcall, $owner);
}
%inline %{
class SomeClass;
SomeClass *foo();
%newobject bar();
SomeClass *bar();
%}
</pre></div>
<p>The code generated for <tt>foo()</tt> and <tt>bar()</tt> looks like this:</p>
<div class="targetlang"><pre>
SomeClass foo() {
return new SomeClass(example_im.foo(), false);
}
SomeClass bar() {
return new SomeClass(example_im.bar(), true);
}
</pre></div>
</dd>
<dt><tt>$dcall</tt> and <tt>$winput</tt> (C#: <tt>$cscall</tt>, <tt>$iminput</tt>)</dt>
<dd><a name="D_dpcall"></a><p>These variables are used in the director-specific typemaps <a href="D.html#D_ddirectorinout"><tt>ddirectorin</tt></a> and <a href="D.html#D_ddirectorinout"><tt>ddirectorout</tt></a>. They are more or less the reverse of the <tt>$imcall</tt> and <tt>$dinput</tt> macros: <tt>$dcall</tt> contains the invocation of the D proxy method of which the return value is to be passed back to C++, <tt>$winput</tt> contains the parameter value from C++.</p></dd>
<dt><tt>$excode</tt></dt>
<dd><p>This variable is used in <tt>dout</tt> and <tt>dconstructor</tt> typemaps and is filled with the contents of the <tt>excode</tt> typemap attribute if an exception could be thrown from the C++ side. See the <a href="CSharp.html#CSharp_exceptions">C# documentation</a> for details.</p></dd>
<dt><tt>$dbaseclass</tt></dt>
<dd><p>Currently for internal use only, it contains the D name of the C++ base class (if any) inside proxy classes.</p></dd>
<dt><tt>$directorconnect</tt></dt>
<dd>
<p>This macro is only valid inside the <tt><a href="D.html#D_class_code_typemaps">dconstructor</a></tt> typemap and contains the value of the <tt>dconstructor</tt> typemap attribute if the currently wrapped class has directors enabled.</p>
<p>This is how the default <tt>dconstructor</tt> typemap looks like (you usually do not want to specify a custom one):</p>
<div class="code"><pre>
%typemap(dconstructor, excode=SWIGEXCODE,
directorconnect="\n swigDirectorConnect();") SWIGTYPE {
this($imcall, true);$excode$directorconnect
}
</pre></div>
</dd>
<dt><a name="D_importtype"></a><tt>$importtype(SomeDType)</tt></dt>
<dd>
<p>This macro is used in the <tt>dimports</tt> typemap if a dependency on another D type generated by SWIG is added by a custom typemap.</p>
<p>Consider the following code snippet:</p>
<div class="code"><pre>
%typemap(dinterfaces) SomeClass "AnInterface, AnotherInterface";
</pre></div>
<p>This causes SWIG to add <tt>AnInterface</tt> and <tt>AnotherInterface</tt> to the base class list of <tt>SomeClass</tt>:</p>
<div class="targetlang"><pre>
class SomeClass : AnInterface, AnotherInterface {
...
}
</pre></div>
<p>For this to work, <tt>AnInterface</tt> and <tt>AnotherInterface</tt> have to be in scope. If SWIG is not in split proxy mode, this is already the case, but it it is, they have to be added to the import list via the <tt>dimports</tt> typemap. Additionally, the import statement depends on the package SWIG is configured to emit the modules to.</p>
<p>The <tt>$importtype</tt> macro helps you to elegantly solve this problem:</p>
<div class="code"><pre>
%typemap(dimports) RemoteMpe %{
$importtype(AnInterface)
$importtype(AnotherInterface)
%}
</pre></div>
<p>If SWIG is in split proxy mode, it expands to an <tt>import</tt> statement for the specified type, to nothing if not.</p>
</dd>
<dt><tt>$module</tt></dt>
<dd><p>Expands to the name of the main proxy D module.</p></dd>
<dt><tt>$imdmodule</tt></dt>
<dd><p>Contains the fully qualified name of the intermediary D module.</p></dd>
</dl>
<H2><a name="D_features">22.4 D and %feature</a></H2>
<p>The D module defines a number of directives which modify the <a href="Customization.html#Customization_features">SWIG features</a> set globally or for a specific declaration:</p>
<dl>
<dt><tt>%dmanifestconst</tt> and <tt>%dconstvalue(value)</tt></dt>
<dd>
<p>Out of the box, SWIG generates accessor methods for C <tt>#defines</tt> and C++ constants. The <tt>%dmanifestconst</tt> directive enables wrapping these constants as D manifest constants (<tt>const</tt> in D1, <tt>enum</tt> in D2).</p>
<p>For this to work, the C/C++ code for the constant value must directly compile as D code, though. If this is not the case, you can manually override the expression written to the D proxy module using the <tt>%dconstvalue</tt> directive, passing the new value as parameter.</p>
<p>For <tt>enum</tt>s, again <tt>%dconstvalue</tt> can be used to override the value of an enum item if the initializer should not compile in D.</p>
</dd>
<dt><tt>%dmethodmodifiers</tt></dt>
<dd>
<p>This directive can be used to override the modifiers for a proxy function. For instance, you could make a <tt>public</tt> C++ member function <tt>private</tt> in D like this:</p>
<div class="code"><pre>
%dmethodmodifiers A::foo "private";
%inline %{
struct A {
void foo();
};
%}
</pre></div>
</dd>
</dl>
<H2><a name="D_pragmas">22.5 Pragmas</a></H2>
<p>There are a few SWIG pragmas specific to the D module, which you can use to influence the D code SWIG generates:</p>
<dl>
<dt><tt>%pragma(d) imdmodulecode</tt></dt>
<dd><p>The passed text (D code) is copied verbatim to the intermediary D module. For example, it can be (and is, internally) used to emit additional private helper code for the use by proxy typemaps.</p></dd>
<dt><tt>%pragma(d) imdmoduleimports</tt></dt>
<dd><p>Additional code to be emitted to the imports section of the intermediary D module (the <a href="D.html#D_importtype">$importtype</a> macro can be used here). You probably want to use this in conjunction with the <tt>imdmodulecode</tt> pragma.</p></dd>
<dt><tt>%pragma(d) proxydmodulecode</tt></dt>
<dd><p>Just like <tt>proxydmodulecode</tt>, the argument is copied to the proxy D module (if SWIG is in <a href="D.html#D_splitproxy">split proxy mode</a> and/or the <tt>nspace</tt> feature is used, it is emitted to the main proxy D module only).</p></dd>
<dt><tt>%pragma(d) globalproxyimports</tt></dt>
<dd>
<p>The D module currently does not support specifying dependencies on external modules (e.g. from the standard library) for the D typemaps. To add the import statements to the proxy modules (resp. to <em>all</em> proxy modules if in split proxy mode), you can use the <tt>globalproxyimports</tt> directive.</p>
<p>For example:</p>
<div class="code"><pre>
%typemap(din) char[] "($dinput ? tango.stdc.stringz.toStringz($dinput) : null)"
%pragma(d) globalproxyimports = "static import tango.stdc.stringz;";
</pre></div>
</dd>
<dt><tt>%pragma(d) wrapperloadercode</tt></dt>
<dd>
<p>The D code for loading the wrapper library (it is copied to the intermediary D module). The <tt>$wrapperloaderbindcode</tt> variable is replaced by the list of commands for binding the functions from the wrapper library to the symbols in the intermediary D module.</p>
<p>Each time this pragma is specified, the previous value is overwritten.</p>
</dd>
<dt><tt>%pragma(d) wrapperloaderbindcommand</tt></dt>
<dd>
<p>The D command to use for binding the wrapper functions from the C/C++ library to the symbols in the intermediary D module. The <tt>$function</tt> variable contains the name of the D function in the wrap module, the <tt>$symbol</tt> variable is replaced by the name of the symbol in the library.</p>
<p>Each time this pragma is specified, the previous value is overwritten.</p>
</dd>
</dl>
<H2><a name="D_exceptions">22.6 D Exceptions</a></H2>
<p>Out of the box, C++ exceptions are fundamentally incompatible to their equivalent in the D world and cannot simply be propagated to a calling D method. There is, however, an easy way to solve this problem: Just catch the exception in the C/C++ wrapper layer, pass the contents to D, and make the wrapper code rethrow the exception in the D world.</p>
<p>The implementation details of this are a bit crude, but the SWIG D module automatically takes care of this, as long as it is able to detect that an exception could potentially be thrown (e.g. because the C++ method has a <tt>throw(...)</tt> exception specification).</p>
<p>As this feature is implemented in exactly the same way it is for C#, please see the <a href="CSharp.html#CSharp_exceptions">C# documentation</a> for a more detailed explanation.</p>
<H2><a name="D_directors">22.7 D Directors</a></H2>
<p>When the directors feature is activated, SWIG generates extra code on both the C++ and the D side to enable cross-language polymorphism. Essentially, this means that if you subclass a proxy class in D, C++ code can access any overridden virtual methods just as if you created a derived class in C++.</p>
<p>There is no D specific documentation yet, but the way the feature is implemented is very similar to how it is done in <a href="Java.html#Java_directors">Java</a> and <a href="CSharp.html#CSharp_directors">C#</a>.
</p>
<H2><a name="D_other_features">22.8 Other features</a></H2>
<H3><a name="D_nspace">22.8.1 Extended namespace support (nspace)</a></H3>
<p>By default, SWIG flattens all C++ namespaces into a single target language namespace, but as for Java and C#, the <a href="SWIGPlus.html#SWIGPlus_nspace"><tt>nspace</tt></a> feature is supported for D. If it is active, C++ namespaces are mapped to D packages/modules. Note, however, that like for the other languages, <em>free</em> variables and functions are not supported yet; currently, they are all allows written to the main proxy D module.</p>
<H3><a name="D_native_pointer_support">22.8.2 Native pointer support</a></H3>
<p>Contrary to many of the scripting languages supported by SWIG, D fully supports C-style pointers. The D module thus includes a custom mechanism to wrap C pointers directly as D pointers where applicable, that is, if the type that is pointed to is represented the same in C and D (on the bit-level), dubbed a <em>primitive type</em> below.</p>
<p>Central to this custom pointer handling scheme are two typemap attributes: the <tt>cprimitive</tt> attribute on the <tt>dtype</tt> typemap and the <tt>nativepointer</tt> attribute on all the typemaps which influence the D side of the code (<tt>dtype</tt>, <tt>din</tt>, <tt>dout</tt>, ...). When a D typemap is looked up, the following happens behind the scenes:</p>
<p>First, the matching typemap is determined by the usual typemap lookup rules. Then, it is checked if the result has the <tt>nativepointer</tt> attribute set. If it is present, it means that its value should replace the typemap value <em>if and only if</em> the actual type the typemap is looked up for is a primitive type, a pointer to a primitive type (through an arbitrary level of indirections), or a function pointer with only primitive types in its signature.</p>
<p>To determine if a type should be considered primitive, the <tt>cprimitive</tt> attribute on its <tt>dtype</tt> attribute is used. For example, the <tt>dtype</tt> typemap for <tt>float</tt> has <tt>cprimitive="1"</tt>, so the code from the <tt>nativepointer</tt> attribute is taken into account e.g. for <tt>float **</tt> or the function pointer <tt>float (*)(float *)</tt>.</p>
<H3><a name="D_operator_overloading">22.8.3 Operator overloading</a></H3>
<p>The D module comes with basic operator overloading support for both D1 and D2. There are, however, a few limitations arising from conceptual differences between C++ and D:</p>
<p>The first key difference is that C++ supports free functions as operators (along with argument-dependent lookup), while D requires operators to be member functions of the class they are operating on. SWIG can only automatically generate wrapping code for member function operators; if you want to use operators defined as free functions in D, you need to handle them manually.</p>
<p>Another set of differences between C++ and D concerns individual operators. For example, there are quite a few operators which are overloadable in C++, but not in D, for example <tt>&amp;&amp;</tt> and <tt>||</tt>, but also <tt>!</tt>, and prefix increment/decrement operators in <a href="http://www.digitalmars.com/d/1.0/operatoroverloading.html">D1</a> resp. their postfix pendants in <a href="http://www.digitalmars.com/d/2.0/operatoroverloading.html">D2</a>.</p>
<p>There are also some cases where the operators can be translated to D, but the differences in the implementation details are big enough that a rather involved scheme would be required for automatic wrapping them, which has not been implemented yet. This affects, for example, the array subscript operator, <tt>[]</tt>, in combination with assignments - while <tt>operator []</tt> in C++ simply returns a reference which is then written to, D resorts to a separate <tt>opIndexAssign</tt> method -, or implicit casting (which was introduced in D2 via <tt>alias this</tt>). Despite the lack of automatic support, manually handling these cases should be perfectly possible.</p>
<H3><a name="D_test_suite">22.8.4 Running the test-suite</a></H3>
<p>As with any other language, the SWIG test-suite can be built for D using the <tt>*-d-test-suite</tt> targets of the top-level Makefile. By default, D1 is targeted, to build it with D2, use the optional <tt>D_VERSION</tt> variable, e.g. <tt>make check-d-test-suite D_VERSION=2</tt>.</p>
<p>Note: If you want to use GDC on Linux or another platform which requires you to link <tt>libdl</tt> for dynamically loading the shared library, you might have to add <tt>-ldl</tt> manually to the <tt>d_compile</tt> target in <tt>Examples/Makefile</tt>, because GDC does not currently honor the <tt>pragma(lib, ...)</tt> statement.</p>
<H2><a name="D_typemap_examples">22.9 D Typemap examples</a></H2>
<p>There are no D-specific typemap examples yet. However, with the above <a href="D.html#D_typemap_name_comparison">name comparison table</a>, you should be able to get an idea what can be done by looking at the <a href="CSharp.html#CSharp_typemap_examples">corresponding C# section</a>.</p>
<H2><a name="D_planned_features">22.10 Work in progress and planned features</a></H2>
<p>There are a couple of features which are not implemented yet, but would be very useful and might be added in the near future:</p>
<ul>
<li><em>Static linking:</em> Currently, the C wrapper code is compiled into a dynamic library, out of which the symbol addresses are looked up at runtime by the D part. If statically linking the different languages into one binary was supported, a tool-chain capable of performing IPO at link time could inline the wrapping code, effectively reducing the overhead for simple calls to zero.</li>
<li><em>C array handling:</em> Many data structures in some C/C++ libraries contain array containing of a pointer to the first element and the element count. Currently, one must manually writing wrapper code to be able to access these from D. It should be possible to add a set of SWIG macros to semi-automatically generate conversion code.</li>
</ul>
<p>Some generated code might also be a bit rough around the edges, particularly in the following areas:</p>
<ul>
<li><em>Memory management:</em> Although the currently generated wrapper code works fine with regard to the GC for the test-suite, there might be issues coming up in real-world multi-threaded usage.</li>
<li><em>D2 support</em>: Originally, the module has been developed for the use with D1, D2/Phobos support has been added in later. The basic features should work equally well for both, but there <em>could</em> be issues concerning const-correctness etc.</li>
</ul>
</body>
</html>

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,859 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>SWIG and Guile</title>
<link rel="stylesheet" type="text/css" href="style.css">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body bgcolor="#ffffff">
<H1><a name="Guile">24 SWIG and Guile</a></H1>
<!-- INDEX -->
<div class="sectiontoc">
<ul>
<li><a href="#Guile_nn1">Supported Guile Versions</a>
<li><a href="#Guile_nn2">Meaning of "Module"</a>
<li><a href="#Guile_nn3">Old GH Guile API</a>
<li><a href="#Guile_nn4">Linkage</a>
<ul>
<li><a href="#Guile_nn5">Simple Linkage</a>
<li><a href="#Guile_nn6">Passive Linkage</a>
<li><a href="#Guile_nn7">Native Guile Module Linkage</a>
<li><a href="#Guile_nn8">Old Auto-Loading Guile Module Linkage</a>
<li><a href="#Guile_nn9">Hobbit4D Linkage</a>
</ul>
<li><a href="#Guile_nn10">Underscore Folding</a>
<li><a href="#Guile_nn11">Typemaps</a>
<li><a href="#Guile_nn12">Representation of pointers as smobs</a>
<ul>
<li><a href="#Guile_nn14">Smobs</a>
<li><a href="#Guile_nn15">Garbage Collection</a>
</ul>
<li><a href="#Guile_nn16">Native Guile pointers</a>
<li><a href="#Guile_nn17">Exception Handling</a>
<li><a href="#Guile_nn18">Procedure documentation</a>
<li><a href="#Guile_nn19">Procedures with setters</a>
<li><a href="#Guile_nn20">GOOPS Proxy Classes</a>
<ul>
<li><a href="#Guile_nn21">Naming Issues</a>
<li><a href="#Guile_nn22">Linking</a>
</ul>
</ul>
</div>
<!-- INDEX -->
<p>
This section details guile-specific support in SWIG.
<H2><a name="Guile_nn1">24.1 Supported Guile Versions</a></H2>
<p>
SWIG works with Guile versions 1.8.x and 2.0.x. Support for version
1.6.x has been dropped. The last version of SWIG that still works with
Guile version 1.6.x is SWIG 2.0.9.
<p>
Note that starting with guile 2.0, the guile sources can be compiled for
improved performance. This is currently not tested with swig
so your mileage may vary. To be safe set environment variable
GUILE_AUTO_COMPILE to 0 when using swig generated guile code.
<H2><a name="Guile_nn2">24.2 Meaning of "Module"</a></H2>
<p>
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".
<H2><a name="Guile_nn3">24.3 Old GH Guile API</a></H2>
<p>Guile 1.8 and older could be interfaced using two different api's, the SCM
or the GH API. The GH interface to guile is deprecated. Read more about why in the
<a href="http://www.gnu.org/software/guile/docs/docs-1.6/guile-ref/GH.html#GH">Guile manual</a>.
<p>Support for the guile GH wrapper code generation has been dropped from SWIG. The last
version of SWIG that can still generate guile GH wrapper code is 2.0.9. Please
use that version if you really need the GH wrapper code.
<H2><a name="Guile_nn4">24.4 Linkage</a></H2>
<p>
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 <b>linkage</b>.
<H3><a name="Guile_nn5">24.4.1 Simple Linkage</a></H3>
<p>
The default linkage is the simplest; nothing special is done. In this
case the function <code>SWIG_init()</code> is exported. Simple linkage
can be used in several ways:
</p>
<ul>
<li><b>Embedded Guile, no modules.</b> You want to embed a Guile
interpreter into your program; all bindings made by SWIG shall show up
in the root module. Then call <code>SWIG_init()</code> in the
<code>inner_main()</code> function. See the "simple" and "matrix" examples under
<code>Examples/guile</code>.
<li><p><b>Dynamic module mix-in.</b> You want to create a Guile module
using <code>define-module</code>, containing both Scheme code and
bindings made by SWIG; you want to load the SWIG modules as shared
libraries into Guile.</p>
<div class="targetlang">
<pre>
(define-module (my module))
(define my-so (dynamic-link "./libexample.so"))
(dynamic-call "SWIG_init" my-so) ; make SWIG bindings
;; Scheme definitions can go here
</pre>
</div>
<p>
Newer Guile versions provide a shorthand for <code>dynamic-link</code>
and <code>dynamic-call</code>:
</p>
<div class="targetlang">
<pre>
(load-extension "./libexample.so" "SWIG_init")
</pre>
</div>
<p>
A more portable approach would be to drop the shared library extension:
</p>
<div class="targetlang">
<pre>
(load-extension "./libexample" "SWIG_init")
</pre>
</div>
<p>
You need to explicitly export those bindings made by SWIG that you
want to import into other modules:
</p>
<div class="targetlang">
<pre>
(export foo bar)
</pre>
</div>
<p>
In this example, the procedures <code>foo</code> and <code>bar</code>
would be exported. Alternatively, you can export all bindings with the
following module-system hack:
</p>
<div class="targetlang">
<pre>
(module-map (lambda (sym var)
(module-export! (current-module) (list sym)))
(current-module))
</pre>
</div>
<p>SWIG can also generate this Scheme stub (from
<code>define-module</code> up to <code>export</code>)
semi-automagically if you pass it the command-line argument
<code>-scmstub</code>. The code will be exported in a file called
<code><i>module</i>.scm</code> in the directory specified by <code>-outdir</code>
or the current directory if <code>-outdir</code> is not specified.
Since SWIG doesn't know how
to load your extension module (with <code>dynamic-link</code> or
<code>load-extension</code>), you need to supply this
information by including a directive like this in the interface file:
</p>
<div class="code">
<pre>
%scheme %{ (load-extension "./libexample.so" "SWIG_init") %}
</pre>
</div>
<p>
(The <code>%scheme</code> directive allows to insert arbitrary Scheme
code into the generated file <code><var>module.scm</var></code>; it is
placed between the <code>define-module</code> form and the
<code>export</code> form.)
</p>
</ul>
<p>If you want to include several SWIG modules, you would need to rename
<code>SWIG_init</code> via a preprocessor define to avoid symbol
clashes. For this case, however, passive linkage is available.
<H3><a name="Guile_nn6">24.4.2 Passive Linkage</a></H3>
<p>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).
<p>You should use passive linkage rather than simple linkage when you
are using multiple modules.
<H3><a name="Guile_nn7">24.4.3 Native Guile Module Linkage</a></H3>
<p>SWIG can also generate wrapper code that does all the Guile module
declarations on its own if you pass it the <code>-Linkage
module</code> command-line option.
<p>The module name is set with the <code>-package</code> and
<code>-module</code> command-line options. Suppose you want to define
a module with name <code>(my lib foo)</code>; then you would have to
pass the options <code>-package <var>my</var>/<var>lib</var> -module
<var>foo</var></code>. Note that the last part of the name can also be set
via the SWIG directive <code>%module</code>.
<p>You can use this linkage in several ways:
<ul>
<li><b>Embedded Guile with SWIG modules.</b> You want to embed a Guile
interpreter into your program; the SWIG bindings shall be put into
different modules. Simply call the function
<code>scm_init_<var>my</var>_<var>modules</var>_<var>foo</var>_module</code>
in the <code>inner_main()</code> function.
<li><b>Dynamic Guile modules.</b> You want to load the SWIG modules as
shared libraries into Guile; all bindings are automatically put in
newly created Guile modules.
<div class="targetlang">
<pre>
(define my-so (dynamic-link "./libfoo"))
;; create new module and put bindings there:
(dynamic-call "scm_init_my_modules_foo_module" my-so)
</pre>
</div>
Newer Guile versions have a shorthand procedure for this:
<div class="targetlang">
<pre>
(load-extension "./libfoo.so" "scm_init_my_modules_foo_module")
</pre>
</div>
</ul>
<H3><a name="Guile_nn8">24.4.4 Old Auto-Loading Guile Module Linkage</a></H3>
<p>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 <code>-Linkage ltdlmod</code>
command-line option.
<p>Auto-loading worked like this: Suppose a module with name <code>(my
lib foo)</code> is required and not loaded yet. Guile will then search
all directories in its search path
for a Scheme file <code>my/modules/foo.scm</code> or a shared library
<code><var>my</var>/<var>modules</var>/lib<var>foo</var>.so</code> (or
<code><var>my</var>/<var>modules</var>/lib<var>foo</var>.la</code>;
see the GNU libtool documentation). If a
shared library is found that contains the symbol
<code>scm_init_<var>my</var>_<var>modules</var>_<var>foo</var>_module</code>,
the library is loaded, and the function at that symbol is called with
no arguments in order to initialize the module.
<p>When invoked with the <code>-Linkage ltdlmod</code> command-line
option, SWIG generates an exported module initialization function with
an appropriate name.
<H3><a name="Guile_nn9">24.4.5 Hobbit4D Linkage</a></H3>
<p>
The only other linkage supported at this time creates shared object
libraries suitable for use by hobbit's <code>(hobbit4d link)</code>
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:
</p>
<div class="shell">
<pre>
swig -guile -package my/lib foo.i
swig -guile -package my/lib -module foo foo.i
</pre>
</div>
<p>
would create module <code>(my lib foo)</code> (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.
</p>
<H2><a name="Guile_nn10">24.5 Underscore Folding</a></H2>
<p>
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.
<p>You can use the SWIG directives <code>%name</code> and
<code>%rename</code> to specify the Guile name of the wrapped
functions and variables (see CHANGES).
<H2><a name="Guile_nn11">24.6 Typemaps</a></H2>
<p>
The Guile module handles all types via typemaps. This
information is read from <code>Lib/guile/typemaps.i</code>.
Some non-standard typemap substitutions are supported:
<ul>
<li><code>$descriptor</code> expands to a type descriptor for use with
the <code>SWIG_NewPointerObj()</code> and
<code>SWIG_ConvertPtr</code> functions.
<li>For pointer types, <code>$*descriptor</code> expands to a
descriptor for the direct base type (i.e., one pointer is stripped),
whereas <code>$basedescriptor</code> expands to a
descriptor for the base type (i.e., all pointers are stripped).
</ul>
<p>A function returning <code>void</code> (more precisely, a function
whose <code>out</code> typemap returns <code>SCM_UNSPECIFIED</code>) is
treated as returning no values. In <code>argout</code> typemaps, one
can use the macro <code>GUILE_APPEND_RESULT</code> in order to append
a value to the list of function return values.
<p>Multiple values can be passed up to Scheme in one of three ways:
<ul>
<li><p><em>Multiple values as lists.</em>
By default, if more than one value is to
be returned, a list of the values is created and returned; to switch
back to this behavior, use</p>
<div class="code">
<pre>
%values_as_list;</pre>
</div>
<li><p><em>Multiple values as vectors.</em>
By issuing
</p>
<div class="code">
<pre>
%values_as_vector;</pre>
</div>
<p>
vectors instead of lists will be used.
<li><p><em>Multiple values for multiple-value continuations.</em>
<strong>This is the most elegant way.</strong> By issuing
</p>
<div class="code">
<pre>
%multiple_values;</pre>
</div>
<p>
multiple values are passed to the multiple-value
continuation, as created by <code>call-with-values</code> or the
convenience macro <code>receive</code>. The latter is available if you
issue <code>(use-modules (srfi srfi-8))</code>. Assuming that your
<code>divide</code> function
wants to return two values, a quotient and a remainder, you can write:
</p>
<div class="targetlang">
<pre>
(receive (quotient remainder)
(divide 35 17)
<var>body</var>...)
</pre>
</div>
<p>
In <code><var>body</var></code>, the first result of
<code>divide</code> will be bound to the variable
<code>quotient</code>, and the second result to <code>remainder</code>.
</p>
</ul>
<p>
See also the "multivalue" example.
</p>
<p>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
<a href="Customization.html#Customization_features">Features and the %feature directive</a>
for info on how to apply the %feature.</p>
<H2><a name="Guile_nn12">24.7 Representation of pointers as smobs</a></H2>
<p>
For pointer types, SWIG uses Guile smobs. SWIG smobs print
like this: <code>#&lt;swig struct xyzzy * 0x1234affe&gt;</code> Two of
them are <code>equal?</code> if and only if they have the same type
and value.
<p>
To construct a Scheme object from a C pointer, the wrapper code calls
the function <code>SWIG_NewPointerObj()</code>, 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 <code>SWIG_ConvertPtr()</code>, passing a pointer to a struct
representing the expected pointer type. See also
<a href="Typemaps.html#Typemaps_runtime_type_checker">The run-time type checker</a>.
If the Scheme object passed was not a SWIG smob representing a compatible
pointer, a <code>wrong-type-arg</code> exception is raised.
<H3><a name="Guile_nn14">24.7.1 Smobs</a></H3>
<p>
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.
</p>
<p>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. If a generated GOOPS module has been loaded, smobs will be wrapped by
the corresponding GOOPS class.</p>
<H3><a name="Guile_nn15">24.7.2 Garbage Collection</a></H3>
<p>Garbage collection is a feature of Guile since version 1.6. As SWIG now requires Guile &gt; 1.8,
it is automatically included.
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 <a href="Customization.html#Customization_ownership">
Object ownership and %newobject</a> in the SWIG manual. All typemaps use an $owner var, and
the guile module replaces $owner with 0 or 1 depending on feature:new.</p>
<H2><a name="Guile_nn16">24.8 Native Guile pointers</a></H2>
<p>
In addition to SWIG smob pointers, <a href="https://www.gnu.org/software/guile/manual/html_node/Foreign-Pointers.html">Guile's native pointer type</a> are accepted as arguments to wrapped SWIG functions. This can be useful for passing <a href="https://www.gnu.org/software/guile/manual/html_node/Void-Pointers-and-Byte-Access.html#">pointers to bytevector data</a> to wrapped functions.
</p>
<H2><a name="Guile_nn17">24.9 Exception Handling</a></H2>
<p>
SWIG code calls <code>scm_error</code> on exception, using the following
mapping:
<div class="code">
<pre>
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");
</pre>
</div>
<p>
The default when not specified here is to use "swig-error".
See Lib/exception.i for details.
<H2><a name="Guile_nn18">24.10 Procedure documentation</a></H2>
<p>If invoked with the command-line option <code>-procdoc
<var>file</var></code>, SWIG creates documentation strings for the
generated wrapper functions, describing the procedure signature and
return value, and writes them to <var>file</var>.
<p>SWIG can generate documentation strings in three formats, which are
selected via the command-line option <code>-procdocformat
<var>format</var></code>:
<ul>
<li><code>guile-1.4</code> (default): Generates a format suitable for Guile 1.4.
<li><code>plain</code>: Generates a format suitable for Guile 1.4.1 and
later.
<li><code>texinfo</code>: Generates texinfo source, which must be run
through texinfo in order to get a format suitable for Guile 1.4.1 and
later.
</ul>
<p>You need to register the generated documentation file with Guile
like this:
<div class="targetlang">
<pre>
(use-modules (ice-9 documentation))
(set! documentation-files
(cons "<var>file</var>" documentation-files))
</pre>
</div>
<p>Documentation strings can be configured using the Guile-specific
typemap argument <code>doc</code>. See <code>Lib/guile/typemaps.i</code> for
details.
<H2><a name="Guile_nn19">24.11 Procedures with setters</a></H2>
<p>For global variables, SWIG creates a single wrapper procedure
<code>(<var>variable</var> :optional value)</code>, which is used for
both getting and setting the value. For struct members, SWIG creates
two wrapper procedures <code>(<var>struct</var>-<var>member</var>-get
pointer)</code> and <code>(<var>struct-member</var>-set pointer value)</code>.
<p>If invoked with the command-line option <code>-emit-setters</code>
(<em>recommended</em>),
SWIG will additionally create procedures with setters. For global
variables, the procedure-with-setter <code><var>variable</var></code>
is created, so you can use <code>(<var>variable</var>)</code> to get
the value and <code>(set! (<var>variable</var>)
<var>value</var>)</code> to set it. For struct members, the
procedure-with-setter <code><var>struct</var>-<var>member</var></code>
is created, so you can use <code>(<var>struct</var>-<var>member</var>
<var>pointer</var>)</code> to get the value and <code>(set!
(<var>struct</var>-<var>member</var> <var>pointer</var>)
<var>value</var>)</code> to set it.
<p>If invoked with the command-line option <code>-only-setters</code>,
SWIG will <em>only</em> create procedures with setters, i.e., for
struct members, the procedures <code>(<var>struct</var>-<var>member</var>-get
pointer)</code> and <code>(<var>struct-member</var>-set pointer
value)</code> are <em>not</em> generated.
<H2><a name="Guile_nn20">24.12 GOOPS Proxy Classes</a></H2>
<p>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).
<p>To enable GOOPS support, pass the <code>-proxy</code> argument to
swig. This will export the GOOPS wrapper definitions into the
<code><i>module</i>.scm</code> file in the directory specified by -outdir or the
current directory. GOOPS support requires either passive or module linkage.</p>
<p>The generated file will contain definitions of GOOPS classes mimicking the C++ class hierarchy.
<p>Enabling GOOPS support implies <code>-emit-setters</code>.
<p>If <code>-emit-slot-accessors</code> 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</p>
<div class="code"><pre>
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); }
</pre></div>
<p>
will produce (if <code>-emit-slot-accessors</code> is not passed as a parameter)
</p>
<div class="targetlang"><pre>
(define-class &lt;Foo&gt; (&lt;swig&gt;)
(a #:allocation #:swig-virtual
#:slot-ref primitive:Foo-a-get
#:slot-set! primitive:Foo-a-set)
#:metaclass &lt;swig-metaclass&gt;
#:new-function primitive:new-Foo
)
(define-method (getMultBy (swig_smob &lt;Foo&gt;) i)
(primitive:Foo-getMultBy (slot-ref swig_smob 'smob) i))
(define-method (getFooMultBy (swig_smob &lt;Foo&gt;) i)
(make &lt;Foo&gt; #:init-smob (primitive:Foo-getFooMultBy (slot-ref swig_smob 'smob) i)))
(define-method (getFooPlus i)
(make &lt;Foo&gt; #:init-smob (primitive:getFooPlus i)))
(export &lt;Foo&gt; getMultBy getFooMultBy getFooPlus )
</pre></div>
<p>
and will produce (if <code>-emit-slot-accessors</code> is passed as a parameter)
</p>
<div class="targetlang"><pre>
(define-class &lt;Foo&gt; (&lt;swig&gt;)
(a #:allocation #:swig-virtual
#:slot-ref primitive:Foo-a-get
#:slot-set! primitive:Foo-a-set
<b>#:accessor a</b>)
#:metaclass &lt;swig-metaclass&gt;
#:new-function primitive:new-Foo
)
(define-method (getMultBy (swig_smob &lt;Foo&gt;) i)
(primitive:Foo-getMultBy (slot-ref swig_smob 'smob) i))
(define-method (getFooMultBy (swig_smob &lt;Foo&gt;) i)
(make &lt;Foo&gt; #:init-smob (primitive:Foo-getFooMultBy (slot-ref swig_smob 'smob) i)))
(define-method (getFooPlus i)
(make &lt;Foo&gt; #:init-smob (primitive:getFooPlus i)))
(export &lt;Foo&gt; <b>a</b> getMultBy getFooMultBy getFooPlus )
</pre></div>
<p>
which can then be used by this code
</p>
<div class="targetlang"><pre>
;; not using getters and setters
(define foo (make &lt;Foo&gt; #: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 &lt;Foo&gt; #:args '(45)))
(a foo)
(set! (a foo) 5)
(getMultBy foo 4)
(a (getFooMultBy foo 7))
</pre></div>
<p>Notice that constructor arguments are passed as a list after the <code>#:args</code> keyword. Hopefully in
the future the following will be valid <code>(make &lt;Foo&gt; #:a 5 #:b 4)</code></p>
<p>Also note that the order the declarations occur in the .i file make a difference. For example,
</p>
<div class="code"><pre>
%module test
%{ #include "foo.h" %}
%inline %{
int someFunc(Foo &amp;a) {
...
}
%}
%include "foo.h"
</pre></div>
<p>
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 <code>someFunc</code> definition is parsed by SWIG before all the
declarations in foo.h, the generated GOOPS file will contain the definition of <code>someFunc()</code>
before the definition of &lt;Foo&gt;. The generated GOOPS file would look like
</p>
<div class="targetlang"><pre>
;;...
(define-method (someFunc (swig_smob &lt;Foo&gt;))
(primitive:someFunc (slot-ref swig_smob 'smob)))
;;...
(define-class &lt;Foo&gt; (&lt;swig&gt;)
;;...
)
;;...
</pre></div>
<p>
Notice that &lt;Foo&gt; is used before it is defined. The fix is to just put the
<code>%import "foo.h"</code> before the <code>%inline</code> block.
</p>
<H3><a name="Guile_nn21">24.12.1 Naming Issues</a></H3>
<p>As you can see in the example above, there are potential naming conflicts. The default exported
accessor for the <code>Foo::a</code> variable is named <code>a</code>. The name of the wrapper global
function is <code>getFooPlus</code>.
If the <code>-useclassprefix</code> 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 <code>Foo-a</code> and
the member functions will be called <code>Foo-getMultBy</code>. Also, if the
<code>-goopsprefix goops:</code> argument is passed to swig, every identifier will be prefixed by
<code>goops:</code></p>
<p>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 <code>-Linkage
module</code>) or in the scmstub file (if <code>-Linkage passive -scmstub</code>). 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 <code>%module Test</code> is set in the swig interface file, the name of the guile-module in
the scmstub or <code>-Linkage module</code> will be <code>Test-primitive</code>. Also, the scmstub
file will be named <code>Test-primitive.scm</code>.
The string "primitive" can be changed by the <code>-primsuffix</code> swig
argument. So the same interface, with the <code>-primsuffix base</code> will produce a module called
<code>Test-base</code>.
The second generated guile-module contains all the GOOPS class definitions and is located in
a file named <i>module</i>.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 <code>%module</code> directive).
In the previous example, the GOOPS definitions will be in a file named Test.scm.</p>
<p>Because of the naming conflicts, you can't in general use both the <code>-primitive</code> 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,</p>
<div class="targetlang"><pre>
(use-modules ((Test-primitive) #:renamer (symbol-prefix-proc 'primitive:)))
(use-modules ((Test) #:renamer (symbol-prefix-proc 'goops:)))
</pre></div>
<H3><a name="Guile_nn22">24.12.2 Linking</a></H3>
<p>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 <i>Module</i>.scm. This should be installed on the autoload
path for guile, so that <code>(use-modules (<i>Package Module</i>))</code> 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 <code>%goops</code> directive inserts arbitrary code into the generated GOOPS guile-module, and
should be used to load the dependent libraries.</p>
<p>This breaks up into three cases</p>
<ul>
<li><b>Passive Linkage without -scmstub</b>: Note that this linkage style has the potential for naming
conflicts, since the primitive exported function and variable names are not wrapped in a guile-module
and might conflict with names from the GOOPS guile-module (see above). Pass the -goopsprefix
argument to solve this problem. If the <code>-exportprimitive</code> option is passed to SWIG the
<code>(export ...)</code> code that would be exported into the scmstub file is exported at the bottom
of the generated GOOPS guile-module.
The <code>%goops</code> directive should contain code to load the shared library.
<div class="code"><pre>
%goops %{ (load-extension "./libfoo.so" "scm_init_my_modules_foo_module") %}
</pre></div>
<p>
Produces the following code at the top of the generated GOOPS guile-module
(with the <code>-package my/modules -module foo</code> command line arguments)
</p>
<div class="targetlang"><pre>
(define-module (my modules foo))
;; %goops directive goes here
(load-extension "./libfoo.so" "scm_init_my_modules_foo_module")
(use-modules (oop goops) (Swig common))
</pre></div>
</li>
<li><p><b>Passive Linkage with -scmstub</b>: Here, the name of the scmstub file should be
<code>Module-primitive.scm</code> (with <i>primitive</i> replaced with whatever is given with the <code>-primsuffix</code>
argument. The code to load the shared library should be located in the <code>%scheme</code> directive,
which will then be added to the scmstub file.
SWIG will automatically generate the line <code>(use-modules (<i>Package</i> <i>Module-primitive</i>))</code>
into the GOOPS guile-module. So if <i>Module-primitive.scm</i> is on the autoload path for guile, the
<code>%goops</code> directive can be empty. Otherwise, the <code>%goops</code> directive should contain
whatever code is needed to load the <i>Module-primitive.scm</i> file into guile.</p>
<div class="targetlang"><pre>
%scheme %{ (load-extension "./libfoo.so" "scm_init_my_modules_foo_module") %}
// only include the following definition if (my modules foo) cannot
// be loaded automatically
%goops %{
(primitive-load "/path/to/foo-primitive.scm")
(primitive-load "/path/to/Swig/common.scm")
%}
</pre></div>
<p>
Produces the following code at the top of the generated GOOPS guile-module
</p>
<div class="targetlang"><pre>
(define-module (my modules foo))
;; %goops directive goes here (if any)
(primitive-load "/path/to/foo-primitive.scm")
(primitive-load "/path/to/Swig/common.scm")
(use-modules (oop goops) (Swig common))
(use-modules ((my modules foo-primitive) :renamer (symbol-prefix-proc
'primitive:)))
</pre></div>
</li>
<li><p><b>Module Linkage</b>: This is very similar to passive linkage with a scmstub file.
SWIG will also automatically generate the line <code>(use-modules
(<i>Package</i> <i>Module-primitive</i>))</code> into the GOOPS guile-module. Again the <code>%goops</code>
directive should contain whatever code is needed to get that module loaded into guile.</p>
<div class="code"><pre>
%goops %{ (load-extension "./libfoo.so" "scm_init_my_modules_foo_module") %}
</pre></div>
<p>
Produces the following code at the top of the generated GOOPS guile-module
</p>
<div class="targetlang"><pre>
(define-module (my modules foo))
;; %goops directive goes here (if any)
(load-extension "./libfoo.so" "scm_init_my_modules_foo_module")
(use-modules (oop goops) (Swig common))
(use-modules ((my modules foo-primitive) :renamer (symbol-prefix-proc
'primitive:)))
</pre></div>
</li>
</ul>
<p><b>(Swig common)</b>: 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
<code>%goops</code> directive also needs to contain code to load the <code>common.scm</code> 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.</p>
<p><b>Multiple Modules</b>: Type dependencies between modules is supported. For example, if
<code>mod1</code> includes definitions of some classes, and <code>mod2</code> includes some classes
derived from classes in <code>mod1</code>, the generated GOOPS file for <code>mod2</code> will declare
the correct superclasses. The only problem is that since <code>mod2</code> uses symbols from
<code>mod1</code>, the <code>mod2</code> GOOPS file must include a <code>(use-modules (mod2))</code>.
Currently, SWIG does not automatically export this line; it must be included in the <code>%goops</code>
directive of <code>mod2</code>. Maybe in the future SWIG can detect dependencies and export this line.
(how do other language modules handle this problem?)</p>
</body>
</html>

View File

@@ -0,0 +1,470 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Introduction</title>
<link rel="stylesheet" type="text/css" href="style.css">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body bgcolor="#ffffff">
<H1><a name="Introduction">2 Introduction</a></H1>
<!-- INDEX -->
<div class="sectiontoc">
<ul>
<li><a href="#Introduction_nn2">What is SWIG?</a>
<li><a href="#Introduction_nn3">Why use SWIG?</a>
<li><a href="#Introduction_nn4">A SWIG example</a>
<ul>
<li><a href="#Introduction_nn5">SWIG interface file</a>
<li><a href="#Introduction_nn6">The swig command</a>
<li><a href="#Introduction_nn7">Building a Perl5 module</a>
<li><a href="#Introduction_nn8">Building a Python module</a>
<li><a href="#Introduction_nn9">Shortcuts</a>
</ul>
<li><a href="#Introduction_nn10">Supported C/C++ language features</a>
<li><a href="#Introduction_nn11">Non-intrusive interface building</a>
<li><a href="#Introduction_build_system">Incorporating SWIG into a build system</a>
<li><a href="#Introduction_nn12">Hands off code generation</a>
<li><a href="#Introduction_nn13">SWIG and freedom</a>
</ul>
</div>
<!-- INDEX -->
<H2><a name="Introduction_nn2">2.1 What is SWIG?</a></H2>
<p>
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/C++ declarations and creates
the wrappers needed to access those declarations from other languages
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:
</p>
<ul>
<li>Building interpreted interfaces to existing C programs.
<li>Rapid prototyping and application development.
<li>Interactive debugging.
<li>Reengineering or refactoring of legacy software into scripting language components.
<li>Making a graphical user interface (using Tk for example).
<li>Testing of C libraries and programs (using scripts).
<li>Building high performance C modules for scripting languages.
<li>Making C programming more enjoyable (or tolerable depending on your point of view).
<li>Impressing your friends.
<li>Obtaining vast sums of research funding (although obviously not applicable to the author).
</ul>
<p>
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. However, nowadays SWIG is known to be used in many
large open source and commercial projects.
<H2><a name="Introduction_nn3">2.2 Why use SWIG?</a></H2>
<p>
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:
</p>
<ul>
<li>Excellent support for writing programming libraries.
<li>High performance (number crunching, data processing, graphics, etc.).
<li>Systems programming and systems integration.
<li>Large user community and software base.
</ul>
<p>
Next, let's list a few problems with C/C++ programming
</p>
<ul>
<li>Writing a user interface is rather painful (i.e., consider programming with MFC, X11, GTK, or any number
of other libraries).
<li>Testing is time consuming (the compile/debug cycle).
<li>Not easy to reconfigure or customize without recompilation.
<li>Modularization can be tricky.
<li>Security concerns (buffer overflows for instance).
</ul>
<p>
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.
</p>
<p>
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:
<ul>
<li>A collection of functions and variables that do something useful.
<li>A <tt>main()</tt> program that starts everything.
<li>A horrible collection of hacks that form some kind of user interface (but
which no-one really wants to touch).
</ul>
<p>
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.
</p>
<p>
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 ;-).
<H2><a name="Introduction_nn4">2.3 A SWIG example</a></H2>
<p>
The best way to illustrate SWIG is with a simple example. Consider the
following C code:
</p>
<div class="code"><pre>
/* File : example.c */
double My_variable = 3.0;
/* Compute factorial of n */
int fact(int n) {
if (n &lt;= 1)
return 1;
else
return n*fact(n-1);
}
/* Compute n mod m */
int my_mod(int n, int m) {
return(n % m);
}
</pre></div>
<p>
Suppose that you wanted to access these functions and the global
variable <tt>My_variable</tt> from Tcl. You start by making a SWIG
interface file as shown below (by convention, these files carry a .i
suffix) :
<H3><a name="Introduction_nn5">2.3.1 SWIG interface file</a></H3>
<div class="code"><pre>
/* 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);
</pre></div>
<p>
The interface file contains ANSI C function prototypes and variable
declarations. The <tt>%module</tt> directive defines the name of the
module that will be created by SWIG. The <tt>%{ %}</tt> block
provides a location for inserting additional code, such as C header
files or additional C declarations, into the generated C wrapper code.
<H3><a name="Introduction_nn6">2.3.2 The swig command</a></H3>
<p>
SWIG is invoked using the <tt>swig</tt> command. We can use this to
build a Tcl module (under Linux) as follows :
</p>
<div class="shell"><pre>
unix &gt; <b>swig -tcl example.i</b>
unix &gt; <b>gcc -c -fpic example.c example_wrap.c -I/usr/local/include</b>
unix &gt; <b>gcc -shared example.o example_wrap.o -o example.so</b>
unix &gt; <b>tclsh</b>
% <b>load ./example.so</b>
% <b>fact 4</b>
24
% <b>my_mod 23 7</b>
2
% <b>expr $My_variable + 4.5</b>
7.5
%
</pre></div>
<p>
The <tt>swig</tt> command produced a new file called
<tt>example_wrap.c</tt> that should be compiled along with the
<tt>example.c</tt> 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
<tt>example_wrap.c</tt> reveals a hideous mess. However, you
almost never need to worry about it.
<H3><a name="Introduction_nn7">2.3.3 Building a Perl5 module</a></H3>
<p>
Now, let's turn these functions into a Perl5 module. Without making
any changes type the following (shown for Solaris):
</p>
<div class="shell"><pre>
unix &gt; <b>swig -perl5 example.i</b>
unix &gt; <b>gcc -c example.c example_wrap.c \
-I/usr/local/lib/perl5/sun4-solaris/5.003/CORE</b>
unix &gt; <b>ld -G example.o example_wrap.o -o example.so</b> # This is for Solaris
unix &gt; <b>perl5.003
use example;
print example::fact(4), "\n";
print example::my_mod(23, 7), "\n";
print $example::My_variable + 4.5, "\n";
&lt;ctrl-d&gt;</b>
24
2
7.5
unix &gt;
</pre></div>
<H3><a name="Introduction_nn8">2.3.4 Building a Python module</a></H3>
<p>
Finally, let's build a module for Python (shown for Irix).
</p>
<div class="shell"><pre>
unix &gt; <b>swig -python example.i</b>
unix &gt; <b>gcc -c -fpic example.c example_wrap.c -I/usr/local/include/python2.0</b>
unix &gt; <b>gcc -shared example.o example_wrap.o -o _example.so</b>
unix &gt; <b>python</b>
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.
&gt;&gt;&gt; <b>import example</b>
&gt;&gt;&gt; <b>example.fact(4)</b>
24
&gt;&gt;&gt; <b>example.my_mod(23, 7)</b>
2
&gt;&gt;&gt; <b>example.cvar.My_variable + 4.5</b>
7.5
</pre></div>
<H3><a name="Introduction_nn9">2.3.5 Shortcuts</a></H3>
<p>
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
</p>
<div class="shell"><pre>
unix &gt; <b>swig -perl5 -module example example.h</b>
unix &gt; <b>gcc -c example.c example_wrap.c \
-I/usr/local/lib/perl5/sun4-solaris/5.003/CORE</b>
unix &gt; <b>ld -G example.o example_wrap.o -o example.so</b>
unix &gt; <b>perl5.003
use example;
print example::fact(4), "\n";
print example::my_mod(23, 7), "\n";
print $example::My_variable + 4.5, "\n";
&lt;ctrl-d&gt;</b>
24
2
7.5
</pre></div>
<H2><a name="Introduction_nn10">2.4 Supported C/C++ language features</a></H2>
<p>
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:
</p>
<ul>
<li>Full C99 preprocessing.
<li>All ANSI C and C++ datatypes.
<li>Functions, variables, and constants.
<li>Classes.
<li>Single and multiple inheritance.
<li>Overloaded functions and methods.
<li>Overloaded operators.
<li>C++ templates (including member templates, specialization, and partial specialization).
<li>Namespaces.
<li>Variable length arguments.
<li>C++ smart pointers.
</ul>
<p>
Most of C++11 is also supported. Details are in the <a href="CPlusPlus11.html#CPlusPlus11">C++11</a> section.
</p>
<p>
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 to handle C++ code that
stresses the very limits of many C++ compilers.
<H2><a name="Introduction_nn11">2.5 Non-intrusive interface building</a></H2>
<p>
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.
</p>
<H2><a name="Introduction_build_system">2.6 Incorporating SWIG into a build system</a></H2>
<p>
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 popular IDEs such as
Microsoft Visual Studio.
</p>
<p>
If you are using the GNU Autotools
(<a href="http://www.gnu.org/software/autoconf/">Autoconf</a>/
<a href="http://www.gnu.org/software/automake/">Automake</a>/
<a href="http://www.gnu.org/software/libtool/">Libtool</a>)
to configure SWIG use in your project, the SWIG Autoconf macros can be used.
The primary macro is <tt>ax_pkg_swig</tt>, see
<a href="http://www.gnu.org/software/autoconf-archive/ax_pkg_swig.html#ax_pkg_swig">http://www.gnu.org/software/autoconf-archive/ax_pkg_swig.html#ax_pkg_swig</a>.
The <tt>ax_python_devel</tt> macro is also helpful for generating Python extensions. See the
<a href="http://www.gnu.org/software/autoconf-archive/">Autoconf Archive</a>
for further information on this and other Autoconf macros.
</p>
<p>
There is growing support for SWIG in some build tools, for example <a href="http://cmake.org">CMake</a>
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 can also generate the custom commands necessary for
driving SWIG from IDEs 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:
</p>
<div class="code"><pre>
# 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})
</pre></div>
<p>
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.pyd (Windows).
For other target languages on Windows a dll, instead of a .pyd file, is usually generated.
</p>
<H2><a name="Introduction_nn12">2.7 Hands off code generation</a></H2>
<p>
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.
</p>
<H2><a name="Introduction_nn13">2.8 SWIG and freedom</a></H2>
<p>
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.
</p>
<p>
Ironically, the freedom that SWIG provides is countered by an
extremely conservative approach to code generation. At its 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.
Dependencies are often a source of incompatibilities and problems and so
additional third party libraries are not used in the generated code.
SWIG will also generally avoid generating code that introduces a dependency
on the C++ Standard Template Library (STL).
SWIG will generate code that depends on the C libraries though.
</p>
</body>
</html>

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,999 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<link rel="stylesheet" type="text/css" href="./style.css">
<title></title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body>
<H1><a name="Javascript">26 SWIG and Javascript</a></H1>
<!-- INDEX -->
<div class="sectiontoc">
<ul>
<li><a href="#Javascript_overview">Overview</a>
<li><a href="#Javascript_preliminaries">Preliminaries</a>
<ul>
<li><a href="#Javascript_running_swig">Running SWIG</a>
<li><a href="#Javascript_running_tests_examples">Running Tests and Examples</a>
<li><a href="#Javascript_known_issues">Known Issues</a>
</ul>
<li><a href="#Javascript_integration">Integration</a>
<ul>
<li><a href="#Javascript_node_extensions">Creating node.js Extensions</a>
<ul>
<li><a href="#Javascript_troubleshooting">Troubleshooting</a>
</ul>
<li><a href="#Javascript_embedded_webkit">Embedded Webkit</a>
<ul>
<li><a href="#Javascript_osx">Mac OS X</a>
<li><a href="#Javascript_gtk">GTK</a>
</ul>
<li><a href="#Javascript_applications_webkit">Creating Applications with node-webkit</a>
</ul>
<li><a href="#Javascript_examples">Examples</a>
<ul>
<li><a href="#Javascript_simple_example">Simple</a>
<li><a href="#Javascript_class_example">Class</a>
</ul>
<li><a href="#Javascript_implementation">Implementation</a>
<ul>
<li><a href="#Javascript_source_code">Source Code</a>
<li><a href="#Javascript_code_templates">Code Templates</a>
<li><a href="#Javascript_emitter">Emitter</a>
<li><a href="#Javascript_emitter_states">Emitter states</a>
<li><a href="#Javascript_jsc_exceptions">Handling Exceptions in JavascriptCore</a>
</ul>
</ul>
</div>
<!-- INDEX -->
<p>This chapter describes SWIG's support of Javascript. It does not cover SWIG basics, but only information that is specific to this module.</p>
<H2><a name="Javascript_overview">26.1 Overview</a></H2>
<p>Javascript is a prototype-based scripting language that is dynamic, weakly typed and has first-class functions. Its arguably the most popular language for web development.
Javascript has gone beyond being a browser-based scripting language and with <a href="http://nodejs.org">node.js</a>, it is also used as a backend development language.</p>
<p>Native Javascript extensions can be used for applications that embed a web-browser view or that embed a Javascript engine (such as <em>node.js</em>). Extending a general purpose web-browser is not possible as this would be a severe security issue.</p>
<p>SWIG Javascript currently supports <strong>JavascriptCore</strong>, the Javascript engine used by <code>Safari/Webkit</code>, and <a href="https://developers.google.com/v8"><strong>v8</strong></a>, which is used by <code>Chromium</code> and <code>node.js</code>.</p>
<p><a href="http://www.webkit.org/">WebKit</a> is a modern browser implementation available as open-source which can be embedded into an application.
With <a href="https://github.com/rogerwang/node-webkit">node-webkit</a> there is a platform which uses Google's <code>Chromium</code> as Web-Browser widget and <code>node.js</code> for javascript extensions.
</p>
<H2><a name="Javascript_preliminaries">26.2 Preliminaries</a></H2>
<H3><a name="Javascript_running_swig">26.2.1 Running SWIG</a></H3>
<p>Suppose that you defined a SWIG module such as the following:</p>
<div class="code">
<pre>
%module example
%{
#include "example.h"
%}
int gcd(int x, int y);
extern double Foo;</pre>
</div>
<p>To build a Javascript module, run SWIG using the <code>-javascript</code> option and a desired target engine <code>-jsc</code>, <code>-v8</code>, or <code>-node</code>. The generator for <code>node</code> is essentially delegating to the <code>v8</code> generator and adds some necessary preprocessor definitions.</p>
<div class="shell">
<pre>
$ swig -javascript -jsc example.i</pre>
</div>
<p>If building a C++ extension, add the -c++ option:</p>
<div class="shell">
<pre>
$ swig -c++ -javascript -jsc example.i</pre>
</div>
<p>The V8 code that SWIG generates should work with most versions from 3.11.10 up to 3.29.14 and later.</p>
<p>The API headers for V8 &gt;= 4.3.0 define constants which SWIG can use to
determine the V8 version it is compiling for. For versions &lt; 4.3.0, you
need to specify the V8 version when running SWIG. This is specified as a hex
constant, but the constant is read as pairs of decimal digits, so for V8
3.25.30 use constant 0x032530. This scheme can't represent components &gt; 99,
but this constant is only useful for V8 &lt; 4.3.0, and no V8 versions from
that era had a component &gt; 99. For example:</p>
<div class="shell">
<pre>
$ swig -c++ -javascript -v8 -DV8_VERSION=0x032530 example.i</pre>
</div>
<p>If you're targetting V8 &gt;= 4.3.0, you would just run swig like so:</p>
<div class="shell">
<pre>
$ swig -c++ -javascript -v8 example.i</pre>
</div>
<p>This creates a C/C++ source file <code>example_wrap.c</code> or <code>example_wrap.cxx</code>. 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.</p>
<p>The name of the wrapper file is derived from the name of the input file. For example, if the input file is <code>example.i</code>, the name of the wrapper file is <code>example_wrap.c</code>. To change this, you can use the -o option. The wrapped module will export one function which must be called to register the module with the Javascript interpreter. For example, if your module is named <code>example</code> the corresponding initializer for JavascriptCore would be</p>
<div class="code">
<pre>
bool example_initialize(JSGlobalContextRef context, JSObjectRef *exports)</pre>
</div>
<p>and for v8:</p>
<div class="code">
<pre>
void example_initialize(v8::Handle&lt;v8::Object&gt; exports)</pre>
</div>
<p>
<b>Note</b>: be aware that <code>v8</code> has a C++ API, and thus, the generated modules must be compiled as C++.
</p>
<H3><a name="Javascript_running_tests_examples">26.2.2 Running Tests and Examples</a></H3>
<p>The configuration for tests and examples currently supports Linux and Mac only and not MinGW (Windows) yet.</p>
<p>The default interpreter is <code>node.js</code> as it is available on all platforms and convenient to use.</p>
<p>Running the examples with JavascriptCore requires <code>libjavascriptcoregtk-1.0</code> to be installed, e.g., under Ubuntu with</p>
<div class="shell">
<pre>
$ sudo apt-get install libjavascriptcoregtk-1.0-dev</pre>
</div>
<p>Running with <code>V8</code> requires <code>libv8</code>:</p>
<div class="shell">
<pre>
$ sudo apt-get install libv8-dev</pre>
</div>
<p>Examples can be run using</p>
<div class="shell">
<pre>
$ make check-javascript-examples ENGINE=jsc</pre>
</div>
<p><code>ENGINE</code> can be <code>node</code>, <code>jsc</code>, or <code>v8</code>.</p>
<p>The test-suite can be run using</p>
<div class="shell">
<pre>
$ make check-javascript-test-suite ENGINE=jsc</pre>
</div>
<p>You can specify a specific <code>V8</code> version for running the examples and tests</p>
<div class="shell">
<pre>
$ make check-javascript-examples V8_VERSION=0x032530 ENGINE=v8</pre>
</div>
<H3><a name="Javascript_known_issues">26.2.3 Known Issues</a></H3>
<p>At the moment, the Javascript generators pass all tests syntactically, i.e., the generated source code compiles. However, there are still remaining runtime issues.</p>
<ul>
<li><p>Default optional arguments do not work for all targeted interpreters</p></li>
<li><p>Multiple output arguments do not work for JSC</p></li>
<li><p>C89 incompatibily: the JSC generator might still generate C89 violating code</p></li>
<li><p><code>long long</code> is not supported</p></li>
<li><p><code>%native</code> is not supported</p></li>
<li><p>Javascript callbacks are not supported</p></li>
<li><p><code>instanceOf</code> does not work under JSC</p></li>
</ul>
<p>The primary development environment has been Linux (Ubuntu 12.04). Windows and Mac OS X have been tested sporadically. Therefore, the generators might have more issues on those platforms. Please report back any problem you observe to help us improving this module quickly.</p>
<H2><a name="Javascript_integration">26.3 Integration</a></H2>
<p>This chapter gives a short introduction how to use a native Javascript extension: as a <code>node.js</code> module, and as an extension for an embedded Webkit.</p>
<H3><a name="Javascript_node_extensions">26.3.1 Creating node.js Extensions</a></H3>
<p>To install <code>node.js</code> you can download an installer from their <a href="https://launchpad.net/~chris-lea/+archive/node.js">web-site</a> for Mac OS X and Windows. For Linux you can either build the source yourself and run <code>sudo checkinstall</code> or keep to the (probably stone-age) packaged version. For Ubuntu there is a <a href="https://launchpad.net/~chris-lea/+archive/ubuntu/node.js/">PPA</a> available.</p>
<div class="shell">
<pre>
$ sudo add-apt-repository ppa:chris-lea/node.js
$ sudo apt-get update
$ sudo apt-get install nodejs</pre>
</div>
<p>As <code>v8</code> is written in C++ and comes as a C++ library it is crucial to compile your module using the same compiler flags as used for building v8. To make things easier, <code>node.js</code> provides a build tool called <code>node-gyp</code>.</p>
<p>You have to install it using <code>npm</code>:</p>
<div class="shell">
<pre>
$ sudo npm install -g node-gyp</pre>
</div>
<p><code>node-gyp</code> expects a configuration file named <code>binding.gyp</code> which is basically in JSON format and conforms to the same format that is used with Google's build-tool <code>gyp</code>.</p>
<p><code>binding.gyp</code>:</p>
<div class="code">
<pre>
{
"targets": [
{
"target_name": "example",
"sources": [ "example.cxx", "example_wrap.cxx" ]
}
]
}</pre>
</div>
<p>First create the wrapper using SWIG:</p>
<div class="shell">
<pre>
$ swig -javascript -node -c++ example.i</pre>
</div>
<p>Then run <code>node-gyp build</code> to actually create the module:</p>
<div class="shell">
<pre>
$ node-gyp build</pre>
</div>
<p>This will create a <code>build</code> folder containing the native module. To use the extension you need to 'require' it in your Javascript source file:</p>
<div class="code">
<pre>
require("./build/Release/example")</pre>
</div>
<p>A more detailed explanation is given in the <a href="#Javascript_examples">Examples</a> section.</p>
<H4><a name="Javascript_troubleshooting">26.3.1.1 Troubleshooting</a></H4>
<ul>
<li><em>'module' object has no attribute 'script_main'</em></li>
</ul>
<p>This error happens when <code>gyp</code> is installed as a distribution package. It seems to be outdated. Removing it resolves the problem.</p>
<div class="shell">
<pre>
$ sudo apt-get remove gyp</pre>
</div>
<H3><a name="Javascript_embedded_webkit">26.3.2 Embedded Webkit</a></H3>
<p>Webkit is pre-installed on Mac OS X and available as a library for GTK.</p>
<H4><a name="Javascript_osx">26.3.2.1 Mac OS X</a></H4>
<p>There is general information about programming with WebKit on <a href="https://developer.apple.com/library/mac/documentation/cocoa/conceptual/DisplayWebContent/DisplayWebContent.html">Apple Developer Documentation</a>. Details about <code>Cocoa</code> programming are not covered here.</p>
<p>An integration of a native extension 'example' would look like this:</p>
<div class="code">
<pre>
#import "appDelegate.h"
extern bool example_initialize(JSGlobalContextRef context, JSObjectRef* exports);
@implementation ExampleAppDelegate
@synthesize webView;
- (void)addGlobalObject:(JSContextRef) context:(NSString *)objectName:(JSObjectRef) theObject {
JSObjectRef global = JSContextGetGlobalObject(context);
JSStringRef objectJSName = JSStringCreateWithCFString( (CFStringRef) objectName )
if ( objectJSName != NULL ) {
JSObjectSetProperty(context, global, objectJSName, theObject, kJSPropertyAttributeReadOnly, NULL);
JSStringRelease( objectJSName );
}
}
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
// Start a webview with the bundled index.html file
NSString *path = [[NSBundle mainBundle] bundlePath];
NSString *url = [NSString stringWithFormat: @"file://%@/Contents/Assets/index.html", path];
WebFrame *webframe = [webView mainFrame];
JSGlobalContextRef context = [webframe globalContext];
JSObjectRef example;
example_initialize(context, &amp;example);
[self addGlobalObject:context:@"example":example]
JSObjectSetProperty(context, global, JSStringRef propertyName, example, JSPropertyAttributes attributes, NULL);
[ [webView mainFrame] loadRequest:
[NSURLRequest requestWithURL: [NSURL URLWithString:url] ]
];
}
@end</pre>
</div>
<H4><a name="Javascript_gtk">26.3.2.2 GTK</a></H4>
<p>There is general information about programming GTK at <a href="https://developer.gnome.org/gtk2/">GTK documentation</a> and in the <a href="https://developer.gnome.org/gtk-tutorial">GTK tutorial</a>, and for Webkit there is a <a href="http://webkitgtk.org/reference/webkitgtk/stable/index.html">Webkit GTK+ API Reference</a>.</p>
<p>An integration of a native extension 'example' would look like this:</p>
<div class="code">
<pre>
#include &lt;gtk/gtk.h&gt;
#include &lt;webkit/webkit.h&gt;
extern bool example_initialize(JSGlobalContextRef context);
int main(int argc, char* argv[])
{
// Initialize GTK+
gtk_init(&amp;argc, &amp;argv);
...
// Create a browser instance
WebKitWebView *webView = WEBKIT_WEB_VIEW(webkit_web_view_new());
WebFrame *webframe = webkit_web_view_get_main_frame(webView);
JSGlobalContextRef context = webkit_web_frame_get_global_context(webFrame);
JSObjectRef global = JSContextGetGlobalObject(context);
JSObjectRef exampleModule;
example_initialize(context, &amp;exampleModule);
JSStringRef jsName = JSStringCreateWithUTF8CString("example");
JSObjectSetProperty(context, global, jsName, exampleModule, kJSPropertyAttributeReadOnly, NULL);
JSStringRelease(jsName);
...
// Load a web page into the browser instance
webkit_web_view_load_uri(webView, "http://www.webkitgtk.org/");
...
// Run the main GTK+ event loop
gtk_main();
return 0;
}</pre>
</div>
<H3><a name="Javascript_applications_webkit">26.3.3 Creating Applications with node-webkit</a></H3>
<p>To get started with <code>node-webkit</code> there is a very informative set of <a href="https://github.com/rogerwang/node-webkit/wiki">wiki pages</a>.</p>
<p>Similar to <code>node.js</code>, <code>node-webkit</code> is started from command line within a <code>node.js</code> project directory.
Native extensions are created in the very same way as for <code>node.js</code>, except that a customized <code>gyp</code> derivate has to be used: <a href="https://github.com/rogerwang/nw-gyp">nw-gyp</a>.
</p>
<p>
A simple example would have the following structure:
</p>
<div class="code">
<pre>
- package.json
- app.html
- app.js
- node_modules
/ example
... (as known from node.js)
</pre>
</div>
<p>
The configuration file essentially conforms to <code>node.js</code> syntax.
It has some extras to configure <code>node-webkit</code>. See the <a href="https://github.com/rogerwang/node-webkit/wiki/Manifest-format">Manifest</a> specification for more details.
</p>
<p>
<code>package.json</code>:
</p>
<div class="code">
<pre>
{
"name": "example",
"main": "app.html",
"window": {
"show": true,
"width": 800,
"height": 600
}
}</pre>
</div>
<p>
The <code>'main'</code> property of <code>package.json</code> specifies a web-page to be rendered in
the main window.</p>
<p>
<code>app.html</code>:
</p>
<div class="code">
<pre>
&lt;html&gt;
&lt;head&gt;
&lt;script src="app.js"&gt;&lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;div&gt;
The greatest common divisor of
&lt;span id="x"&gt;&lt;/span&gt; and
&lt;span id="y"&gt;&lt;/span&gt; is
&lt;span id="z"&gt;&lt;/span&gt;.
&lt;/div&gt;
&lt;/body&gt;
&lt;/html&gt;</pre>
</div>
<p>
As known from <code>node.js</code> one can use <code>require</code> to load javascript modules.
Additionally, <code>node-webkit</code> provides an API that allows to manipulate the window's menu,
open new windows, and many more things.
</p>
<p>
<code>app.js</code>:
</p>
<div class="code">
<pre>window.onload = function() {
var example = require("example");
var x = 18;
var y = 24;
var z = example.gcd(x, y);
document.querySelector('#x').innerHTML = x;
document.querySelector('#y').innerHTML = y;
document.querySelector('#z').innerHTML = z;
};</pre>
</div>
<H2><a name="Javascript_examples">26.4 Examples</a></H2>
<p>Some basic examples are shown here in more detail.</p>
<H3><a name="Javascript_simple_example">26.4.1 Simple</a></H3>
<p>The common example <code>simple</code> looks like this:</p>
<div class="code">
<pre>
/* File : example.i */
%module example
%inline %{
extern int gcd(int x, int y);
extern double Foo;
%}</pre>
</div>
<p>To make this available as a node extension a <code>binding.gyp</code> has to be created:</p>
<div class="code">
<pre>
{
"targets": [
{
"target_name": "example",
"sources": [ "example.cxx", "example_wrap.cxx" ]
}
]
}</pre>
</div>
<p>Then <code>node-gyp</code> is used to build the extension:</p>
<div class="shell">
<pre>
$ node-gyp configure build</pre>
</div>
<p>From a 'nodejs` application the extension would be used like this:</p>
<div class="code">
<pre>
// import the extension via require
var example = require("./build/Release/example");
// calling the global method
var x = 42;
var y = 105;
var g = example.gcd(x, y);
// Accessing the global variable
var f = example.Foo;
example.Foo = 3.1415926;</pre>
</div>
<p>First the module <code>example</code> is loaded from the previously built extension. Global methods and variables are available in the scope of the module.</p>
<p><b>Note</b>: ECMAScript 5, the currently implemented Javascript standard, does not have modules. <code>node.js</code> and other implementations provide this mechanism defined by the <a href="http://wiki.commonjs.org/wiki/CommonJS">CommonJS</a> group. For browsers this is provided by <a href="http://browserify.org">Browserify</a>, for instance.</p>
<H3><a name="Javascript_class_example">26.4.2 Class</a></H3>
<p>The common example <code>class</code> defines three classes, <code>Shape</code>, <code>Circle</code>, and <code>Square</code>:</p>
<div class="code">
<pre>
class Shape {
public:
Shape() {
nshapes++;
}
virtual ~Shape() {
nshapes--;
}
double x, y;
void move(double dx, double dy);
virtual double area(void) = 0;
virtual double perimeter(void) = 0;
static int nshapes;
};
class Circle : public Shape {
private:
double radius;
public:
Circle(double r) : radius(r) { }
virtual double area(void);
virtual double perimeter(void);
};
class Square : public Shape {
private:
double width;
public:
Square(double w) : width(w) { }
virtual double area(void);
virtual double perimeter(void);
};</pre>
</div>
<p><code>Circle</code> and <code>Square</code> inherit from <code>Shape</code>. <code>Shape</code> has a static variable <code>nshapes</code>, a function <code>move</code> that can't be overridden (non-virtual), and two abstract functions <code>area</code> and <code>perimeter</code> (pure virtual) that must be overridden by the sub-classes.</p>
<p>A <code>nodejs</code> extension is built the same way as for the <code>simple</code> example.</p>
<p>In Javascript it can be used as follows:</p>
<div class="code">
<pre>
var example = require("./build/Release/example");
// local aliases for convenience
var Shape = example.Shape;
var Circle = example.Circle;
var Square = example.Square;
// creating new instances using the 'new' operator
var c = new Circle(10);
var s = new Square(10);
// accessing a static member
Shape.nshapes;
// accessing member variables
c.x = 20;
c.y = 30;
s.x = -10;
s.y = 5;
// calling some methods
c.area();
c.perimeter();
s.area();
s.perimeter();
// instantiation of Shape is not permitted
new Shape();</pre>
</div>
<p>Running these commands in an interactive node shell results in the following output:</p>
<div class="shell">
<pre>
$ node -i
&amp; var example = require("./build/Release/example");
undefined
&amp; var Shape = example.Shape;
undefined
&amp; var Circle = example.Circle;
undefined
&amp; var Square = example.Square;
undefined
&amp; var c = new Circle(10);
undefined
&amp; var s = new Square(10);
undefined
&amp; Shape.nshapes;
2
&amp; c.x = 20;
20
&amp; c.y = 30;
30
&amp; s.x = -10;
-10
&amp; s.y = 5;
5
&amp; c.area();
314.1592653589793
&amp; c.perimeter();
62.83185307179586
&amp; s.area();
100
&amp; s.perimeter();
40
&amp; c.move(40, 40)
undefined
&amp; c.x
60
&amp; c.y
70
&amp; new Shape()
Error: Class Shape can not be instantiated
at repl:1:2
at REPLServer.self.eval (repl.js:110:21)
at Interface.&lt;anonymous&gt; (repl.js:239:12)
at Interface.EventEmitter.emit (events.js:95:17)
at Interface._onLine (readline.js:202:10)
at Interface._line (readline.js:531:8)
at Interface._ttyWrite (readline.js:760:14)
at ReadStream.onkeypress (readline.js:99:10)
at ReadStream.EventEmitter.emit (events.js:98:17)
at emitKey (readline.js:1095:12)</pre>
</div>
<p>
<b>Note</b>: In ECMAScript 5 there is no concept for classes. Instead each function can be used as a constructor function which is executed by the 'new' operator. Furthermore, during construction the key property <code>prototype</code> of the constructor function is used to attach a prototype instance to the created object. A prototype is essentially an object itself that is the first-class delegate of a class used whenever the access to a property of an object fails. The very same prototype instance is shared among all instances of one type. Prototypal inheritance is explained in more detail on in <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Inheritance_and_the_prototype_chain">Inheritance and the prototype chain</a>, for instance.
</p>
<H2><a name="Javascript_implementation">26.5 Implementation</a></H2>
<p>The Javascript Module implementation has taken a very different approach compared to other language modules in order to support different Javascript interpreters.</p>
<H3><a name="Javascript_source_code">26.5.1 Source Code</a></H3>
<p>The Javascript module is implemented in <code>Source/Modules/javascript.cxx</code>. It dispatches the code generation to a <code>JSEmitter</code> instance, <code>V8Emitter</code> or <code>JSCEmitter</code>. Additionally there are some helpers: <code>Template</code>, for templated code generation, and <code>JSEmitterState</code>, which is used to manage state information during AST traversal. This rough map shall make it easier to find a way through this huge source file:</p>
<div class="code">
<pre>
// module wide defines
#define NAME "name"
...
// ###############################
// # Helper class declarations
class JSEmitterState { ... };
class Template { ... };
// ###############################
// # JSEmitter declaration
class JSEmitter { ... };
// Emitter factory declarations
JSEmitter *swig_javascript_create_JSCEmitter();
JSEmitter *swig_javascript_create_V8Emitter();
// ###############################
// # Javascript module
// Javascript module declaration
class JAVASCRIPT:public Language { ... };
// Javascript module implementation
int JAVASCRIPT::functionWrapper(Node *n) { ... }
...
// Module factory implementation
static Language *new_swig_javascript() { ... }
extern "C" Language *swig_javascript(void) { ... }
// ###############################
// # JSEmitter base implementation
JSEmitter::JSEmitter() { ... }
Template JSEmitter::getTemplate(const String *name) { ... }
...
// ###############################
// # JSCEmitter
// JSCEmitter declaration
class JSCEmitter: public JSEmitter { ... };
// JSCEmitter implementation
JSCEmitter::JSCEmitter() { ... }
void JSCEmitter::marshalInputArgs(Node *n, ParmList *parms, Wrapper *wrapper, MarshallingMode mode, bool is_member, bool is_static) { ... }
...
// JSCEmitter factory
JSEmitter *swig_javascript_create_JSCEmitter() { ... }
// ###############################
// # V8Emitter
// V8Emitter declaration
class V8Emitter: public JSEmitter { ... };
// V8Emitter implementation
V8Emitter::V8Emitter() { ... }
int V8Emitter::initialize(Node *n) { ... }
// V8Emitter factory
JSEmitter *swig_javascript_create_V8Emitter() { ... }
// ###############################
// # Helper implementation (JSEmitterState, Template)
JSEmitterState::JSEmitterState() { ... }
...
Template::Template(const String *code_) { ... }
...</pre>
</div>
<H3><a name="Javascript_code_templates">26.5.2 Code Templates</a></H3>
<p>All generated code is created on the basis of code templates. The templates for <em>JavascriptCore</em> can be found in <code>Lib/javascript/jsc/javascriptcode.swg</code>, for <em>v8</em> in <code>Lib/javascript/v8/javascriptcode.swg</code>.</p>
<p>To track the originating code template for generated code you can run</p>
<div class="shell">
<pre>
$ swig -javascript -jsc -debug-codetemplates</pre>
</div>
<p>which wraps generated code with a descriptive comment</p>
<div class="code">
<pre>
/* begin fragment("template_name") */
...generated code ...
/* end fragment("template_name") */</pre>
</div>
<p>The Template class is used like this:</p>
<div class="code">
<pre>
Template t_register = getTemplate("jsv8_register_static_variable");
t_register.replace("$jsparent", state.clazz(NAME_MANGLED))
.replace("$jsname", state.variable(NAME))
.replace("$jsgetter", state.variable(GETTER))
.replace("$jssetter", state.variable(SETTER))
.trim().
print(f_init_static_wrappers);</pre>
</div>
<p>A code template is registered with the <em>JSEmitter</em> via <code>fragment(name, &quot;template&quot;)</code>, e.g., </p>
<div class="code">
<pre>
%fragment ("jsc_variable_declaration", "templates")
%{
{"$jsname", $jsgetter, $jssetter, kJSPropertyAttributeNone},
%}</pre>
</div>
<p><code>Template</code> creates a copy of that string and <code>Template::replace</code> uses Swig's <code>Replaceall</code> to replace variables in the template. <code>Template::trim</code> can be used to eliminate leading and trailing whitespaces. <code>Template::print</code> is used to write the final template string to a Swig <code>DOH</code> (based on <code>Printv</code>). All methods allow chaining.</p>
<H3><a name="Javascript_emitter">26.5.3 Emitter</a></H3>
<p>The Javascript module delegates code generation to a <code>JSEmitter</code> instance. The following extract shows the essential interface:</p>
<div class="code">
<pre>
class JSEmitter {
...
/**
* Opens output files and temporary output DOHs.
*/
virtual int initialize(Node *n);
/**
* Writes all collected code into the output file(s).
*/
virtual int dump(Node *n) = 0;
/**
* Cleans up all open output DOHs.
*/
virtual int close() = 0;
...
/**
* Invoked at the beginning of the classHandler.
*/
virtual int enterClass(Node *);
/**
* Invoked at the end of the classHandler.
*/
virtual int exitClass(Node *) {
return SWIG_OK;
}
/**
* Invoked at the beginning of the variableHandler.
*/
virtual int enterVariable(Node *);
/**
* Invoked at the end of the variableHandler.
*/
virtual int exitVariable(Node *) {
return SWIG_OK;
}
/**
* Invoked at the beginning of the functionHandler.
*/
virtual int enterFunction(Node *);
/**
* Invoked at the end of the functionHandler.
*/
virtual int exitFunction(Node *) {
return SWIG_OK;
}
/**
* Invoked by functionWrapper callback after call to Language::functionWrapper.
*/
virtual int emitWrapperFunction(Node *n);
/**
* Invoked from constantWrapper after call to Language::constantWrapper.
**/
virtual int emitConstant(Node *n);
/**
* Registers a given code snippet for a given key name.
*
* This method is called by the fragmentDirective handler
* of the JAVASCRIPT language module.
**/
int registerTemplate(const String *name, const String *code);
/**
* Retrieve the code template registered for a given name.
*/
Template getTemplate(const String *name);
State &amp;getState();
...
}</pre>
</div>
<p>The module calls <code>initialize</code>, <code>dump</code>, and <code>close</code> from within the <code>top</code> method:</p>
<div class="code">
<pre>
int JAVASCRIPT::top(Node *n) {
emitter-&gt;initialize(n);
Language::top(n);
emitter-&gt;dump(n);
emitter-&gt;close();
return SWIG_OK;
}</pre>
</div>
<p>The methods <code>enterClass</code> and <code>exitClass</code> are called from within the <code>classHandler</code> method:</p>
<div class="code">
<pre>
int JAVASCRIPT::classHandler(Node *n) {
emitter-&gt;enterClass(n);
Language::classHandler(n);
emitter-&gt;exitClass(n);
return SWIG_OK;
}</pre>
</div>
<p>In <code>enterClass</code> the emitter stores state information that is necessary when processing class members. In <code>exitClass</code> the wrapper code for the whole class is generated.</p>
<H3><a name="Javascript_emitter_states">26.5.4 Emitter states</a></H3>
<p>For storing information during the AST traversal the emitter provides a <code>JSEmitterState</code> with different slots to store data representing the scopes global, class, function, and variable.</p>
<div class="code">
<pre>
class JSEmitterState {
public:
JSEmitterState();
~JSEmitterState();
DOH *global();
DOH *global(const char* key, DOH *initial = 0);
DOH *clazz(bool reset = false);
DOH *clazz(const char* key, DOH *initial = 0);
DOH *function(bool reset = false);
DOH *function(const char* key, DOH *initial = 0);
DOH *variable(bool reset = false);
DOH *variable(const char* key, DOH *initial = 0);
static int IsSet(DOH *val);
...
};</pre>
</div>
<p>When entering a scope, such as in <code>enterClass</code>, the corresponding state is reset and new data is stored:</p>
<div class="code">
<pre>
state.clazz(RESET);
state.clazz(NAME, Getattr(n, "sym:name"));</pre>
</div>
<p>State information can be retrieved using <code>state.clazz(NAME)</code> or with <code>Getattr</code> on <code>state.clazz()</code> which actually returns a <code>Hash</code> instance.</p>
<H3><a name="Javascript_jsc_exceptions">26.5.5 Handling Exceptions in JavascriptCore</a></H3>
<p>Applications with an embedded JavascriptCore should be able to present detailed exception messages that occur in the Javascript engine. Below is an example derived from code provided by Brian Barnes on how these exception details can be extracted.</p>
<div class="code">
<pre>
void script_exception_to_string(JSContextRef js_context, JSValueRef exception_value_ref, char* return_error_string, int return_error_string_max_length)
{
JSObjectRef exception_object;
JSValueRef value_ref;
JSStringRef jsstring_property_name = NULL;
JSValueRef temporary_exception = NULL;
JSStringRef js_return_string = NULL;
size_t bytes_needed;
char* c_result_string = NULL;
exception_object = JSValueToObject(js_context, exception_value_ref, NULL);
/* source url */
strcpy(return_error_string, &quot;[&quot;);
jsstring_property_name = JSStringCreateWithUTF8CString(&quot;sourceURL&quot;);
value_ref = JSObjectGetProperty(js_context, exception_object, jsstring_property_name, &amp;temporary_exception);
JSStringRelease(jsstring_property_name);
js_return_string = JSValueToStringCopy(js_context, value_ref, NULL);
bytes_needed = JSStringGetMaximumUTF8CStringSize(js_return_string);
c_result_string = (char*)calloc(bytes_needed, sizeof(char));
JSStringGetUTF8CString(js_return_string, c_result_string, bytes_needed);
JSStringRelease(js_return_string);
strncat(return_error_string, c_result_string, return_error_string_max_length-1);
free(c_result_string);
strncat(return_error_string, &quot;:&quot;, return_error_string_max_length-1);
/* line number */
jsstring_property_name = JSStringCreateWithUTF8CString(&quot;line&quot;);
value_ref = JSObjectGetProperty(js_context, exception_object, jsstring_property_name, &amp;temporary_exception);
JSStringRelease(jsstring_property_name);
js_return_string = JSValueToStringCopy(js_context, value_ref, NULL);
bytes_needed = JSStringGetMaximumUTF8CStringSize(js_return_string);
c_result_string = (char*)calloc(bytes_needed, sizeof(char));
JSStringGetUTF8CString(js_return_string, c_result_string, bytes_needed);
JSStringRelease(js_return_string);
strncat(return_error_string, c_result_string, return_error_string_max_length-1);
free(c_result_string);
strncat(return_error_string, &quot;]&quot;, return_error_string_max_length-1);
/* error message */
jsstring_property_name = JSStringCreateWithUTF8CString(&quot;message&quot;);
value_ref = JSObjectGetProperty(js_context, exception_object, jsstring_property_name, &amp;temporary_exception);
JSStringRelease(jsstring_property_name);
if(NULL == value_ref)
{
strncat(return_error_string, &quot;Unknown Error&quot;, return_error_string_max_length-1);
}
else
{
js_return_string = JSValueToStringCopy(js_context, value_ref, NULL);
bytes_needed = JSStringGetMaximumUTF8CStringSize(js_return_string);
c_result_string = (char*)calloc(bytes_needed, sizeof(char));
JSStringGetUTF8CString(js_return_string, c_result_string, bytes_needed);
JSStringRelease(js_return_string);
strncat(return_error_string, c_result_string, return_error_string_max_length-1);
free(c_result_string);
}
}</pre>
</div>
<p>It would be used in the following way:</p>
<div class="code">
<pre>
if(js_exception)
{
char return_error_string[256];
script_exception_to_string(js_context, js_exception, return_error_string, 256);
printf("Compile error is %s", return_error_string);
}</pre>
</div>
</body>
</html>

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,802 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>SWIG and Common Lisp</title>
<link rel="stylesheet" type="text/css" href="style.css">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body bgcolor="#ffffff">
<H1><a name="Lisp">27 SWIG and Common Lisp</a></H1>
<!-- INDEX -->
<div class="sectiontoc">
<ul>
<li><a href="#Lisp_nn2">Allegro Common Lisp</a>
<li><a href="#Lisp_nn3">Common Foreign Function Interface(CFFI)</a>
<ul>
<li><a href="#Lisp_nn4">Additional Commandline Options </a>
<li><a href="#Lisp_nn5">Generating CFFI bindings</a>
<li><a href="#Lisp_nn6">Generating CFFI bindings for C++ code</a>
<li><a href="#Lisp_nn7">Inserting user code into generated files</a>
</ul>
<li><a href="#Lisp_nn8">CLISP</a>
<ul>
<li><a href="#Lisp_nn9">Additional Commandline Options </a>
<li><a href="#Lisp_nn10">Details on CLISP bindings</a>
</ul>
<li><a href="#Lisp_nn11">UFFI </a>
</ul>
</div>
<!-- INDEX -->
<p>
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.
</p>
<H2><a name="Lisp_nn2">27.1 Allegro Common Lisp</a></H2>
<p>
Allegro Common Lisp support in SWIG has been updated to include
support for both C and C++. You can read about the interface
<a href="Allegrocl.html#Allegrocl">here</a>
</p>
<H2><a name="Lisp_nn3">27.2 Common Foreign Function Interface(CFFI)</a></H2>
<p>
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.
</p>
<p>
To run the cffi module of SWIG requires very little effort, you
just need to run:
</p>
<div class="code"><pre>
swig -cffi -module <i>module-name</i> <i>file-name</i>
</pre></div>
<p>
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.
</p>
<H3><a name="Lisp_nn4">27.2.1 Additional Commandline Options </a></H3>
<p>
The following table list the additional commandline options available for the CLISP module. They can also be seen by using:
</p>
<div class="code"><pre>
swig -cffi -help
</pre></div>
<br/>
<table summary="CFFI specific options">
<tr>
<th> CFFI specific options</th>
</tr>
<tr>
<td>-generate-typedef</td>
<td>If this option is given then defctype will be used to generate<br/>
shortcuts according to the typedefs in the input.
</td>
</tr>
<tr>
<td>-[no]cwrap</td>
<td>Turn on or turn off generation of an intermediate C file when<br/>
creating a C interface. By default this is only done for C++ code.
</td>
</tr>
<tr>
<td>-[no]swig-lisp</td>
<td>Turns 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.
</td>
</tr>
</table>
<H3><a name="Lisp_nn5">27.2.2 Generating CFFI bindings</a></H3>
As we mentioned earlier the ideal way to use SWIG is to use interface
files. To illustrate the use of it, let's assume that we have a
file named <i>test.h</i> with the following C code:
<div class="code"><pre>
#define y 5
#define x (y &gt;&gt; 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};
</pre></div>
Corresponding to this we will write a simple interface file:
<div class="code"><pre>
%module test
%include "test.h"
</pre></div>
The generated SWIG Code will be:
<div class="targetlang"><pre>
;;;SWIG wrapper code starts here
(cl:defmacro defanonenum (&amp;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:&amp;optional (package cl:*package*))
(cl:labels ((helper (lst last rest cl:&amp;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)
</pre></div>
<p>
The <i>SWIG wrapper</i> 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 <i>-[no]swig-lisp</i>
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.
</p>
<p> 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 <a
href="Customization.html#Customization_features">feature directive</a>.
Let's 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.
</p>
<div class="code"><pre>
%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;
%feature("export", package="'some-other-package") lispsort_double;
%rename func123 renamed_cool_func;
%ignore "pointer_func";
%include "test.h"
</pre></div>
<p>
The <i>typemap(cin)</i> ensures that for all arguments which are input
to C with the type "div_t*", the ":my-pointer" type be
used. Similarly <i>typemap(cout)</i> are used for all types which
are returned from C.
</p>
<p>
The feature <i>intern_function</i> ensures that all C names are
interned using the <b>swig-lispify</b> function. The "1" given
to the feature is optional. The use of feature like
<i>%feature("intern_function", "1");</i> globally enables
interning for everything. If you want to target a single
function, or declaration then use the targeted version of
feature, <i>%feature("intern_function", "my-lispify")
lispsort_double;</i>, here we are using an additional feature
which allows us to use our lispify function.
</p>
<p>The <i>export</i> feature allows us to export the symbols. If
the <i>package</i> argument is given, then the symbol will be exported to
the specified Lisp package. The <i>inline</i> feature declaims the
declared function as inline. The <i>rename</i> directive allows us to
change the name(it is useful when generating C wrapper code for handling
overloaded functions). The <i>ignore</i> directive ignores a certain
declaration.
</p>
<p>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:
</p>
<div class="targetlang"><pre>
(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) 'some-other-package)
(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))
</pre></div>
<H3><a name="Lisp_nn6">27.2.3 Generating CFFI bindings for C++ code</a></H3>
<p>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.
</p>
<p> Generating bindings for C++ code, requires <i>-c++</i> 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.
</p>
<div class="code"><pre>
%{
#include "Test/test.h"
%}
</pre></div>
<p>
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.
</p>
<div class="code"><pre>
%import "ancillary/header.h"
%include "target/header.h"
</pre></div>
Various features which were available for C headers can also be used
here. The target header which we are going to use here is:
<div class="code"><pre>
namespace OpenDemo {
class Test
{
public:
float x;
// constructors
Test (void) {x = 0;}
Test (float X) {x = X;}
// vector addition
Test operator+ (const Test&amp; v) const {return Test (x+v.x);}
// length squared
float lengthSquared (void) const {return this-&gt;dot (*this);}
static float distance (const Test&amp; a, const Test&amp; b){return(a-b).length();}
inline Test parallelComponent (const Test&amp; unitBasis) const {
return unitBasis * projection;
}
Test setYtoZero (void) const {return Test (this-&gt;x);}
static const Test zero;
};
inline Test operator* (float s, const Test&amp; v) {return v*s;}
inline std::ostream&amp; operator&lt;&lt; (std::ostream&amp; o, const Test&amp; v)
{
return o &lt;&lt; "(" &lt;&lt; v.x &lt;&lt; ")";
}
inline Test RandomUnitVectorOnXZPlane (void)
{
return RandomVectorInUnitRadiusSphere().setYtoZero().normalize();
}
}
</pre></div>
<p>The interface used is: </p>
<div class="code"><pre>
%module test
%include "test.cpp"
</pre></div>
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:
<div class="targetlang"><pre>
(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)
</pre></div>
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
<div class="targetlang"><pre>
(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)))
</pre></div>
<p>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.
</p>
<p>
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.
<H3><a name="Lisp_nn7">27.2.4 Inserting user code into generated files</a></H3>
<p>
It is often necessary to <a href="SWIG.html#SWIG_nn40">include user-defined code</a>
into the automatically generated interface files. For example, when building
a C++ interface, example_wrap.cxx will likely not compile unless
you add a <tt>#include "header.h"</tt> directive. This can be done
using the SWIG <tt>%insert(section) %{ ...code... %}</tt> directive:
</p>
<div class="code">
<pre>
%module example
%{
#include "header.h"
%}
%include "header.h"
int fact(int n);
</pre>
</div>
<p>
Additional sections have been added for inserting into the
generated lisp interface file:
</p>
<ul>
<li><tt>lisphead</tt> - inserts before type declarations</li>
<li><tt>swiglisp</tt> - inserts after type declarations according to
where it appears in the .i file</li>
</ul>
<p>
Note that the block <tt>%{ ... %}</tt> is effectively a shortcut for
<tt>%insert("header") %{ ... %}</tt>.
</p>
<H2><a name="Lisp_nn8">27.3 CLISP</a></H2>
<p>
<a href="http://clisp.cons.org">CLISP</a> 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.
</p>
<p>
To run the clisp module of SWIG requires very little effort, you
just need to execute:
</p>
<div class="code"><pre>
swig -clisp -module <i>module-name</i> <i>file-name</i>
</pre></div>
<p>
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.
</p>
<H3><a name="Lisp_nn9">27.3.1 Additional Commandline Options </a></H3>
<p>
The following table list the additional commandline options available for the CLISP module. They can also be seen by using:
</p>
<div class="code"><pre>
swig -clisp -help
</pre></div>
<br/>
<table summary="CLISP specific options">
<tr>
<th>CLISP specific options</th>
</tr>
<tr>
<td>-extern-all</td>
<td>If this option is given then clisp definitions for all the functions<br/>
and global variables will be created otherwise only definitions for<br/>
externed functions and variables are created.
</td>
</tr>
<tr>
<td>-generate-typedef</td>
<td>If this option is given then def-c-type will be used to generate<br/>
shortcuts according to the typedefs in the input.
</td>
</tr>
</table>
<H3><a name="Lisp_nn10">27.3.2 Details on CLISP bindings</a></H3>
<p>
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.<br/>
After generating the defpackage statement, the clisp module also
sets the default language.
<div class="targetlang"><pre>
(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)
</pre></div>
<p>
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)))'
</p>
<div class="code"><pre>
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);
}
</pre></div>
<div class="targetlang"><pre>
(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+))
</pre></div>
<p>
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.
</p>
<div class="code"><pre>
struct bar {
short x, y;
char a, b;
int *z[1000];
struct bar * n;
};
#define max 1000
</pre></div>
<div class="targetlang"><pre>
(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)
</pre></div>
<H2><a name="Lisp_nn11">27.4 UFFI </a></H2>
</body>
</html>

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,91 @@
# Makefile for generating the SWIG documentation
#
# Note that the htmldoc package needs to be installed. wkhtmltopdf patched with qt is also required
# and can be installed from http://wkhtmltopdf.org/downloads.html.
#
# The .html files are first processed and updated with chapter numbering and anchor names
# are added to the HTML headings using the python scripts. The htmldoc program is then
# used to generate the single page HTML version of the documentation.
# wkhtmltopdf is used to generate the pdf document from the single page html file.
# HTML TIDY (package also known as tidy) is also required and is used as an aid to HTML
# validation.
#
# Additional html validation can be done using the validate target.
# Additional link checking can be done using the linkchecker1 and linkchecker2 target.
#
# Note the # and " are escaped
HTMLDOC_OPTIONS = "--book --toclevels 4 --no-numbered --toctitle \"Table of Contents\" --title --titleimage swig16.png --linkcolor \#0000ff --linkstyle underline --size Universal --left 0.50in --right 0.50in --top 0.50in --bottom 0.50in --header .t. --footer h.1 --nup 1 --tocheader .t. --tocfooter ..i --portrait --color --no-pscommands --no-xrxcomments --compression=1 --jpeg=0 --fontsize 10.0 --fontspacing 1.2 --headingfont Helvetica --bodyfont Times --headfootsize 10.0 --headfootfont Helvetica --charset iso-8859-1 --links --no-embedfonts --pagemode outline --pagelayout single --firstpage c1 --pageeffect none --pageduration 10 --effectduration 1.0 --no-encryption --permissions all --owner-password \"\" --user-password \"\" --browserwidth 680"
.PHONY: maketoc check generate all maintainer-clean validate test
all: maketoc check generate
maketoc:
python maketoc.py
# Use this to regenerate CCache.html should this ever be needed
CCache.html: ../../CCache/ccache.yo
yodl2html -o CCache.html ../../CCache/ccache.yo
# Tabs in the html files will stop the build as wkhtmltopdf does not expand them correctly - replace them with the appropriate number of tabs
# Use htmltidy to warn about some HTML errors. Note that it is not used to clean/tidy the HTML,
# it is just used as a primitive HTML checker.
# CCache.html is generated by yodl2html and has a few insignificant problems, so we don't put it through tidy
check:
all="index.html Sections.html `sed '/^#/d' chapters | grep -v CCache.html`" && for a in $$all; do echo "Check for tabs $$a" && if grep -P '\t' $$a; then echo "Please delete the tabs from the lines above" && exit 1; fi; done && for a in $$all; do echo "HTML tidy check $$a" && tidy -errors --gnu-emacs yes -quiet $$a; done;
# Note wkhtmltopdf limitations for generating pdf docs:
# 1) <H1><a name="X"></a>Text</H1> style links don't work and need changing to
# <H1><a name="X">Text</a></H1>
# 2) Tabs in <pre> elements should be expanded to 8 spaces by default, but
# are expanded to just one space and css tab-size is not working.
# 3) <pre> <tt> <code> elements do not always select a fixed-width font - try installing the
# Courier font to fix - these have been added to style.css.
generate: SWIGDocumentation.html
wkhtmltopdf --version | grep "with patched qt" || (echo "wkhtmltopdf is not the patched qt version and so cannot be used - download it from http://wkhtmltopdf.org/downloads.html" && false)
wkhtmltopdf --margin-top 20mm --margin-bottom 20mm --margin-left 10mm --margin-right 10mm --header-font-size 6 --footer-font-size 6 --header-spacing 6 --footer-spacing 6 --header-center '[doctitle]' --footer-left '[subsection]' --footer-right '[page]' SWIGDocumentation.html SWIGDocumentation.pdf
SWIGDocumentation.html: swightml.book
htmldoc --batch swightml.book || true
python fixstyle.py SWIGDocumentation.html
swightml.book: chapters Sections.html
echo "#HTMLDOC 1.8.24" > swightml.book
echo -t html -f SWIGDocumentation.html $(HTMLDOC_OPTIONS) >> swightml.book
echo "Sections.html" >> swightml.book
cat chapters >> swightml.book
maintainer-clean: clean-baks
rm -f swightml.book
rm -f SWIGDocumentation.html
rm -f SWIGDocumentation.pdf
rm -rf linkchecker-tmp
clean-baks:
rm -f *.bak
test:
grep "href=\".*\.html\"" index.html
grep "href=\".*\.html\"" Sections.html
all=`sed '/^#/d' chapters`; for a in $$all; do grep -l "href=\".*\.html\"" $$a; done;
# Validating using the WDG offline validator - http://www.htmlhelp.com/tools/validator/offline/
validate:
all=`sed '/^#/d' chapters`; for a in $$all; do validate --emacs $$a; done;
# Link checking using linkchecker of the index.html only file (including anchors)
linkchecker1:
@echo -----------------------------------------------------------------------
@echo Note linkchecker versions prior to 6.1 do not work properly wrt anchors
@echo -----------------------------------------------------------------------
linkchecker --config=./linkchecker.config --anchors index.html
# Check for links which don't work including those generated from the individual .html files into SWIGDocumentation.html
linkchecker2:
rm -rf linkchecker-tmp
mkdir linkchecker-tmp
cp SWIGDocumentation.html linkchecker-tmp
cp *.png linkchecker-tmp
(cd linkchecker-tmp && linkchecker --config=../linkchecker.config -F text --no-warnings SWIGDocumentation.html)

View File

@@ -0,0 +1,942 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>SWIG and Modula-3</title>
<link rel="stylesheet" type="text/css" href="style.css">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body bgcolor="#FFFFFF">
<H1><a name="Modula3">29 SWIG and Modula-3</a></H1>
<!-- INDEX -->
<div class="sectiontoc">
<ul>
<li><a href="#Modula3_modula3_overview">Overview</a>
<ul>
<li><a href="#Modula3_motivation">Motivation</a>
</ul>
<li><a href="#Modula3_conception">Conception</a>
<ul>
<li><a href="#Modula3_cinterface">Interfaces to C libraries</a>
<li><a href="#Modula3_cppinterface">Interfaces to C++ libraries</a>
</ul>
<li><a href="#Modula3_preliminaries">Preliminaries</a>
<ul>
<li><a href="#Modula3_compilers">Compilers</a>
<li><a href="#Modula3_commandline">Additional Commandline Options</a>
</ul>
<li><a href="#Modula3_typemaps">Modula-3 typemaps</a>
<ul>
<li><a href="#Modula3_inoutparam">Inputs and outputs</a>
<li><a href="#Modula3_ordinals">Subranges, Enumerations, Sets</a>
<li><a href="#Modula3_class">Objects</a>
<li><a href="#Modula3_imports">Imports</a>
<li><a href="#Modula3_exceptions">Exceptions</a>
<li><a href="#Modula3_typemap_example">Example</a>
</ul>
<li><a href="#Modula3_hints">More hints to the generator</a>
<ul>
<li><a href="#Modula3_features">Features</a>
<li><a href="#Modula3_pragmas">Pragmas</a>
</ul>
<li><a href="#Modula3_remarks">Remarks</a>
</ul>
</div>
<!-- INDEX -->
<p>
This chapter describes SWIG's support for
<a href="http://modula3.org/">Modula-3</a>.
You should be familiar with the
<a href="SWIG.html#SWIG">basics</a>
of SWIG,
especially
<a href="Typemaps.html#Typemaps">typemaps</a>.
</p>
<H2><a name="Modula3_modula3_overview">29.1 Overview</a></H2>
<p>
Modula-3 is a compiled language in the tradition of Niklaus Wirth's Modula 2,
which is in turn a successor to Pascal.
</p>
<p>
SWIG's Modula-3 support is currently very basic and highly experimental!
Many features are still not designed satisfyingly
and I need more discussion about the odds and ends.
Don't rely on any feature, incompatible changes are likely in the future!
However, the Modula-3 generator was already useful for interfacing
to the libraries:
</p>
<ol>
<li>
<a href="http://www.elegosoft.com/cgi-bin/cvsweb.cgi/cm3/m3-libs/plplot/">
PLPlot
</a>
</li>
<li>
<a href="http://www.elegosoft.com/cgi-bin/cvsweb.cgi/cm3/m3-libs/fftw/">
FFTW
</a>
</li>
</ol>
<H3><a name="Modula3_motivation">29.1.1 Motivation</a></H3>
<p>
Although it is possible to write Modula-3 code that performs as well as C/C++
most existing libraries are not written in Modula-3 but in C or C++, and
even libraries in other languages may provide C header files.
</p>
<p>
Fortunately Modula-3 can call C functions, but you have to write Modula-3
interfaces to them, and to make things comfortable you will also need
wrappers that convert between high-level features of Modula-3 (garbage
collecting, exceptions) and the explicit tracking of allocated memory and
exception codes used by C APIs.
</p>
<p>
SWIG converts C headers to Modula-3 interfaces for you, and using typemaps
you can pass <tt>TEXT</tt>s or open arrays, and convert error return codes
into exceptions.
</p>
<p>
If the library API is ill designed
writing appropriate typemaps can still be time-consuming.
E.g. C programmers are very creative to work-around
missing data types like (real) enumerations and sets.
You should turn such work-arounds back to the Modula-3 way
otherwise you lose static safety and consistency.
</p>
<p>
Without SWIG you would probably never consider trying to call C++ libraries
from Modula-3, but with SWIG this is becomes feasible.
SWIG can generate C wrappers to C++ functions and object methods
that may throw exceptions, and then wrap these C wrappers for Modula-3.
To make it complete you can then hide the C interface with Modula-3 classes and
exceptions.
</p>
<p>
SWIG allows you to call C and C++ libraries from Modula-3 (even with call back
functions), but it doesn't allow you to easily integrate a Modula-3 module into
a C/C++ project.
</p>
<H2><a name="Modula3_conception">29.2 Conception</a></H2>
<H3><a name="Modula3_cinterface">29.2.1 Interfaces to C libraries</a></H3>
<p>
Modula-3 has integrated support for calling C functions.
This is also extensively used by the standard Modula-3 libraries
to call OS functions.
The Modula-3 part of SWIG and the corresponding SWIG library
modula3.swg
contain code that uses these features.
Because of the built-in support there is no need
for calling the SWIG kernel to generate wrappers written in C.
All conversion and argument checking can be done in Modula-3
and the interfacing is quite efficient.
All you have to do is to write pieces of Modula-3 code
that SWIG puts together.
</p>
<table border summary="Modula-3 C library support">
<tr><th colspan=2>C library support integrated in Modula-3<th></tr>
<tr>
<td>Pragma <tt>&lt;* EXTERNAL *&gt;</tt></td>
<td>Precedes a declaration of a PROCEDURE that is implemented
in an external library instead of a Modula-3 module.</td>
</tr>
<tr>
<td>Pragma <tt>&lt;* CALLBACK *&gt;</tt></td>
<td>Precedes a declaration of a PROCEDURE that should be called
by external library code.</td>
</tr>
<tr>
<td>Module <tt>Ctypes</tt></td>
<td>Contains Modula-3 types that match some basic C types.</td>
</tr>
<tr>
<td>Module <tt>M3toC</tt></td>
<td>Contains routines that convert between Modula-3's <tt>TEXT</tt> type
and C's <tt>char *</tt> type.</td>
</tr>
</table>
<p>
In each run of SWIG the Modula-3 part
generates several files:
</p>
<table border summary="Modula-3 generated files">
<tr>
<th>Module name scheme</th>
<th>Identifier for <tt>%insert</tt></th>
<th>Description</th>
</tr>
<tr>
<td>Module<tt>Raw.i3</tt></td>
<td><tt>m3rawintf</tt></td>
<td>Declaration of types that are equivalent to those of the C library,
<tt>EXTERNAL</tt> procedures as interface to the C library functions</td>
</tr>
<tr>
<td>Module<tt>Raw.m3</tt></td>
<td><tt>m3rawimpl</tt></td>
<td>Almost empty.</td>
</tr>
<tr>
<td>Module<tt>.i3</tt></td>
<td><tt>m3wrapintf</tt></td>
<td>Declaration of comfortable wrappers to the C library functions.</td>
</tr>
<tr>
<td>Module<tt>.m3</tt></td>
<td><tt>m3wrapimpl</tt></td>
<td>Implementation of the wrappers that
convert between Modula-3 and C types,
check for validity of values,
hand-over resource management to the garbage collector using <tt>WeakRef</tt>s
and raises exceptions.</td>
</tr>
<tr>
<td><tt>m3makefile</tt></td>
<td><tt>m3makefile</tt></td>
<td>Add the modules above to the Modula-3 project and
specify the name of the Modula-3 wrapper library
to be generated.
Today I'm not sure if it is a good idea
to create a <tt>m3makefile</tt> in each run,
because SWIG must be started for each Modula-3 module it creates.
Thus the m3makefile is overwritten each time. :-(
</td>
</tr>
</table>
<p>
Here's a scheme of how the function calls to Modula-3 wrappers
are redirected to C library functions:
</p>
<table summary="Modula-3 C library">
<tr>
<td align=center>
Modula-3 wrapper<br>
Module<tt>.i3</tt><br>
generated by Modula-3 part of SWIG
</td>
<td></td>
<td align=center></td>
</tr>
<tr>
<td align=center>
<!-- pre tag overrides centering -->
|<br>
v
</td>
<td></td>
<td align=center></td>
</tr>
<tr>
<td align=center>
Modula-3 interface to C<br>
Module<tt>Raw.i3</tt><br>
generated by Modula-3 part of SWIG
</td>
<td>--&gt;</td>
<td align=center>
C library
</td>
</tr>
</table>
<p>
I have still no good conception how one can split C library interfaces
into type oriented interfaces.
A Module in Modula-3 represents an Abstract DataType
(or call it a static classes, i.e. a class without virtual methods).
E.g. if you have a principal type, say <tt>Database</tt>,
it is good Modula-3 style to set up one Module with the name <tt>Database</tt>
where the database type is declared with the name <tt>T</tt>
and where all functions are declared that operates on it.
</p>
<p>
The normal operation of SWIG is to generate a fixed set of files per call.
To generate multiple modules one has to write one SWIG interface
(different SWIG interfaces can share common data) per module.
Identifiers belonging to a different module may ignored (<tt>%ignore</tt>)
and the principal type must be renamed (<tt>%typemap</tt>).
</p>
<H3><a name="Modula3_cppinterface">29.2.2 Interfaces to C++ libraries</a></H3>
<p>
Interfaces to C++ files are much more complicated and
there are some more design decisions that are not made, yet.
Modula-3 has no support for C++ functions
but C++ compilers should support generating C++ functions
with a C interface.
</p>
<p>
Here's a scheme of how the function calls to Modula-3 wrappers
are redirected to C library functions:
</p>
<table summary="Modula-3 C++ library">
<tr>
<td align=center>
Modula-3 wrapper<br>
Module<tt>.i3</tt><br>
generated by Modula-3 part of SWIG
</td>
<td></td>
<td align=center>C++ library</td>
</tr>
<tr>
<td align=center>
<!-- pre tag overrides centering -->
|<br>
v
</td>
<td></td>
<td align=center>
^<br>
|
</td>
</tr>
<tr>
<td align=center>
Modula-3 interface to C<br>
Module<tt>Raw.i3</tt><br>
generated by Modula-3 part of SWIG
</td>
<td>--&gt;</td>
<td align=center>
C interface to C++<br>
module<tt>_wrap.cxx</tt><br>
generated by the SWIG core
</td>
</tr>
</table>
<p>
Wrapping C++ libraries arises additional problems:
</p>
<ul>
<li>
Is it sensible to wrap C++ classes with Modula-3 classes?
</li>
<li>
How to find the wrapping Modula-3 class
for a class pointer that is returned by a C++ routine?
</li>
<li>
How to deal with multiple inheritance
which was neglected for Modula-3 for good reasons?
</li>
<li>
Is it possible to sub-class C++ classes with Modula-3 code?
This issue is addressed by directors,
a feature that was experimentally added to some Language modules
like
<a href="Java.html#Java_directors">Java</a> and
<a href="Python.html#Python_directors">Python</a>.
</li>
<li>
How to manage storage with the garbage collector of Modula-3?
Support for
<a href="Customization.html#Customization_ownership">
<tt>%newobject</tt> and <tt>%typemap(newfree)</tt></a>
isn't implemented, yet.
What's about resources that are managed by the garbage collector
but shall be passed back to the storage management of the C++ library?
This is a general issue which is not solved in a satisfying fashion
as far as I know.
</li>
<li>
How to turn C++ exceptions into Modula-3 exceptions?
There's also no support for
<a href="Customization.html#Customization_exception">
<tt>%exception</tt></a>, yet.
</li>
</ul>
<p>
Be warned:
There is no C++ library I wrote a SWIG interface for,
so I'm not sure if this is possible or sensible, yet.
</p>
<H2><a name="Modula3_preliminaries">29.3 Preliminaries</a></H2>
<H3><a name="Modula3_compilers">29.3.1 Compilers</a></H3>
<p>
There are different Modula-3 compilers around:
cm3, pm3, ezm3, Klagenfurth Modula-3, Cambridge Modula-3.
SWIG itself does not contain compiler specific code
but the modula3.swg library file
may do so.
For testing examples I use Critical Mass cm3.
</p>
<H3><a name="Modula3_commandline">29.3.2 Additional Commandline Options</a></H3>
<p>
There are some experimental command line options
that prevent SWIG from generating interface files.
Instead files are emitted that may assist you
when writing SWIG interface files.
</p>
<table border summary="Modula-3 specific options">
<tr>
<th>Modula-3 specific options</th>
<th>Description</th>
</tr>
<tr>
<td valign=top>-generateconst &lt;file&gt;</td>
<td>
Disable generation of interfaces and wrappers.
Instead write code for computing numeric values of constants
to the specified file.
<br>
C code may contain several constant definitions
written as preprocessor macros.
Other language modules of SWIG use
compute-once-use-readonly variables or
functions to wrap such definitions.
All of them can invoke C code dynamically
for computing the macro values.
But if one wants to turn them into Modula-3
integer constants, enumerations or set types,
the values of these expressions has to be known statically.
Although definitions like <tt>(1 &lt;&lt; FLAG_MAXIMIZEWINDOW)</tt>
must be considered as good C style
they are hard to convert to Modula-3
since the value computation can use every feature of C.
<br>
Thus I implemented these switch
to extract all constant definitions
and write a C program that output the values of them.
It works for numeric constants only
and treats all of them as <tt>double</tt>.
Future versions may generate a C++ program
that can detect the type of the macros
by overloaded output functions.
Then strings can also be processed.
</td>
</tr>
<tr>
<td valign=top>-generaterename &lt;file&gt;</td>
<td>
Disable generation of interfaces and wrappers.
Instead generate suggestions for <tt>%rename</tt>.
<br>
C libraries use a naming style
that is neither homogeneous nor similar to that of Modula-3.
C function names often contain a prefix denoting the library
and some name components separated by underscores
or capitalization changes.
To get library interfaces that are really Modula-3 like
you should rename the function names with the <tt>%rename</tt> directive.
This switch outputs a list of such directives
with a name suggestion generated by a simple heuristic.
</td>
</tr>
<tr>
<td valign=top>-generatetypemap &lt;file&gt;</td>
<td>
Disable generation of interfaces and wrappers.
Instead generate templates for some basic typemaps.
</td>
</tr>
</table>
<H2><a name="Modula3_typemaps">29.4 Modula-3 typemaps</a></H2>
<H3><a name="Modula3_inoutparam">29.4.1 Inputs and outputs</a></H3>
<p>
Each C procedure has a bunch of inputs and outputs.
Inputs are passed as function arguments,
outputs are updated referential arguments and
the function value.
</p>
<p>
Each C type can have several typemaps
that apply only in case if a type is used
for an input argument, for an output argument,
or for a return value.
A further typemap may specify
the direction that is used for certain parameters.
I have chosen this separation
in order to be able to write general typemaps for the modula3.swg typemap library.
In the library code the final usage of the type is not known.
Using separate typemaps for each possible use
allows appropriate definitions for each case.
If these pre-definitions are fine
then the direction of the function parameter
is the only hint the user must give.
</p>
<p>
The typemaps specific to Modula-3 have a common name scheme:
A typemap name starts with "m3",
followed by "raw" or "wrap"
depending on whether it controls the generation
of the Module<tt>Raw.i3</tt> or the Module<tt>.i3</tt>, respectively.
It follows an "in" for typemaps applied to input argument,
"out" for output arguments, "arg" for all kind of arguments,
"ret" for returned values.
</p>
<p>
The main task of SWIG is to build wrapper function,
i.e. functions that convert values between C and Modula-3
and call the corresponding C function.
Modula-3 wrapper functions generated by SWIG
consist of the following parts:
</p>
<ul>
<li>Generate <tt>PROCEDURE</tt> signature.</li>
<li>Declare local variables.</li>
<li>Convert input values from Modula-3 to C.</li>
<li>Check for input value integrity.</li>
<li>Call the C function.</li>
<li>Check returned values, e.g. error codes.</li>
<li>Convert and write back values into Modula-3 records.</li>
<li>Free temporary storage.</li>
<li>Return values.</li>
</ul>
<table border summary="Modula-3 typemaps">
<tr>
<th>Typemap</th>
<th>Example</th>
<th>Description</th>
</tr>
<tr>
<td>m3wrapargvar</td>
<td><tt>$1: INTEGER := $1_name;</tt></td>
<td>
Declaration of some variables needed for temporary results.
</td>
</tr>
<tr>
<td>m3wrapargconst</td>
<td><tt>$1 = "$1_name";</tt></td>
<td>
Declaration of some constant, maybe for debug purposes.
</td>
</tr>
<tr>
<td>m3wrapargraw</td>
<td><tt>ORD($1_name)</tt></td>
<td>
The expression that should be passed as argument to the raw Modula-3 interface function.
</td>
</tr>
<tr>
<td>m3wrapargdir</td>
<td><tt>out</tt></td>
<td>
Referential arguments can be used for input, output, update.
???
</td>
</tr>
<tr>
<td>m3wrapinmode</td>
<td><tt>READONLY</tt></td>
<td>
One of Modula-3 parameter modes
<tt>VALUE</tt> (or empty),
<tt>VAR</tt>,
<tt>READONLY</tt>
</td>
</tr>
<tr>
<td>m3wrapinname</td>
<td></td>
<td>
New name of the input argument.
</td>
</tr>
<tr>
<td>m3wrapintype</td>
<td></td>
<td>
Modula-3 type of the input argument.
</td>
</tr>
<tr>
<td>m3wrapindefault</td>
<td></td>
<td>
Default value of the input argument
</td>
</tr>
<tr>
<td>m3wrapinconv</td>
<td><tt>$1 := M3toC.SharedTtoS($1_name);</tt></td>
<td>
Statement for converting the Modula-3 input value to C compliant value.
</td>
</tr>
<tr>
<td>m3wrapincheck</td>
<td><tt>IF Text.Length($1_name) &gt; 10 THEN RAISE E("str too long"); END;</tt></td>
<td>
Check the integrity of the input value.
</td>
</tr>
<tr>
<td>m3wrapoutname</td>
<td></td>
<td>
Name of the <tt>RECORD</tt> field to be used for returning multiple values.
This applies to referential output arguments that shall be turned
into return values.
</td>
</tr>
<tr>
<td>m3wrapouttype</td>
<td></td>
<td>
Type of the value that is returned instead of a referential output argument.
</td>
</tr>
<tr>
<td>m3wrapoutconv</td>
<td></td>
<td>
</td>
</tr>
<tr>
<td>m3wrapoutcheck</td>
<td></td>
<td>
</td>
</tr>
<tr>
<td>m3wrapretraw</td>
<td></td>
<td>
</td>
</tr>
<tr>
<td>m3wrapretname</td>
<td></td>
<td>
</td>
</tr>
<tr>
<td>m3wraprettype</td>
<td></td>
<td>
</td>
</tr>
<tr>
<td>m3wrapretvar</td>
<td></td>
<td>
</td>
</tr>
<tr>
<td>m3wrapretconv</td>
<td></td>
<td>
</td>
</tr>
<tr>
<td>m3wrapretcheck</td>
<td></td>
<td>
</td>
</tr>
<tr>
<td>m3wrapfreearg</td>
<td><tt>M3toC.FreeSharedS(str, arg1);</tt></td>
<td>
Free resources that were temporarily used in the wrapper.
Since this step should never be skipped,
SWIG will put it in the <tt>FINALLY</tt> branch
of a <tt>TRY .. FINALLY</tt> structure.
</td>
</tr>
</table>
<H3><a name="Modula3_ordinals">29.4.2 Subranges, Enumerations, Sets</a></H3>
<p>
Subranges, enumerations, and sets are machine oriented types
that make Modula very strong and expressive compared
with the type systems of many other languages.
</p>
<ul>
<li>
Subranges are used for statically restricted choices of integers.
</li>
<li>
Enumerations are used for named choices.
</li>
<li>
Sets are commonly used for flag (option) sets.
</li>
</ul>
<p>
Using them extensively makes Modula code very safe and readable.
</p>
<p>
C supports enumerations, too, but they are not as safe as the ones of Modula.
Thus they are abused for many things:
For named choices, for integer constant definitions, for sets.
To make it complete every way of defining a value in C
(<tt>#define</tt>, <tt>const int</tt>, <tt>enum</tt>)
is somewhere used for defining something
that must be handled completely different in Modula-3
(<tt>INTEGER</tt>, enumeration, <tt>SET</tt>).
</p>
<p>
I played around with several <tt>%feature</tt>s and <tt>%pragma</tt>s
that split the task up into converting
the C bit patterns (integer or bit set)
into Modula-3 bit patterns (integer or bit set)
and change the type as requested.
See the corresponding example in the
Examples/modula3/enum/example.i file.
This is quite messy and not satisfying.
So the best what you can currently do is
to rewrite constant definitions manually.
Though this is a tedious work
that I'd like to automate.
</p>
<H3><a name="Modula3_class">29.4.3 Objects</a></H3>
<p>
Declarations of C++ classes are mapped to <tt>OBJECT</tt> types
while it is tried to retain the access hierarchy
"public - protected - private" using partial revelation.
Though the example in
Examples/modula3/class/example.i
is not really useful, yet.
</p>
<H3><a name="Modula3_imports">29.4.4 Imports</a></H3>
<p>
Pieces of Modula-3 code provided by typemaps
may contain identifiers from foreign modules.
If the typemap <tt>m3wrapinconv</tt> for <tt>blah *</tt>
contains code using the function <tt>M3toC.SharedTtoS</tt>
you may declare <tt>%typemap("m3wrapinconv:import") blah * %{M3toC%}</tt>.
Then the module <tt>M3toC</tt> is imported
if the <tt>m3wrapinconv</tt> typemap for <tt>blah *</tt>
is used at least once.
Use <tt>%typemap("m3wrapinconv:import") blah * %{MyConversions AS M3toC%}</tt>
if you need module renaming.
Unqualified import is not supported.
</p>
<p>
It is cumbersome to add this typemap to each piece of Modula-3 code.
It is especially useful when writing general typemaps
for the modula3.swg typemap library.
For a monolithic module you might be better off
if you add the imports directly:
</p>
<div class="code">
<pre>
%insert(m3rawintf) %{
IMPORT M3toC;
%}
</pre></div>
<H3><a name="Modula3_exceptions">29.4.5 Exceptions</a></H3>
<p>
Modula-3 provides another possibility
of an output of a function: exceptions.
</p>
<p>
Any piece of Modula-3 code that SWIG inserts
due to a typemap can raise an exception.
This way you can also convert an error code
from a C function into a Modula-3 exception.
</p>
<p>
The <tt>RAISES</tt> clause is controlled
by typemaps with the <tt>throws</tt> extension.
If the typemap <tt>m3wrapinconv</tt> for <tt>blah *</tt>
contains code that may raise the exceptions <tt>OSError.E</tt>
you should declare
<tt>%typemap("m3wrapinconv:throws") blah * %{OSError.E%}</tt>.
</p>
<H3><a name="Modula3_typemap_example">29.4.6 Example</a></H3>
<p>
The generation of wrappers in Modula-3 needs very fine control
to take advantage of the language features.
Here is an example of a generated wrapper
where almost everything is generated by a typemap:
</p>
<div class="code"><pre>
<I> (* %relabel m3wrapinmode m3wrapinname m3wrapintype m3wrapindefault *)</I>
PROCEDURE Name (READONLY str : TEXT := "" )
<I> (* m3wrapoutcheck:throws *)</I>
: NameResult RAISES {E} =
CONST
arg1name = "str"; <I>(* m3wrapargconst *)</I>
VAR
arg0 : C.char_star; <I>(* m3wrapretvar *)</I>
arg1 : C.char_star; <I>(* m3wrapargvar *)</I>
arg2 : C.int;
result : RECORD
<I> (*m3wrapretname m3wraprettype*)</I>
unixPath : TEXT;
<I> (*m3wrapoutname m3wrapouttype*)</I>
checksum : CARDINAL;
END;
BEGIN
TRY
arg1 := M3toC.SharedTtoS(str); <I>(* m3wrapinconv *)</I>
IF Text.Length(arg1) &gt; 10 THEN <I>(* m3wrapincheck *)</I>
RAISE E("str too long");
END;
<I> (* m3wrapretraw m3wrapargraw *)</I>
arg0 := MessyToUnix (arg1, arg2);
result.unixPath := M3toC.CopyStoT(arg0); <I>(* m3wrapretconv *)</I>
result.checksum := arg2; <I>(* m3wrapoutconv *)</I>
IF result.checksum = 0 THEN <I>(* m3wrapoutcheck *)</I>
RAISE E("invalid checksum");
END;
FINALLY
M3toC.FreeSharedS(str, arg1); <I>(* m3wrapfreearg *)</I>
END;
END Name;
</pre></div>
<H2><a name="Modula3_hints">29.5 More hints to the generator</a></H2>
<H3><a name="Modula3_features">29.5.1 Features</a></H3>
<table border summary="Modula-3 features">
<tr>
<th>Feature</th>
<th>Example</th>
<th>Description</th>
</tr>
<tr>
<td>multiretval</td>
<td><tt>%m3multiretval get_box;</tt> or
<tt>%feature("modula3:multiretval") get_box;</tt></td>
<td>Let the denoted function return a <tt>RECORD</tt>
rather than a plain value.
This <tt>RECORD</tt> contains all arguments with "out" direction
including the return value of the C function (if there is one).
If more than one argument is "out"
then the function <b>must</b> have the <tt>multiretval</tt> feature activated,
but it is explicitly requested from the user to prevent mistakes.</td>
</tr>
<tr>
<td>constnumeric</td>
<td><tt>%constnumeric(12) twelve;</tt> or
<tt>%feature("constnumeric", "12") twelve;</tt></td>
<td>This feature can be used to tell Modula-3's back-end of SWIG
the value of an identifier.
This is necessary in the cases
where it was defined by a non-trivial C expression.
This feature is used by the
<tt>-generateconst</tt> <a href="#Modula3_commandline">option</a>.
In future it may be generalized to other kind of values
such as strings.
</td>
</tr>
</table>
<H3><a name="Modula3_pragmas">29.5.2 Pragmas</a></H3>
<table border summary="Modula-3 pragmas">
<tr>
<th>Pragma</th>
<th>Example</th>
<th>Description</th>
</tr>
<tr>
<td>unsafe</td>
<td><tt>%pragma(modula3) unsafe="true";</tt></td>
<td>Mark the raw interface modules as <tt>UNSAFE</tt>.
This will be necessary in many cases.</td>
</tr>
<tr>
<td>library</td>
<td><tt>%pragma(modula3) library="m3fftw";</tt></td>
<td>Specifies the library name for the wrapper library to be created.
It should be distinct from the name of the library to be wrapped.</td>
</tr>
</table>
<H2><a name="Modula3_remarks">29.6 Remarks</a></H2>
<ul>
<li>
The Modula-3 part of SWIG doesn't try to generate nicely formatted code.
If you need to read the generated code, use <tt>m3pp</tt> to postprocess the
Modula files.
</li>
</ul>
</body>
</html>

View File

@@ -0,0 +1,352 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Working with Modules</title>
<link rel="stylesheet" type="text/css" href="style.css">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body bgcolor="#ffffff">
<H1><a name="Modules">16 Working with Modules</a></H1>
<!-- INDEX -->
<div class="sectiontoc">
<ul>
<li><a href="#Modules_introduction">Modules Introduction</a>
<li><a href="#Modules_nn1">Basics</a>
<li><a href="#Modules_nn2">The SWIG runtime code</a>
<li><a href="#Modules_external_run_time">External access to the runtime</a>
<li><a href="#Modules_nn4">A word of caution about static libraries</a>
<li><a href="#Modules_nn5">References</a>
<li><a href="#Modules_nn6">Reducing the wrapper file size</a>
</ul>
</div>
<!-- INDEX -->
<H2><a name="Modules_introduction">16.1 Modules Introduction</a></H2>
<p>
Each invocation of SWIG requires a module name to be specified.
The module name is used to name the resulting target language extension module.
Exactly what this means and what the name is used for
depends on the target language, for example the name can define
a target language namespace or merely be a useful name for naming files or helper classes.
Essentially, a module comprises target language wrappers for a chosen collection of global variables/functions, structs/classes and other C/C++ types.
</p>
<p>
The module name can be supplied in one of two ways.
The first is to specify it with the special <tt>%module</tt>
directive. This directive must appear at the beginning of the interface file.
The general form of this directive is:
</p>
<div class="code"><pre>
<tt>%module(option1="value1", option2="value2", ...) modulename</tt>
</pre></div>
<p>
where the modulename is mandatory and the options add one or more optional additional features.
Typically no options are specified, for example:
</p>
<div class="code"><pre>
<tt>%module mymodule</tt>
</pre></div>
<p>
The second way to specify the module name is with the <tt>-module</tt> command line option, for example <tt>-module mymodule</tt>.
If the module name is supplied on the command line, it overrides the name specified by the
<tt>%module</tt> directive.
</p>
<p>
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 together 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.
</p>
<p>
This chapter describes the problem of using SWIG in programs
where you want to create a collection of modules.
Each module in the collection is created via separate invocations of SWIG.
</p>
<H2><a name="Modules_nn1">16.2 Basics</a></H2>
<p>
The basic usage case with multiple modules is when modules do not have
cross-references (ie. when wrapping multiple independent C APIs). In that case,
swig input files should just work out of the box - you simply create multiple
wrapper .cxx files, link them into your application, and insert/load each in the
scripting language runtime as you would do for the single module case.
</p>
<p>
A bit more complex is the case in which modules need to share information.
For example, when one module extends the class of another by deriving from
it:
</p>
<div class="code"><pre>
// File: base.h
class base {
public:
int foo();
};
</pre></div>
&nbsp;
<div class="code"><pre>
// File: base_module.i
%module base_module
%{
#include "base.h"
%}
%include "base.h"
</pre></div>
&nbsp;
<div class="code"><pre>
// File: derived_module.i
%module derived_module
%import "base_module.i"
%inline %{
class derived : public base {
public:
int bar();
};
%}
</pre></div>
<p>To create the wrapper properly, module <tt>derived_module</tt> needs to know about the
<tt>base</tt> class and that its interface is covered in another module. The
line <tt>%import "base_module.i"</tt> lets SWIG know exactly that. Often
the <tt>.h</tt> file is passed to <tt>%import</tt> instead of the <tt>.i</tt>,
which unfortunately doesn't work for all language modules. For example, Python requires the
name of module that the base class exists in so that the proxy classes can fully inherit the
base class's methods. Typically you will get a warning when the module name is missing, eg:
</p>
<div class="shell"> <pre>
derived_module.i:8: Warning 401: Base class 'base' ignored - unknown module name for base. Either
import
the appropriate module interface file or specify the name of the module in the %import directive.
</pre></div>
<p>
It is sometimes desirable to import the header file rather than the interface file and overcome
the above warning.
For example in the case of the imported interface being quite large, it may be desirable to
simplify matters and just import a small header file of dependent types.
This can be done by specifying the optional <tt>module</tt> attribute in the <tt>%import</tt> directive.
The <tt>derived_module.i</tt> file shown above could be replaced with the following:
<div class="code"><pre>
// File: derived_module.i
%module derived_module
%import(module="base_module") "base.h"
%inline %{
class derived : public base {
public:
int bar();
};
</pre></div>
<p>
Note that "base_module" is the module name and is the same as that specified in <tt>%module</tt>
in <tt>base_module.i</tt> as well as the <tt>%import</tt> in <tt>derived_module.i</tt>.
</p>
<p>
Another issue
to beware of is that multiple dependent wrappers should not be linked/loaded
in parallel from multiple threads as SWIG provides no locking - for more on that
issue, read on.
</p>
<H2><a name="Modules_nn2">16.3 The SWIG runtime code</a></H2>
<p>
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.
</p>
<p>
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.
</p>
<p>
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.
</p>
<p>
There are a few trade offs with this approach. This type information is global
across all SWIG modules loaded, and can cause type conflicts between modules
that were not designed to work together. To solve this approach, the SWIG
runtime code uses a define SWIG_TYPE_TABLE to provide a unique type table. This
behavior can be enabled when compiling the generated _wrap.cxx or _wrap.c file
by adding -DSWIG_TYPE_TABLE=myprojectname to the command line argument.
</p>
<p>
Then, only modules compiled with SWIG_TYPE_TABLE set to myprojectname will share
type information. So if your project has three modules, all three should be
compiled with -DSWIG_TYPE_TABLE=myprojectname, and then these three modules will
share type information. But any other project's types will not interfere or
clash with the types in your module.
</p>
<p>
Another issue relating to the global type table is thread safety. 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, or use SWIG_TYPE_TABLE to
separate type tables so they do not clash with each other.
</p>
<p>
Lastly, SWIG uses a #define SWIG_RUNTIME_VERSION, located in Lib/swigrun.swg and
near the top of every generated module. This number gets incremented when the
data structures change, so that SWIG modules generated with different versions
can peacefully coexist. So the type structures are separated by the
(SWIG_TYPE_TABLE, SWIG_RUNTIME_VERSION) pair, where by default SWIG_TYPE_TABLE
is empty. Only modules compiled with the same pair will share type information.
</p>
<H2><a name="Modules_external_run_time">16.4 External access to the runtime</a></H2>
<p>As described in <a href="Typemaps.html#Typemaps_runtime_type_checker">The run-time type checker</a>,
the functions <tt>SWIG_TypeQuery</tt>, <tt>SWIG_NewPointerObj</tt>, and others sometimes need
to be called. Calling these functions from a typemap is supported, since the typemap code
is embedded into the <tt>_wrap.c</tt> 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, SWIG can be run in a different
mode via <tt>-external-runtime</tt> to generate the run-time instead of the normal mode of
processing an input interface file. For example:
<div class="shell"><pre>
$ swig -python -external-runtime &lt;filename&gt;
</pre></div>
<p>The filename argument is optional and if it is not passed, then the default filename will
be something like <tt>swigpyrun.h</tt>, 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 <tt>SWIG_TypeQuery</tt>,
<tt>SWIG_NewPointerObj</tt>, <tt>SWIG_ConvertPtr</tt> and others. The exact argument parameters
for these functions might differ between language modules; please check the language module chapters
for more information.</p>
<p>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).</p>
<p>
This header will also use the -DSWIG_TYPE_TABLE described above, so when
compiling any code which includes the generated header file should define the
SWIG_TYPE_TABLE to be the same as the module whose types you are trying to
access.
</p>
<H2><a name="Modules_nn4">16.5 A word of caution about static libraries</a></H2>
<p>
When working with multiple SWIG modules, you should take care not to use static
libraries. For example, if you have a static library <tt>libfoo.a</tt> 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 <b>NOT</b> 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.
</p>
<H2><a name="Modules_nn5">16.6 References</a></H2>
<p>
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.
</p>
<H2><a name="Modules_nn6">16.7 Reducing the wrapper file size</a></H2>
<p>
Using multiple modules with the <tt>%import</tt> 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.
</p>
<p>
<b>-fcompact</b><br>
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.
</p>
<p>
<b>-fvirtual</b><br>
This command line option will remove the generation of superfluous virtual method wrappers.
Consider the following inheritance hierarchy:
</p>
<div class="code">
<pre>
struct Base {
virtual void method();
...
};
struct Derived : Base {
virtual void method();
...
};
</pre>
</div>
<p>
Normally wrappers are generated for both methods, whereas this command line option will suppress the generation of a wrapper for <tt>Derived::method</tt>.
Normal polymorphic behaviour remains as <tt>Derived::method</tt> will still be called should you have
a <tt>Derived</tt> instance and call the wrapper for <tt>Base::method</tt>.
</p>
<p>
<b>%feature("compactdefaultargs")</b><br>
This feature can reduce the number of wrapper methods when wrapping methods with default arguments. The section on <a href="SWIGPlus.html#SWIGPlus_default_args">default arguments</a> discusses the feature and its limitations.
</p>
</body>
</html>

View File

@@ -0,0 +1,181 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>SWIG and MzScheme/Racket</title>
<link rel="stylesheet" type="text/css" href="style.css">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body bgcolor="#ffffff">
<H1><a name="Mzscheme">30 SWIG and MzScheme/Racket</a></H1>
<!-- INDEX -->
<div class="sectiontoc">
<ul>
<li><a href="#MzScheme_nn2">Creating native structures</a>
<li><a href="#MzScheme_simple">Simple example</a>
<li><a href="#MzScheme_external_docs">External documentation</a>
</ul>
</div>
<!-- INDEX -->
<p>
This section contains information on SWIG's support of Racket, formally known as MzScheme.
<H2><a name="MzScheme_nn2">30.1 Creating native structures</a></H2>
<p>
Example interface file:
</p>
<div class="code">
<pre>
/* define a macro for the struct creation */
%define handle_ptr(TYPE, NAME)
%typemap(argout) TYPE *NAME{
Scheme_Object *o = SWIG_NewStructFromPtr($1, $*1_mangle);
SWIG_APPEND_VALUE(o);
}
%typemap(in, numinputs=0) TYPE *NAME (TYPE temp) {
$1 = &amp;temp;
}
%enddef
/* setup the typemaps for the pointer to an output parameter cntrs */
handle_ptr(struct diag_cntrs, cntrs);
</pre>
</div>
<p>
Then in scheme, you can use regular struct access procedures like
</p>
<div class="code">
<pre>
; suppose a function created a struct foo as
; (define foo (make-diag-cntrs (#x1 #x2 #x3) (make-inspector))
; Then you can do
(format "0x~x" (diag-cntrs-field1 foo))
(format "0x~x" (diag-cntrs-field2 foo))
;etc...
</pre>
</div>
<H2><a name="MzScheme_simple">30.2 Simple example</a></H2>
<p>
A few examples are available in the Examples/mzscheme directory.
The code and log of a session using SWIG below should help getting started.
</p>
<p>
C header file:
</p>
<div class="code">
<pre>
// example.h
int fact(int n);
</pre>
</div>
<p>
C source code:
</p>
<div class="code">
<pre>
// File: example.c
#include "example.h"
int fact(int n) {
if (n &lt; 0) { /* This should probably return an error, but this is simpler */
return 0;
}
if (n == 0) {
return 1;
}
else {
/* testing for overflow would be a good idea here */
return n * fact(n-1);
}
}
</pre>
</div>
<p>
SWIG interface file:
</p>
<div class="code">
<pre>
/* File: example.i */
%module example
%{
#include "example.h"
%}
int fact(int n);
</pre>
</div>
<p>
The session below using the above files is on an OS X machine, but the points to be made are more general. On OS X, libtool is the tool which creates libraries, which are named .dylib, rather than .so on other unixes, or .dll on Windows.
</p>
<div class="shell">
<pre>
% swig -mzscheme -declaremodule example.i
% gcc -c -m32 -o example.o example.c # force 32-bit object file (mzscheme is 32-bit only)
% libtool -dynamic -o libexample.dylib example.o # make it into a library
% ls # what've we got so far?
example.c example.o
example.h example_wrap.c
example.i libexample.dylib*
% mzc --cgc --cc example_wrap.c # compile the wrapping code
% LDFLAGS="-L. -lexample" mzc --ld example_wrap.dylib example_wrap.o # ...and link it
% mzscheme -e '(path-&gt;string (build-path "compiled" "native" (system-library-subpath)))'
"compiled/native/i386-macosx/3m"
% mkdir -p compiled/native/i386-macosx/3m # move the extension library to a magic place
% mv example_wrap.dylib compiled/native/i386-macosx/3m/example_ss.dylib
% mzscheme
Welcome to MzScheme v4.2.4 [3m], Copyright (c) 2004-2010 PLT Scheme Inc.
&gt; (require "example.ss")
&gt; (fact 5)
120
&gt; ^D
% echo 'It works!'
</pre>
</div>
<p>
Some points of interest:
</p>
<ul>
<li> This is on a 64-bit machine, so we have to include the -m32 option when building the object file
<li> If you want to declare a scheme module (and you probably do), it's important that you include the -declaremodule option to swig (if you miss this out, it'll appear to work, but fail later).
<li> Use mzc to compile and then link the wrapped code. You'll probably need to adjust the link flags to refer to the library you're wrapping (you can either do this with an LDFLAGS declaration, as here, or with multiple ++ldf options to mzc).
<li> Create the directory with path (build-path "compiled" "native" (system-library-subpath)) and move the freshly-generated .dylib to there, changing its name to module-name_ss.dylib. After that, you can REQUIRE the new module with (require "module-name.ss").
<li> The above requests mzc to create an extension using the CGC garbage-collector. The alternative -- the 3m collector -- has generally better performance, but work is still required for SWIG to emit code which is compatible with it.
</ul>
<H2><a name="MzScheme_external_docs">30.3 External documentation</a></H2>
<p>
See the <a href="http://docs.racket-lang.org/inside/index.html">C API</a> for more description of using the mechanism for adding extensions. The main documentation is <a href="http://docs.racket-lang.org/">here</a>.
</p>
<p>
Tip: mzc's --vv option is very useful for debugging the inevitable library problems you'll encounter.
</p>
</body>
</html>

View File

@@ -0,0 +1,994 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>SWIG and Ocaml</title>
<link rel="stylesheet" type="text/css" href="style.css">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body bgcolor="#ffffff">
<H1><a name="Ocaml">31 SWIG and Ocaml</a></H1>
<!-- INDEX -->
<div class="sectiontoc">
<ul>
<li><a href="#Ocaml_nn2">Preliminaries</a>
<ul>
<li><a href="#Ocaml_nn3">Running SWIG</a>
<li><a href="#Ocaml_nn4">Compiling the code</a>
<li><a href="#Ocaml_nn5">The camlp4 module</a>
<li><a href="#Ocaml_nn6">Using your module</a>
<li><a href="#Ocaml_nn7">Compilation problems and compiling with C++</a>
</ul>
<li><a href="#Ocaml_nn8">The low-level Ocaml/C interface</a>
<ul>
<li><a href="#Ocaml_nn9">The generated module</a>
<li><a href="#Ocaml_nn10">Enums</a>
<ul>
<li><a href="#Ocaml_nn11">Enum typing in Ocaml</a>
</ul>
<li><a href="#Ocaml_nn12">Arrays</a>
<ul>
<li><a href="#Ocaml_nn13">Simple types of bounded arrays</a>
<li><a href="#Ocaml_nn14">Complex and unbounded arrays</a>
<li><a href="#Ocaml_nn15">Using an object</a>
<li><a href="#Ocaml_nn16">Example typemap for a function taking float * and int</a>
</ul>
<li><a href="#Ocaml_nn17">C++ Classes</a>
<ul>
<li><a href="#Ocaml_nn18">STL vector and string Example</a>
<li><a href="#Ocaml_nn19">C++ Class Example</a>
<li><a href="#Ocaml_nn20">Compiling the example</a>
<li><a href="#Ocaml_nn21">Sample Session</a>
</ul>
<li><a href="#Ocaml_nn22">Director Classes</a>
<ul>
<li><a href="#Ocaml_nn23">Director Introduction</a>
<li><a href="#Ocaml_nn24">Overriding Methods in Ocaml</a>
<li><a href="#Ocaml_nn25">Director Usage Example</a>
<li><a href="#Ocaml_nn26">Creating director objects</a>
<li><a href="#Ocaml_nn27">Typemaps for directors, directorin, directorout, directorargout</a>
<li><a href="#Ocaml_nn28">typemap</a>
<li><a href="#Ocaml_nn29">directorout typemap</a>
<li><a href="#Ocaml_nn30">directorargout typemap</a>
</ul>
<li><a href="#Ocaml_nn31">Exceptions</a>
</ul>
</ul>
</div>
<!-- INDEX -->
<p>
This chapter describes SWIG's support of Ocaml.
</p>
<p>
Ocaml is a relatively recent addition to the ML family,
and is a recent addition to SWIG. It's the second compiled, typed
language to be added. Ocaml has widely acknowledged benefits for engineers,
mostly derived from a sophisticated type system, compile-time checking
which eliminates several classes of common programming errors, and good
native performance. While all of this is wonderful, there are well-written
C and C++ libraries that Ocaml users will want to take advantage of as
part of their arsenal (such as SSL and gdbm), as well as their own mature
C and C++ code. SWIG allows this code to be used in a natural, type-safe
way with Ocaml, by providing the necessary, but repetitive glue code
which creates and uses Ocaml values to communicate with C and C++ code.
In addition, SWIG also produces the needed Ocaml source that binds
variants, functions, classes, etc.
</p>
<p>
If you're not familiar with the Objective Caml language, you can visit
<a href="http://ocaml.org/">The Ocaml Website</a>.
</p>
<H2><a name="Ocaml_nn2">31.1 Preliminaries</a></H2>
<p>
SWIG 3.0 works with Ocaml 3.08.3 and above. Given the choice,
you should use the latest stable release. The SWIG Ocaml module has
been tested on Linux (x86, PPC, Sparc) and Cygwin on Windows. The
best way to determine whether your system will work is to compile the
examples and test-suite which come with SWIG. You can do this by running
<tt>make check</tt> from the SWIG root directory after installing SWIG.
The Ocaml module has been tested using the system's dynamic linking (the
usual -lxxx against libxxx.so, as well as with Gerd Stolpmann's
<a href="http://download.camlcity.org/download/">Dl package</a>.
The ocaml_dynamic and ocaml_dynamic_cpp targets in the
file Examples/Makefile illustrate how to compile and link SWIG modules that
will be loaded dynamically. This has only been tested on Linux so far.
</p>
<H3><a name="Ocaml_nn3">31.1.1 Running SWIG</a></H3>
<p>
The basics of getting a SWIG Ocaml module up and running
can be seen from one of SWIG's example Makefiles, but is also described
here. To build an Ocaml module, run SWIG using the <tt>-ocaml</tt>
option.
</p>
<div class="code">
<pre>
%swig -ocaml example.i
</pre>
</div>
<p>This will produce 3 files. The file <tt>example_wrap.c</tt> contains
all of the C code needed to build an Ocaml module. To build the module,
you will compile the file <tt>example_wrap.c</tt> with <tt>ocamlc</tt> or
<tt>ocamlopt</tt> to create the needed .o file. You will need to compile
the resulting .ml and .mli files as well, and do the final link with -custom
(not needed for native link).</p>
<H3><a name="Ocaml_nn4">31.1.2 Compiling the code</a></H3>
<p>
The OCaml SWIG module now requires you to compile a module (<tt>Swig</tt>)
separately. In addition to aggregating common SWIG functionality, the Swig
module contains the data structure that represents C/C++ values. This allows
easier data sharing between modules if two or more are combined, because
the type of each SWIG'ed module's c_obj is derived from Swig.c_obj_t. This
also allows SWIG to acquire new conversions painlessly, as well as giving
the user more freedom with respect to custom typing.
Use <tt>ocamlc</tt> or <tt>ocamlopt</tt> to compile your SWIG interface like:
</p>
<div class="code">
<pre>
% swig -ocaml -co swig.mli ; swig -ocaml co swig.ml
% ocamlc -c swig.mli ; ocamlc -c swig.ml
% ocamlc -c -ccopt "-I/usr/include/foo" example_wrap.c
% ocamlc -c example.mli
% ocamlc -c example.ml
</pre>
</div>
<p><tt>ocamlc</tt> is aware of .c files and knows how to handle them. Unfortunately,
it does not know about .cxx, .cc, or .cpp files, so when SWIG is invoked
in C++ mode, you must:</p>
<div class="code">
<pre>
% cp example_wrap.cxx example_wrap.cxx.c
% ocamlc -c ... -ccopt -xc++ example_wrap.cxx.c
% ...
</pre>
</div>
<H3><a name="Ocaml_nn5">31.1.3 The camlp4 module</a></H3>
<p>
The camlp4 module (swigp4.ml -&gt; swigp4.cmo) contains a simple rewriter which
makes C++ code blend more seamlessly with objective caml code. Its use is
optional, but encouraged. The source file is included in the Lib/ocaml
directory of the SWIG source distribution. You can checkout this file with
<tt>"swig -ocaml -co swigp4.ml"</tt>. You should compile the file with
<tt>"ocamlc -I `camlp4 -where` -pp 'camlp4o pa_extend.cmo q_MLast.cmo' -c swigp4.ml"</tt>
</p>
<p>
The basic principle of the module is to recognize certain non-caml expressions
and convert them for use with C++ code as interfaced by SWIG. The camlp4
module is written to work with generated SWIG interfaces, and probably isn't
great to use with anything else.
</p>
<p>
Here are the main rewriting rules:
</p>
<table border="1" summary="Rewriting rules">
<tr><th>Input</th><th>Rewritten to</th></tr>
<tr><td>f'( ... ) as in<br> atoi'("0") or<br> _exit'(0)</td>
<td>f(C_list [ ... ]) as in<br> atoi (C_list [ C_string "0" ]) or<br> _exit (C_list [ C_int 0 ])</td></tr>
<tr><td>object -&gt; method ( ... )</td><td>(invoke object) "method" (C_list [ ... ])</td></tr>
<tr><td>
object <i>'binop</i> argument as in<br>
a '+= b</td>
<td>
(invoke object) "+=" argument as in<br>
(invoke a) "+=" b<td></tr>
<tr><th colspan=2>Note that because camlp4 always recognizes &lt;&lt;
and &gt;&gt;, they are replaced by lsl and lsr in operator names.
<tr><td>
<i>'unop</i> object as in<br>
'! a
</td><td>
(invoke a) "!" C_void</td></tr>
<tr><td>
<b>Smart pointer access like this</b><br>
object '-&gt; method ( args )<br>
</td><td>
(invoke (invoke object "-&gt;" C_void))
</td></tr>
<tr><td>
<b>Invoke syntax</b><br>
object . '( ... )
</td><td>
(invoke object) "()" (C_list [ ... ])
</td></tr>
<tr><td>
<b>Array syntax</b><br>
object '[ 10 ]
</td><td>
(invoke object) "[]" (C_int 10)
</td></tr>
<tr><td>
<b>Assignment syntax</b><br>
let a = '10 and b = '"foo" and c = '1.0 and d = 'true
</td><td>
let a = C_int 10 and b = C_string "foo" and c = C_double 1.0 and d = C_bool true
</td></tr>
<tr><td>
<b>Cast syntax</b><br>
let a = _atoi '("2") as int<br>
let b = (getenv "PATH") to string<br>
This works for int, string, float, bool
</td><td>
let a = get_int (_atoi (C_string "2"))<br>
let b = C_string (getenv "PATH")
</td></tr>
</table>
<H3><a name="Ocaml_nn6">31.1.4 Using your module</a></H3>
<p>
You can test-drive your module by building a
toplevel ocaml interpreter. Consult the ocaml manual for details.
</p>
<p>
When linking any ocaml bytecode with your module, use the -custom
option to build your functions into the primitive list. This
option is not needed when you build native code.
</p>
<H3><a name="Ocaml_nn7">31.1.5 Compilation problems and compiling with C++</a></H3>
<p>
As mentioned above, .cxx files need special
handling to be compiled with <tt>ocamlc</tt>. Other than that, C code
that uses <tt>class</tt> as a non-keyword, and C code that is too
liberal with pointer types may not compile under the C++ compiler.
Most code meant to be compiled as C++ will not have problems.
</p>
<H2><a name="Ocaml_nn8">31.2 The low-level Ocaml/C interface</a></H2>
<p>
In order to provide access to overloaded functions, and
provide sensible outputs from them, all C entities are represented as
members of the c_obj type:
</p>
<p>
In the code as seen by the typemap
writer, there is a value, swig_result, that always contains the
current return data. It is a list, and must be appended with the
caml_list_append function, or with functions and macros provided by
objective caml.
</p>
<div class="code"><pre>
type c_obj =
C_void
| C_bool of bool
| C_char of char
| C_uchar of char
| C_short of int
| C_ushort of int
| C_int of int
| C_uint of int32
| C_int32 of int32
| C_int64 of int64
| C_float of float
| C_double of float
| C_ptr of int64 * int64
| C_array of c_obj array
| C_list of c_obj list
| C_obj of (string -&gt; c_obj -&gt; c_obj)
| C_string of string
| C_enum of c_enum_t
</pre></div>
<p>
A few functions exist which generate and return these:
</p>
<ul>
<li>caml_ptr_val receives a c_obj and returns a void *. This
should be used for all pointer purposes.</li>
<li>caml_long_val receives a c_obj and returns a long. This
should be used for most integral purposes.</li>
<li>caml_val_ptr receives a void * and returns a c_obj.</li>
<li>caml_val_bool receives a C int and returns a c_obj representing
its bool value.</li>
<li>caml_val_(u)?(char|short|int|long|float|double) receives an
appropriate C value and returns a c_obj representing it.</li>
<li>caml_val_string receives a char * and returns a string value.</li>
<li>caml_val_string_len receives a char * and a length and returns
a string value.</li>
<li>caml_val_obj receives a void * and an object type and returns
a C_obj, which contains a closure giving method access.</li>
</ul>
<p>
Because of this style, a typemap can return any kind of value it
wants from a function. This enables out typemaps and inout typemaps
to work well. The one thing to remember about outputting values
is that you must append them to the return list with swig_result = caml_list_append(swig_result, v).
</p>
<p>
This function will return a new list that has your element
appended. Upon return to caml space, the fnhelper function
beautifies the result. A list containing a single item degrades to
only that item (i.e. [ C_int 3 ] -&gt; C_int 3), and a list
containing more than one item is wrapped in C_list (i.e. [ C_char
'a' ; C_char 'b' -&gt; C_list [ C_char 'a' ; C_char b
]). This is in order to make return values easier to handle
when functions have only one return value, such as constructors,
and operators. In addition, string, pointer, and object
values are interchangeable with respect to caml_ptr_val, so you can
allocate memory as caml strings and still use the resulting
pointers for C purposes, even using them to construct simple objects
on. Note, though, that foreign C++ code does not respect the garbage
collector, although the SWIG interface does.</p>
<p>
The wild card type that you can use in lots of different ways is
C_obj. It allows you to wrap any type of thing you like as an
object using the same mechanism that the ocaml module
does. When evaluated in caml_ptr_val, the returned value is
the result of a call to the object's "&amp;" operator, taken as a pointer.
</p>
<p>
You should only construct values using objective caml, or using the
functions caml_val_* functions provided as static functions to a SWIG
ocaml module, as well as the caml_list_* functions. These functions
provide everything a typemap needs to produce values. In addition,
value items pass through directly, but you must make your own type
signature for a function that uses value in this way.
</p>
<H3><a name="Ocaml_nn9">31.2.1 The generated module</a></H3>
<p>
The SWIG <tt>%module</tt> directive specifies the name of the Ocaml
module to be generated. If you specified `<tt>%module example</tt>',
then your Ocaml code will be accessible in the module Example. The
module name is always capitalized as is the ocaml convention. Note
that you must not use any Ocaml keyword to name your module. Remember
that the keywords are not the same as the C++ ones.
</p>
<p>
You can introduce extra code into the output wherever you like with SWIG.
These are the places you can introduce code:
<table border="1" summary="Extra code sections">
<tr><td>"header"</td><td>This code is inserted near the beginning of the
C wrapper file, before any function definitions.</td></tr>
<tr><td>"wrapper"</td><td>This code is inserted in the function definition
section.</td></tr>
<tr><td>"runtime"</td><td>This code is inserted near the end of the C wrapper
file.</td></tr>
<tr><td>"mli"</td><td>This code is inserted into the caml interface file.
Special signatures should be inserted here.
</td></tr>
<tr><td>"ml"</td><td>This code is inserted in the caml code defining the
interface to your C code. Special caml code, as well as any initialization
which should run when the module is loaded may be inserted here.
</td></tr>
<tr><td>"classtemplate"</td><td>The "classtemplate" place is special because
it describes the output SWIG will generate for class definitions.
</td></tr>
</table>
<H3><a name="Ocaml_nn10">31.2.2 Enums</a></H3>
<p>
SWIG will wrap enumerations as polymorphic variants in the output
Ocaml code, as above in C_enum. In order to support all
C++-style uses of enums, the function int_to_enum and enum_to_int are
provided for ocaml code to produce and consume these values as
integers. Other than that, correct uses of enums will not have
a problem. Since enum labels may overlap between enums, the
enum_to_int and int_to_enum functions take an enum type label as an
argument. Example:
</p>
<div class="code"><pre>
%module enum_test
%{
enum c_enum_type { a = 1, b, c = 4, d = 8 };
%}
enum c_enum_type { a = 1, b, c = 4, d = 8 };
</pre></div>
<p>
The output mli contains:
</p>
<div class="code"><pre>
type c_enum_type = [
`unknown
| `c_enum_type
]
type c_enum_tag = [
`int of int
| `a
| `b
| `c
| `d
]
val int_to_enum c_enum_type -&gt; int -&gt; c_obj
val enum_to_int c_enum_type -&gt; c_obj -&gt; c_obj
</pre>
</div>
<p>
So it's possible to do this:
</p>
<div class="code">
<pre>
bash-2.05a$ ocamlmktop -custom enum_test_wrap.o enum_test.cmo -o enum_test_top
bash-2.05a$ ./enum_test_top
Objective Caml version 3.04
# open Enum_test ;;
# let x = C_enum `a ;;
val x : Enum_test.c_obj = C_enum `a
# enum_to_int `c_enum_type x ;;
- : Enum_test.c_obj = C_int 1
# int_to_enum `c_enum_type 4 ;;
- : Enum_test.c_obj = C_enum `c
</pre>
</div>
<H4><a name="Ocaml_nn11">31.2.2.1 Enum typing in Ocaml</a></H4>
<p>
The ocaml SWIG module now has support for loading and using multiple SWIG
modules at the same time. This enhances modularity, but presents problems
when used with a language which assumes that each module's types are complete
at compile time. In order to achieve total soundness enum types are now
isolated per-module. The type issue matters when values are shared between
functions imported from different modules. You must convert values to master
values using the swig_val function before sharing them with another module.
</p>
<H3><a name="Ocaml_nn12">31.2.3 Arrays</a></H3>
<H4><a name="Ocaml_nn13">31.2.3.1 Simple types of bounded arrays</a></H4>
<p>
SWIG has support for array types, but you generally will need to provide
a typemap to handle them. You can currently roll your own, or expand
some of the macros provided (but not included by default) with the SWIG
distribution.
</p>
<p>
By including "carray.i", you will get access to some macros that help you
create typemaps for array types fairly easily.
</p>
<p>
<tt>%make_simple_array_typemap</tt> is the easiest way to get access to
arrays of simple types with known bounds in your code, but this only works
for arrays whose bounds are completely specified.
</p>
<H4><a name="Ocaml_nn14">31.2.3.2 Complex and unbounded arrays</a></H4>
<p>
Unfortunately, unbounded arrays and pointers can't be handled in a
completely general way by SWIG, because the end-condition of such an
array can't be predicted. In some cases, it will be by consent
(e.g. an array of four or more chars), sometimes by explicit length
(char *buffer, int len), and sometimes by sentinel value (0, -1, etc.).
SWIG can't predict which of these methods will be used in the array,
so you have to specify it for yourself in the form of a typemap.
</p>
<H4><a name="Ocaml_nn15">31.2.3.3 Using an object</a></H4>
<p>
It's possible to use C++ to your advantage by creating a simple object that
provides access to your array. This may be more desirable in some cases,
since the object can provide bounds checking, etc., that prevents crashes.
</p>
<p>
Consider writing an object when the ending condition of your array is complex,
such as using a required sentinel, etc.
</p>
<H4><a name="Ocaml_nn16">31.2.3.4 Example typemap for a function taking float * and int</a></H4>
<p>
This is a simple example <tt>in</tt> typemap for an array of float, where the
length of the array is specified as an extra parameter. Other such typemaps
will work similarly. In the example, the function printfloats is called with
a float array, and specified length. The actual length reported in the len
argument is the length of the array passed from ocaml, making passing an array
into this type of function convenient.
</p>
<table border="1" bgcolor="#dddddd" summary="float * and int typemap example">
<tr><th><center>tarray.i</center></th></tr>
<tr><td><pre>
%module tarray
%{
#include &lt;stdio.h&gt;
void printfloats( float *tab, int len ) {
int i;
for( i = 0; i &lt; len; i++ ) {
printf( "%f ", tab[i] );
}
printf( "\n" );
}
%}
%typemap(in) (float *tab, int len) {
int i;
/* $*1_type */
$2 = caml_array_len($input);
$1 = ($*1_type *)malloc( $2 * sizeof( float ) );
for( i = 0; i &lt; $2; i++ ) {
$1[i] = caml_double_val(caml_array_nth($input, i));
}
}
void printfloats( float *tab, int len );
</pre></td></tr>
<tr><th>Sample Run</th></tr>
<tr><td><pre>
# open Tarray ;;
# _printfloats (C_array [| C_double 1.0 ; C_double 3.0 ; C_double 5.6666 |]) ;;
1.000000 3.000000 5.666600
- : Tarray.c_obj = C_void
</pre></td></tr></table>
<H3><a name="Ocaml_nn17">31.2.4 C++ Classes</a></H3>
<p>
C++ classes, along with structs and unions are represented by C_obj
(string -&gt; c_obj -&gt; c_obj) wrapped closures. These objects
contain a method list, and a type, which allow them to be used like
C++ objects. When passed into typemaps that use pointers, they
degrade to pointers through their "&amp;" method. Every method
an object has is represented as a string in the object's method table,
and each method table exists in memory only once. In addition
to any other operators an object might have, certain builtin ones are
provided by SWIG: (all of these take no arguments (C_void))
</p>
<table summary="SWIG provided operators">
<tr><td>"~"</td><td>Delete this object</td></tr>
<tr><td>"&amp;"</td><td>Return an ordinary C_ptr value representing this
object's address</td></tr>
<tr><td>"sizeof"</td><td>If enabled with ("sizeof"="1") on the module node,
return the object's size in char.</td></tr>
<tr><td>":methods"</td><td>Returns a list of strings containing the names of
the methods this object contains</td></tr>
<tr><td>":classof"</td><td>Returns the name of the class this object belongs
to.</td></tr>
<tr><td>":parents"</td><td>Returns a list of all direct parent classes which
have been wrapped by SWIG.</td></tr>
<tr><td>"::[parent-class]"</td><td>Returns a view of the object as the
indicated parent class. This is mainly used internally by the SWIG module,
but may be useful to client programs.</td></tr>
<tr><td>"[member-variable]"</td><td>Each member variable is wrapped as a
method with an optional parameter.
Called with one argument, the member variable is set to the value of the
argument. With zero arguments, the value is returned.
</td></tr>
</table>
<p>
Note that this string belongs to the wrapper object, and not
the underlying pointer, so using create_[x]_from_ptr alters the
returned value for the same object.
</p>
<H4><a name="Ocaml_nn18">31.2.4.1 STL vector and string Example</a></H4>
<p>
Standard typemaps are now provided for STL vector and string. More are in
the works. STL strings are passed just like normal strings, and returned
as strings. STL string references don't mutate the original string, (which
might be surprising), because Ocaml strings are mutable but have fixed
length. Instead, use multiple returns, as in the argout_ref example.
</p>
<table border="1" bgcolor="#dddddd" summary="STL vector and string example">
<tr><th><center>example.i</center></th></tr>
<tr><td><pre>
%module example
%{
#include "example.h"
%}
%include &lt;stl.i&gt;
namespace std {
%template(StringVector) std::vector &lt; string &gt;;
};
%include "example.h"
</pre></td></tr>
<tr><td><font size="-1"><i>This example is in Examples/ocaml/stl
</i></font></td></tr>
</table>
<p>
Since there's a makefile in that directory, the example is easy to build.
</p>
<p>
Here's a sample transcript of an interactive session using a string vector
after making a toplevel (make toplevel). This example uses the camlp4
module.
</p>
<div class="code"><pre>
bash-2.05a$ ./example_top
Objective Caml version 3.06
Camlp4 Parsing version 3.06
# open Swig ;;
# open Example ;;
# let x = new_StringVector '() ;;
val x : Example.c_obj = C_obj &lt;fun&gt;
# x -&gt; ":methods" () ;;
- : Example.c_obj =
C_list
[C_string "nop"; C_string "size"; C_string "empty"; C_string "clear";
C_string "push_back"; C_string "[]"; C_string "="; C_string "set";
C_string "~"; C_string "&amp;"; C_string ":parents"; C_string ":classof";
C_string ":methods"]
# x -&gt; push_back ("foo") ;;
- : Example.c_obj = C_void
# x -&gt; push_back ("bar") ;;
- : Example.c_obj = C_void
# x -&gt; push_back ("baz") ;;
- : Example.c_obj = C_void
# x '[1] ;;
- : Example.c_obj = C_string "bar"
# x -&gt; set (1, "spam") ;;
- : Example.c_obj = C_void
# x '[1] ;;
- : Example.c_obj = C_string "spam"
# for i = 0 to (x -&gt; size() as int) - 1 do
print_endline ((x '[i to int]) as string)
done ;;
foo
bar
baz
- : unit = ()
#
</pre></div>
<H4><a name="Ocaml_nn19">31.2.4.2 C++ Class Example</a></H4>
<p>
Here's a simple example using Trolltech's Qt Library:
</p>
<table border="1" bgcolor="#dddddd" summary="Qt Library example">
<tr><th><center>qt.i</center></th></tr>
<tr><td><pre>
%module qt
%{
#include &lt;qapplication.h&gt;
#include &lt;qpushbutton.h&gt;
%}
class QApplication {
public:
QApplication( int argc, char **argv );
void setMainWidget( QWidget *widget );
void exec();
};
class QPushButton {
public:
QPushButton( char *str, QWidget *w );
void resize( int x, int y );
void show();
};
</pre></td></tr></table>
<H4><a name="Ocaml_nn20">31.2.4.3 Compiling the example</a></H4>
<div class="code"><pre>
bash-2.05a$ QTPATH=/your/qt/path
bash-2.05a$ for file in swig.mli swig.ml swigp4.ml ; do swig -ocaml -co $file ; done
bash-2.05a$ ocamlc -c swig.mli ; ocamlc -c swig.ml
bash-2.05a$ ocamlc -I `camlp4 -where` -pp "camlp4o pa_extend.cmo q_MLast.cmo" -c swigp4.ml
bash-2.05a$ swig -ocaml -c++ -I$QTPATH/include qt.i
bash-2.05a$ mv qt_wrap.cxx qt_wrap.c
bash-2.05a$ ocamlc -c -ccopt -xc++ -ccopt -g -g -ccopt -I$QTPATH/include qt_wrap.c
bash-2.05a$ ocamlc -c qt.mli
bash-2.05a$ ocamlc -c qt.ml
bash-2.05a$ ocamlmktop -custom swig.cmo -I `camlp4 -where` \
camlp4o.cma swigp4.cmo qt_wrap.o qt.cmo -o qt_top -cclib \
-L$QTPATH/lib -cclib -lqt
</pre></div>
<H4><a name="Ocaml_nn21">31.2.4.4 Sample Session</a></H4>
<div class="code"><pre>
bash-2.05a$ ./qt_top
Objective Caml version 3.06
Camlp4 Parsing version 3.06
# open Swig ;;
# open Qt ;;
# let a = new_QApplication '(0, 0) ;;
val a : Qt.c_obj = C_obj &lt;fun&gt;
# let hello = new_QPushButton '("hi", 0) ;;
val hello : Qt.c_obj = C_obj &lt;fun&gt;
# hello -&gt; resize (100, 30) ;;
- : Qt.c_obj = C_void
# hello -&gt; show () ;;
- : Qt.c_obj = C_void
# a -&gt; exec () ;;
</pre></div>
<p>
Assuming you have a working installation of QT, you will see a window
containing the string "hi" in a button.
</p>
<H3><a name="Ocaml_nn22">31.2.5 Director Classes</a></H3>
<H4><a name="Ocaml_nn23">31.2.5.1 Director Introduction</a></H4>
<p>
Director classes are classes which allow Ocaml code to override the public
methods of a C++ object. This facility allows the user to use C++ libraries
that require a derived class to provide application specific functionality in
the context of an application or utility framework.
</p>
<p>
You can turn on director classes by using an optional module argument like
this:
</p>
<div class="code"><pre>
%module(directors="1")
...
// Turn on the director class for a specific class like this:
%feature("director")
class foo {
...
};
</pre></div>
<H4><a name="Ocaml_nn24">31.2.5.2 Overriding Methods in Ocaml</a></H4>
<p>
Because the Ocaml language module treats C++ method calls as calls to a
certain function, all you need to do is to define the function that will
handle the method calls in terms of the public methods of the object, and
any other relevant information. The function <tt>new_derived_object</tt>
uses a stub class to call your methods in place of the ones provided by the
underlying implementation. The object you receive is the underlying object,
so you are free to call any methods you want from within your derived method.
Note that calls to the underlying object do not invoke Ocaml code. You need
to handle that yourself.
</p>
<p>
<tt>new_derived_object</tt> receives your function, the function that creates
the underlying object, and any constructor arguments, and provides an
object that you can use in any usual way. When C++ code calls one of the
object's methods, the object invokes the Ocaml function as if it had been
invoked from Ocaml, allowing any method definitions to override the C++ ones.
</p>
<p>
In this example, I'll examine the objective caml code involved in providing
an overloaded class. This example is contained in Examples/ocaml/shapes.
</p>
<H4><a name="Ocaml_nn25">31.2.5.3 Director Usage Example</a></H4>
<table border="1" bgcolor="#dddddd" summary="Director usage example">
<tr><th><center>example_prog.ml</center>
</th></tr>
<tr><td><pre>
open Swig
open Example
...
let triangle_class pts ob meth args =
match meth with
"cover" -&gt;
(match args with
C_list [ x_arg ; y_arg ] -&gt;
let xa = x_arg as float
and ya = y_arg as float in
(point_in_triangle pts xa ya) to bool
| _ -&gt; raise (Failure "cover needs two double arguments."))
| _ -&gt; (invoke ob) meth args ;;
let triangle =
new_derived_object
new_shape
(triangle_class ((0.0, 0.0), (0.5, 1.0), (1.0, 0.0)))
'() ;;
let _ = _draw_shape_coverage '(triangle, C_int 60, C_int 20) ;;
</pre></td></tr>
</table>
<p>
This is the meat of what you need to do. The actual "class" definition
containing the overloaded method is defined in the function triangle_class.
This is a lot like the class definitions emitted by SWIG, if you look at
example.ml, which is generated when SWIG consumes example.i. Basically,
you are given the arguments as a c_obj and the method name as a string, and
you must intercept the method you are interested in and provide whatever
return value you need. Bear in mind that the underlying C++ code needs the
right return type, or an exception will be thrown. This exception will
generally be Failure, or NotObject. You must call other ocaml methods that
you rely on yourself. Due to the way directors are implemented, method
calls on your object from with ocaml code will always invoke C++ methods
even if they are overridden in ocaml.
</p>
<p>
In the example, the draw_shape_coverage function plots the indicated number
of points as either covered (<tt>x</tt>) or uncovered ( ) between
0 and 1 on the X and Y axes. Your shape implementation can provide any
coverage map it likes, as long as it responds to the "cover" method call
with a boolean return (the underlying method returns bool). This might allow
a tricky shape implementation, such as a boolean combination, to be expressed
in a more effortless style in ocaml, while leaving the "engine" part of the
program in C++.
</p>
<H4><a name="Ocaml_nn26">31.2.5.4 Creating director objects</a></H4>
<p>
The definition of the actual object triangle can be described this way:
</p>
<div class="code"><pre>
let triangle =
new_derived_object
new_shape
(triangle_class ((0.0, 0.0), (0.5, 1.0), (1.0, 0.0)))
'()
</pre></div>
<p>
The first argument to <tt>new_derived_object</tt>, new_shape is the method
which returns a shape instance. This function will be invoked with the
third argument will be appended to the argument list [ C_void ]. In the
example, the actual argument list is sent as (C_list [ C_void ; C_void ]).
The augmented constructor for a director class needs the first argument
to determine whether it is being constructed as a derived object, or as
an object of the indicated type only (in this case <tt>shape</tt>). The
Second argument is a closure that will be added to the final C_obj.
</p>
<p>
The actual object passed to the self parameter of the director object will
be a C_director_core, containing a c_obj option ref and a c_obj. The
c_obj provided is the same object that will be returned from new_derived
object, that is, the object exposing the overridden methods. The other part
is an option ref that will have its value extracted before becoming the
<tt>ob</tt> parameter of your class closure. This ref will contain
<tt>None</tt> if the C++ object underlying is ever destroyed, and will
consequently trigger an exception when any method is called on the object
after that point (the actual raise is from an inner function used by
new_derived_object, and throws NotObject). This prevents a deleted C++
object from causing a core dump, as long as the object is destroyed
properly.
</p>
<H4><a name="Ocaml_nn27">31.2.5.5 Typemaps for directors, directorin, directorout, directorargout</a></H4>
<p>
Special typemaps exist for use with directors, the <tt>directorin, directorout, directorargout</tt>
are used in place of <tt>in, out, argout</tt> typemaps, except that their
direction is reversed. They provide for you to provide argout values, as
well as a function return value in the same way you provide function arguments,
and to receive arguments the same way you normally receive function returns.
</p>
<H4><a name="Ocaml_nn28">31.2.5.6 typemap</a></H4>
<p>
The <tt>directorin</tt> typemap is used when you will receive arguments from a call
made by C++ code to you, therefore, values will be translated from C++ to
ocaml. You must provide some valid C_obj value. This is the value your ocaml
code receives when you are called. In general, a simple <tt>directorin</tt> typemap
can use the same body as a simple <tt>out</tt> typemap.
</p>
<H4><a name="Ocaml_nn29">31.2.5.7 directorout typemap</a></H4>
<p>
The <tt>directorout</tt> typemap is used when you will send an argument from your
code back to the C++ caller. That is; directorout specifies a function return
conversion. You can usually use the same body as an <tt>in</tt> typemap
for the same type, except when there are special requirements for object
ownership, etc.
</p>
<H4><a name="Ocaml_nn30">31.2.5.8 directorargout typemap</a></H4>
<p>
C++ allows function arguments which are by pointer (*) and by reference (&amp;)
to receive a value from the called function, as well as sending one there.
Sometimes, this is the main purpose of the argument given. <tt>directorargout</tt>
typemaps allow your caml code to emulate this by specifying additional return
values to be put into the output parameters. The SWIG ocaml module is a bit
loose in order to make code easier to write. In this case, your return to
the caller must be a list containing the normal function return first, followed
by any argout values in order. These argout values will be taken from the
list and assigned to the values to be returned to C++ through directorargout typemaps.
In the event that you don't specify all of the necessary values, integral
values will read zero, and struct or object returns have undefined results.
</p>
<H3><a name="Ocaml_nn31">31.2.6 Exceptions</a></H3>
<p>
Catching exceptions is now supported using SWIG's %exception feature. A simple
but not too useful example is provided by the throw_exception testcase in
Examples/test-suite. You can provide your own exceptions, too.
</p>
</body>
</html>

View File

@@ -0,0 +1,909 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>SWIG and Octave</title>
<link rel="stylesheet" type="text/css" href="style.css">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body bgcolor="#ffffff">
<H1><a name="Octave">32 SWIG and Octave</a></H1>
<!-- INDEX -->
<div class="sectiontoc">
<ul>
<li><a href="#Octave_nn2">Preliminaries</a>
<li><a href="#Octave_nn3">Running SWIG</a>
<ul>
<li><a href="#Octave_nn4">Command-line options</a>
<li><a href="#Octave_nn5">Compiling a dynamic module</a>
<li><a href="#Octave_nn6">Using your module</a>
</ul>
<li><a href="#Octave_nn7">A tour of basic C/C++ wrapping</a>
<ul>
<li><a href="#Octave_nn8">Modules</a>
<li><a href="#Octave_nn9">Functions</a>
<li><a href="#Octave_nn10">Global variables</a>
<li><a href="#Octave_nn11">Constants and enums</a>
<li><a href="#Octave_nn12">Pointers</a>
<li><a href="#Octave_nn13">Structures and C++ classes</a>
<li><a href="#Octave_nn15">C++ inheritance</a>
<li><a href="#Octave_nn17">C++ overloaded functions</a>
<li><a href="#Octave_nn18">C++ operators</a>
<li><a href="#Octave_nn19">Class extension with %extend</a>
<li><a href="#Octave_nn20">C++ templates</a>
<li><a href="#Octave_nn21">C++ Smart Pointers</a>
<ul>
<li><a href="#Octave_smart_pointers_shared_ptr">The shared_ptr Smart Pointer</a>
<li><a href="#Octave_smart_pointers_generic">Generic Smart Pointers</a>
</ul>
<li><a href="#Octave_nn22">Directors (calling Octave from C++ code)</a>
<li><a href="#Octave_nn23">Threads</a>
<li><a href="#Octave_nn24">Memory management</a>
<li><a href="#Octave_nn25">STL support</a>
<li><a href="#Octave_nn26">Matrix typemaps</a>
</ul>
</ul>
</div>
<!-- INDEX -->
<p>
Octave is a high-level language intended for numerical programming that is mostly compatible with MATLAB.
More information can be found at <a href="http://www.gnu.org/software/octave/">Octave web site</a>.
</p>
<p>
This chapter is intended to give an introduction to using the module. You should also read the SWIG documentation that is not specific to Octave.
Also, there are a dozen or so examples in the Examples/octave directory, and hundreds in the test suite (Examples/test-suite and Examples/test-suite/octave).
</p>
<H2><a name="Octave_nn2">32.1 Preliminaries</a></H2>
<p>
SWIG is regularly tested against the following versions of Octave: 3.8, 4.0, 4.2.
</p>
<p>
Every effort is made to maintain backward compatibility with older versions of Octave.
This cannot be guaranteed however, as in recent times new Octave releases have required nontrivial updates to SWIG, which may break backward compatibility for older Octave versions against which SWIG is not regularly tested.
</p>
<p>
The SWIG runtime exports the function <tt>swig_octave_prereq()</tt> for checking the version of Octave.
</p>
<H2><a name="Octave_nn3">32.2 Running SWIG</a></H2>
<p>
Let's start with a very simple SWIG interface file, example.i:
</p>
<div class="code"><pre>
%module swigexample
%{
#include "example.h"
%}
int gcd(int x, int y);
extern double Foo; </pre></div>
<p>
To build an Octave module when wrapping C code, run SWIG using the <tt>-octave</tt> option:
</p>
<div class="shell"><pre>$ swig -octave -o example_wrap.cpp example.i </pre></div>
<p>
The <tt>-c++</tt> option is also required when wrapping C++ code:
</p>
<div class="shell"><pre>$ swig -octave -c++ -o example_wrap.cpp example.i </pre></div>
<p>
This creates a C++ source file "example_wrap.cpp". A C++ file is generated even when wrapping C code as Octave is itself written in C++ and requires wrapper code to be in the same language. 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 (in this case, the gcd implementation) to create an extension module.
</p>
<H3><a name="Octave_nn4">32.2.1 Command-line options</a></H3>
<p>
The swig command line has a number of options you can use, like to redirect its output. Use <tt>swig -help</tt> to learn about these.
Options specific to the Octave module are:
</p>
<div class="shell">
<pre>$ swig -octave -help
...
Octave Options (available with -octave)
-globals <em>name</em> - Set <em>name</em> used to access C global variables [default: 'cvar']
Use '.' to load C global variables into module namespace
-opprefix <em>str</em> - Prefix <em>str</em> for global operator functions [default: 'op_']
</pre></div>
<p>
The <em>-globals</em> option sets the name of the variable which is the namespace for C global variables exported by the module.
The special name "." loads C global variables into the module namespace, i.e. alongside C functions and structs exported by the module.
The <em>-opprefix</em> options sets the prefix of the names of global/friend <a href="#Octave_nn18">operator</a> functions.
</p>
<H3><a name="Octave_nn5">32.2.2 Compiling a dynamic module</a></H3>
<p>
Octave modules are DLLs/shared objects having the ".oct" suffix.
Building an oct file is usually done with the mkoctfile command (either within Octave itself, or from the shell). For example,
</p>
<div class="shell"><pre>
$ swig -octave -c++ -o example_wrap.cpp example.i
$ mkoctfile example_wrap.cpp example.c
</pre></div>
<p>
where "example.c" is the file containing the gcd() implementation.
</p>
<p>
mkoctfile can also be used to extract the build parameters required to invoke the compiler and linker yourself. See the Octave manual and mkoctfile man page.
</p>
<p>
mkoctfile will produce "swigexample.oct", which contains the compiled extension module. Loading it into Octave is then a matter of invoking
</p>
<div class="targetlang"><pre>octave:1&gt; swigexample</pre></div>
<H3><a name="Octave_nn6">32.2.3 Using your module</a></H3>
<p>
Assuming all goes well, you will be able to do this:
<br>
</p>
<div class="targetlang"><pre>$ octave -q
octave:1&gt; swigexample
octave:2&gt; swigexample.gcd(4, 6)
ans = 2
octave:3&gt; swigexample.cvar.Foo
ans = 3
octave:4&gt; swigexample.cvar.Foo=4;
octave:5&gt; swigexample.cvar.Foo
ans = 4 </pre></div>
<H2><a name="Octave_nn7">32.3 A tour of basic C/C++ wrapping</a></H2>
<H3><a name="Octave_nn8">32.3.1 Modules</a></H3>
<p>
The SWIG module directive specifies the name of the Octave module. If you specify "module swigexample", then in Octave everything in the module will be accessible under "swigexample", as in the above example. When choosing a module name, make sure you don't use the same name as a built-in Octave command or standard module name.
</p>
<p>
When Octave is asked to invoke <tt>swigexample</tt>, it will try to find the ".m" or ".oct" file that defines the function "swigexample". You therefore need to make sure that "swigexample.oct" is in Octave's search path, which can be specified with the environment variable "OCTAVE_PATH".
</p>
<p>
To load an Octave module, simply type its name:
</p>
<div class="targetlang"><pre>
octave:1&gt; swigexample;
octave:2&gt; gcd(4, 6)
ans = 2
octave:3&gt; cvar.Foo
ans = 3
octave:4&gt; cvar.Foo=4;
octave:5&gt; cvar.Foo
ans = 4
</pre></div>
<p>
Modules can also be loaded from within functions, even before being loaded in the base context.
If the module is also used in the base context, however, it must first be loaded again:
</p>
<div class="targetlang"><pre>
octave:1&gt; function l = my_lcm(a, b)
&gt; swigexample
&gt; l = abs(a*b)/swigexample.gcd(a, b);
&gt; endfunction
octave:2&gt; my_lcm(4, 6)
ans = 12
octave:3&gt; swigexample.gcd(4, 6)
error: can't perform indexing operations for &lt;unknown type&gt; type
octave:3&gt; swigexample;
octave:4&gt; swigexample.gcd(4, 6)
ans = 2
</pre></div>
<H3><a name="Octave_nn9">32.3.2 Functions</a></H3>
<p>
Global functions are wrapped as new Octave built-in functions. For example,
</p>
<div class="code"><pre>&#037;module swigexample
int fact(int n); </pre></div>
<p>
creates a built-in function <tt>swigexample.fact(n)</tt> that works exactly like you think it does:
</p>
<div class="targetlang"><pre>octave:1&gt; swigexample.fact(4)
24 </pre></div>
<H3><a name="Octave_nn10">32.3.3 Global variables</a></H3>
<p>
Global variables are a little special in Octave. Given a global variable:
</p>
<div class="code"><pre>%module swigexample
extern double Foo;
</pre></div>
<p>
To expose variables, SWIG actually generates two functions, to get and set the value. In this case, Foo_set and Foo_set would be generated. SWIG then automatically calls these functions when you get and set the variable-- in the former case creating a local copy in the interpreter of the C variables, and in the latter case copying an interpreter variables onto the C variable.
</p>
<div class="targetlang"><pre>octave:1&gt; swigexample;
octave:2&gt; c=swigexample.cvar.Foo
c = 3
octave:3&gt; swigexample.cvar.Foo=4;
octave:4&gt; c
c = 3
octave:5&gt; swigexample.cvar.Foo
ans = 4</pre></div>
<p>
If a variable is marked with the %immutable directive then any attempts to set this variable will cause an Octave error. Given a global variable:
</p>
<div class="code"><pre>%module swigexample
%immutable;
extern double Foo;
%mutable;
</pre></div>
<p>
SWIG will allow the reading of <tt>Foo</tt> but when a set attempt is made, an error function will be called.
</p>
<div class="targetlang"><pre>octave:1&gt; swigexample
octave:2&gt; swigexample.Foo=4
error: attempt to set immutable member variable
error: assignment failed, or no method for `swig_type = scalar'
error: evaluating assignment expression near line 2, column 12 </pre></div>
<p>
It is possible to add new functions or variables to the module. This also allows the user to rename/remove existing functions and constants (but not linked variables, mutable or immutable). Therefore users are recommended to be careful when doing so.
</p>
<div class="targetlang"><pre>octave:1&gt; swigexample;
octave:2&gt; swigexample.PI=3.142;
octave:3&gt; swigexample.PI
ans = 3.1420 </pre></div>
<H3><a name="Octave_nn11">32.3.4 Constants and enums</a></H3>
<p>
Because Octave doesn't really have the concept of constants, C/C++ constants are not really constant in Octave. They are actually just a copy of the value into the Octave interpreter. Therefore they can be changed just as any other value. For example given some constants:
</p>
<div class="code"><pre>%module swigexample
%constant int ICONST=42;
#define SCONST "Hello World"
enum Days{SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY};
</pre></div>
<p>
This is 'effectively' converted into the following Octave code:
</p>
<div class="targetlang"><pre>swigexample.ICONST=42
swigexample.SCONST="Hello World"
swigexample.SUNDAY=0
.... </pre></div>
<H3><a name="Octave_nn12">32.3.5 Pointers</a></H3>
<p>
C/C++ pointers are fully supported by SWIG. Furthermore, SWIG has no problem working with incomplete type information. Given a wrapping of the &lt;file.h&gt; interface:
C/C++ pointers are fully supported by SWIG. Furthermore, SWIG has no problem working with incomplete type information. Given a wrapping of the &lt;file.h&gt; interface:
</p>
<div class="code"><pre>%module swigexample
FILE *fopen(const char *filename, const char *mode);
int fputs(const char *, FILE *);
int fclose(FILE *);
</pre></div>
<p>
When wrapped, you will be able to use the functions in a natural way from Octave. For example:
</p>
<div class="targetlang"><pre>
octave:1&gt; swigexample;
octave:2&gt; f=swigexample.fopen("w", "junk");
octave:3&gt; swigexample.fputs("Hello world", f);
octave:4&gt; swigexample.fclose(f);
</pre></div>
<p>
Simply printing the value of a wrapped C++ type will print its typename. E.g.,
</p>
<div class="targetlang"><pre>octave:1&gt; swigexample;
octave:2&gt; f=swigexample.fopen("junk", "w");
octave:3&gt; f
f =
{
_p_FILE, ptr = 0x9b0cd00
} </pre></div>
<p>
As the user of the pointer, you are responsible for freeing it, or closing any resources associated with it (just as you would in a C program). This does not apply so strictly to classes and structs (see below).
</p>
<div class="targetlang"><pre>octave:1&gt; swigexample;
octave:2&gt; f=swigexample.fopen("not there", "r");
error: value on right hand side of assignment is undefined
error: evaluating assignment expression near line 2, column 2 </pre></div>
<H3><a name="Octave_nn13">32.3.6 Structures and C++ classes</a></H3>
<p>
SWIG wraps C structures and C++ classes by using a special Octave type called a <tt>swig_ref</tt>. A <tt>swig_ref</tt> contains a reference to one or more instances of C/C++ objects, or just the type information for an object.
For each wrapped structure and class, a <tt>swig_ref</tt> will be exposed that has the name of the type. When invoked as a function, it creates a new object of its type and returns a <tt>swig_ref</tt> that points to that instance. This provides a very natural interface. For example,
</p>
<div class="code"><pre>struct Point{
int x, y;
};
</pre></div>
<p>
is used as follows:
</p>
<div class="targetlang">
<pre>octave:1&gt; swigexample;
octave:2&gt; p=swigexample.Point();
octave:3&gt; p.x=3;
octave:4&gt; p.y=5;
octave:5&gt; p.x, p.y
ans = 3
ans = 5
</pre></div>
<p>
In C++, invoking the type object in this way calls the object's constructor.
<tt>swig_ref</tt> objects can also be acquired by having a wrapped function return a pointer, reference, or value of a non-primitive type.
</p>
<p>
The swig_ref type handles indexing operations such that usage maps closely to what you would have in C/C++.
Structure members are accessed as in the above example, by calling set and get methods for C++ variables.
Methods also work as expected. For example, code wrapped in the following way
</p>
<div class="code"><pre>class Point{
public:
int x, y;
Point(int _x, int _y) : x(_x), y(_y) {}
double distance(const Point&amp; rhs) {
return sqrt(pow(x-rhs.x, 2)+pow(y-rhs.y, 2));
}
void set(int _x, int _y) {
x=_x; y=_y;
}
};
</pre></div>
<p>
can be used from Octave like this
</p>
<div class="targetlang">
<pre>octave:1&gt; swigexample;
octave:2&gt; p1=swigexample.Point(3, 5);
octave:3&gt; p2=swigexample.Point(1, 2);
octave:4&gt; p1.distance(p2)
ans = 3.6056
</pre></div>
<p>
By using the <tt>swig_this()</tt> and <tt>swig_type()</tt> functions, one can discover the pointers to and types of the underlying C/C++ object.
</p>
<div class="targetlang">
<pre>
octave:5> swig_this(p1)
ans = 162504808
octave:6> swig_type(p1)
ans = Point
</pre></div>
<p>
Note that <tt>swig_ref</tt> is a reference-counted pointer to a C/C++ object/type, and as such has pass-by-reference semantics. For example if one has a allocated a single object but has two <tt>swig_ref</tt>'s pointing to it, modifying the object through either of them will change the single allocated object.
This differs from the usual pass-by-value (copy-on-write) semantics that Octave maintains for built-in types. For example, in the following snippet, modifying <tt>b</tt> does not modify <tt>a</tt>,
</p>
<div class="targetlang">
<pre>
octave:7> a=struct('x', 4)
a =
{
x = 4
}
octave:8> b=a
b =
{
x = 4
}
octave:9> b.y=4
b =
{
x = 4
y = 4
}
octave:10> a
a =
{
x = 4
}
</pre></div>
<p>
However, when dealing with wrapped objects, one gets the behavior
</p>
<div class="targetlang">
<pre>
octave:2> a=Point(3, 5)
a =
{
Point, ptr = 0x9afbbb0
}
octave:3> b=a
b =
{
Point, ptr = 0x9afbbb0
}
octave:4> b.set(2, 1);
octave:5> b.x, b.y
ans = 2
ans = 1
octave:6> a.x, a.y
ans = 2
ans = 1
</pre></div>
<p>
Depending on the ownership setting of a <tt>swig_ref</tt>, it may call C++ destructors when its reference count goes to zero. See the section on memory management below for details.
</p>
<H3><a name="Octave_nn15">32.3.7 C++ inheritance</a></H3>
<p>
Single and multiple inheritance are fully supported. The <tt>swig_ref</tt> type carries type information along with any C++ object pointer it holds.
This information contains the full class hierarchy. When an indexing operation (such as a method invocation) occurs,
the tree is walked to find a match in the current class as well as any of its bases. The lookup is then cached in the <tt>swig_ref</tt>.
</p>
<H3><a name="Octave_nn17">32.3.8 C++ overloaded functions</a></H3>
<p>
Overloaded functions are supported, and handled as in other modules. That is,
each overload is wrapped separately (under internal names), and a dispatch function is also emitted under the external/visible name.
The dispatch function selects which overload to call (if any) based on the passed arguments.
<tt>typecheck</tt> typemaps are used to analyze each argument, as well as assign precedence. See the chapter on typemaps for details.
</p>
<H3><a name="Octave_nn18">32.3.9 C++ operators</a></H3>
<p>
C++ operator overloading is supported, in a way similar to other modules.
The <tt>swig_ref</tt> type supports all unary and binary operators between itself and all other types that exist in the system at module load time. When an operator is used (where one of the operands is a <tt>swig_ref</tt>), the runtime routes the call to either a member function of the given object, or to a global function whose named is derived from the types of the operands (either both or just the lhs or rhs).
</p>
<p>
For example, if <tt>a</tt> and <tt>b</tt> are SWIG variables in Octave, <tt>a+b</tt> becomes <tt>a.__add__(b)</tt>. The wrapper is then free to implement __add__ to do whatever it wants. A wrapper may define the <tt>__add__</tt> function manually, %rename some other function to it, or %rename a C++ operator to it.
</p>
<p>
By default the C++ operators are renamed to their corresponding Octave operators. So without doing any work, the following interface
</p>
<div class="code"><pre>
%inline {
struct A {
int value;
A(int _value) : value(_value) {}
A operator+ (const A&amp; x) {
return A(value+x.value);
}
};
}
</pre></div>
<p>
is usable from Octave like this:
</p>
<div class="targetlang"><pre>
a=A(2), b=A(3), c=a+b
assert(c.value==5);
</pre></div>
<p>
Octave operators are mapped in the following way:
</p>
<div class="code"><pre>
__brace__ a{args}
__brace_asgn__ a{args} = rhs
__paren__ a(args)
__paren_asgn__ a(args) = rhs
__str__ generates string rep
__not__ !a
__uplus__ +a
__uminus__ -a
__transpose__ a.'
__hermitian__ a'
__incr__ a++
__decr__ a--
__add__ a + b
__sub__ a - b
__mul__ a * b
__div__ a / b
__pow__ a ^ b
__ldiv__ a \ b
__lshift__ a << b
__rshift__ a >> b
__lt__ a < b
__le__ a <= b
__eq__ a == b
__ge__ a >= b
__gt__ a > b
__ne__ a != b
__el_mul__ a .* b
__el_div__ a ./ b
__el_pow__ a .^ b
__el_ldiv__ a .\ b
__el_and__ a &amp; b
__el_or__ a | b
</pre></div>
<p>
On the C++ side, the default mappings are as follows:
</p>
<div class="code"><pre>
%rename(__add__) *::operator+;
%rename(__add__) *::operator+();
%rename(__add__) *::operator+() const;
%rename(__sub__) *::operator-;
%rename(__uminus__) *::operator-();
%rename(__uminus__) *::operator-() const;
%rename(__mul__) *::operator*;
%rename(__div__) *::operator/;
%rename(__mod__) *::operator%;
%rename(__lshift__) *::operator<<;
%rename(__rshift__) *::operator>>;
%rename(__el_and__) *::operator&amp;&amp;;
%rename(__el_or__) *::operator||;
%rename(__xor__) *::operator^;
%rename(__invert__) *::operator~;
%rename(__lt__) *::operator<;
%rename(__le__) *::operator<=;
%rename(__gt__) *::operator>;
%rename(__ge__) *::operator>=;
%rename(__eq__) *::operator==;
%rename(__ne__) *::operator!=;
%rename(__not__) *::operator!;
%rename(__incr__) *::operator++;
%rename(__decr__) *::operator--;
%rename(__paren__) *::operator();
%rename(__brace__) *::operator[];
</pre></div>
<p>
Octave can also utilise friend (i.e. non-member) operators with a simple %rename: see the example in the Examples/octave/operator directory.
</p>
<H3><a name="Octave_nn19">32.3.10 Class extension with %extend</a></H3>
<p>
The %extend directive works the same as in other modules.
</p>
<p>
You can use it to define special behavior, like for example defining Octave operators not mapped to C++ operators, or defining certain Octave mechanisms such as how an object prints. For example, the <tt>octave_value::{is_string, string_value, print}</tt> functions are routed to a special method <tt>__str__</tt> that can be defined inside an %extend.
</p>
<div class="code"><pre>
%extend A {
string __str__() {
stringstream sout;
sout&lt;&lt;$self->value;
return sout.str();
}
}
</pre></div>
<p>
Then in Octave one gets,
</p>
<div class="targetlang"><pre>
octave:1&gt; a=A(4);
octave:2&gt; a
a = 4
octave:3&gt; printf("%s\n", a);
4
octave:4&gt; a.__str__()
4
</pre></div>
<p>
Similarly, Octave can use the <tt>__float__</tt> method to convert an object to a numeric value.
</p>
<p>
Octave 3.8.0 and later versions will also map unary functions X() to the corresponding <tt>__X__</tt> method, where X includes: abs(), acos(), acosh(), angle(), arg(), asin(), asinh(), atan(), atanh(), cbrt(), ceil(), conj(), cos(), cosh(), dawson(), erf(), erfc(), erfcinv(), erfcx(), erfi(), erfinv(), exp(), expm1(), finite(), fix(), floor(), gamma(), imag(), isalnum(), isalpha(), isascii(), iscntrl(), isdigit(), isgraph(), isinf(), islower(), isna(), isnan(), isprint(), ispunct(), isspace(), isupper(), isxdigit(), lgamma(), log(), log10(), log1p(), log2(), real(), round(), roundb(), signbit(), signum(), sin(), sinh(), sqrt(), tan(), tanh(), toascii(), tolower(), toupper()
</p>
<H3><a name="Octave_nn20">32.3.11 C++ templates</a></H3>
<p>
C++ class and function templates are fully supported as in other modules, in that the %template directive may used to create explicit instantiations of templated types.
For example, function templates can be instantiated as follows:
</p>
<div class="code"><pre>%module swigexample
%inline {
template&lt;class __scalar&gt;
__scalar mul(__scalar a, __scalar b) {
return a*b;
}
}
%include &lt;std_complex.i&gt;
%template(mul) mul&lt;std::complex&lt;double&gt; &gt;
%template(mul) mul&lt;double&gt;
</pre></div>
<p>
and then used from Octave
</p>
<div class="targetlang"><pre>
octave:1> mul(4, 3)
ans = 12
octave:2> mul(4.2, 3.6)
ans = 15.120
octave:3> mul(3+4i, 10+2i)
ans = 22 + 46i
</pre></div>
<p>
Similarly, class templates can be instantiated as in the following example,
</p>
<div class="code"><pre>%module swigexample
%include &lt;std_complex.i&gt;
%include &lt;std_string.i&gt;
%inline {
#include &lt;sstream&gt;
template&lt;class __scalar&gt; class sum {
__scalar s;
public:
sum(__scalar _s=0) : s(_s) {}
sum&amp; add(__scalar _s) {
s+=_s;
return *this;
}
std::string __str__() const {
std::stringstream sout;
sout&lt;&lt;s;
return sout.str();
}
};
}
%template(sum_complex) sum&lt;std::complex&lt;double&gt; &gt;;
%template(sum_double) sum&lt;double&gt;;
</pre></div>
<p>
and then used from Octave
</p>
<div class="targetlang"><pre>
octave:2> a=sum_complex(2+3i);
octave:3> a.add(2)
ans =
(4, 3)
octave:4> a.add(3+i)
ans =
(7, 4)
</pre></div>
<H3><a name="Octave_nn21">32.3.12 C++ Smart Pointers</a></H3>
<H4><a name="Octave_smart_pointers_shared_ptr">32.3.12.1 The shared_ptr Smart Pointer</a></H4>
<p>
The C++11 standard provides <tt>std::shared_ptr</tt> which was derived from the Boost
implementation, <tt>boost::shared_ptr</tt>.
Both of these are available for Octave in the SWIG library and usage is outlined
in the <a href="Library.html#Library_std_shared_ptr">shared_ptr smart pointer</a> library section.
</p>
<H4><a name="Octave_smart_pointers_generic">32.3.12.2 Generic Smart Pointers</a></H4>
<p>
C++ smart pointers are fully supported as in other modules.
</p>
<H3><a name="Octave_nn22">32.3.13 Directors (calling Octave from C++ code)</a></H3>
<p>
There is full support for SWIG Directors, which permits Octave code to subclass C++ classes, and implement their virtual methods.
</p>
<p>
Octave has no direct support for object oriented programming, however the <tt>swig_ref</tt> type provides some of this support. You can manufacture a <tt>swig_ref</tt> using the <tt>subclass</tt> function (provided by the SWIG/Octave runtime).
</p>
<p>
For example,
</p>
<div class="targetlang"><pre>
octave:1&gt; a=subclass();
octave:2&gt; a.my_var = 4;
octave:3&gt; a.my_method = @(self) printf("my_var = ", self.my_var);
octave:4&gt; a.my_method();
my_var = 4
</pre></div>
<p>
<tt>subclass()</tt> can also be used to subclass one or more C++ types. Suppose you have an interface defined by
</p>
<div class="code"><pre>
%inline {
class A {
public:
virtual my_method() {
printf("c-side routine called\n");
}
};
void call_your_method(A&amp; a) {
a.my_method();
}
}
</pre></div>
<p>
Then from Octave you can say:
</p>
<div class="targetlang"><pre>
octave:1&gt; B=@() subclass(A(), @my_method);
octave:2&gt; function my_method(self)
octave:3&gt; printf("octave-side routine called\n");
octave:4&gt; end
octave:5&gt; call_your_method(B());
octave-side routine called
</pre></div>
<p>
or more concisely,
</p>
<div class="targetlang"><pre>
octave:1&gt; B=@() subclass(A(), 'my_method', @(self) printf("octave-side routine called\n"));
octave:2&gt; call_your_method(B());
octave-side routine called
</pre></div>
<p>
Note that you have to enable directors via the %feature directive (see other modules for this).
</p>
<p>
<tt>subclass()</tt> will accept any number of C++ bases or other <tt>subclass()</tt>'ed objects, <tt>(string, octave_value)</tt> pairs, and <tt>function_handles</tt>. In the first case, these are taken as base classes; in the second case, as named members (either variables or functions, depending on whether the given value is a function handle); in the third case, as member functions whose name is taken from the given function handle. E.g.,
</p>
<div class="targetlang"><pre>
octave:1&gt; B=@(some_var=2) subclass(A(), 'some_var', some_var, @some_func, 'another_func',
@(self) do_stuff())
</pre></div>
<p>
You can also assign non-C++ member variables and functions after construct time. There is no support for non-C++ static members.
</p>
<p>
There is limited support for explicitly referencing C++ bases. So, in the example above, we could have
</p>
<div class="targetlang"><pre>
octave:1&gt; B=@() subclass(A(), @my_method);
octave:2&gt; function my_method(self)
octave:3&gt; self.A.my_method();
octave:4&gt; printf("octave-side routine called\n");
octave:5&gt; end
octave:6&gt; call_your_method(B());
c-side routine called
octave-side routine called
</pre></div>
<H3><a name="Octave_nn23">32.3.14 Threads</a></H3>
<p>
The use of threads in wrapped Director code is not supported; i.e., an Octave-side implementation of a C++ class must be called from the Octave interpreter's thread. Anything fancier (apartment/queue model, whatever) is left to the user. Without anything fancier, this amounts to the limitation that Octave must drive the module... like, for example, an optimization package that calls Octave to evaluate an objective function.
</p>
<H3><a name="Octave_nn24">32.3.15 Memory management</a></H3>
<p>
As noted above, <tt>swig_ref</tt> represents a reference counted pointer to a C/C++-side object. It also contains a flag indicating whether Octave or the C/C++ code owns the object. If Octave owns it, any destructors will be called when the reference count reaches zero. If the C/C++ side owns the object, then destructors will not be called when the reference count goes to zero.
</p>
<p>
For example,
<div class="code"><pre>
%inline {
class A {
public:
A() { printf("A constructing\n"); }
~A() { printf("A destructing\n"); }
};
}
</pre></div>
<p>
Would produce this behavior in Octave:
</p>
<div class="targetlang"><pre>
octave:1&gt; a=A();
A constructing
octave:2&gt; b=a;
octave:3&gt; clear a;
octave:4&gt; b=4;
A destructing
</pre></div>
<p>
The %newobject directive may be used to control this behavior for pointers returned from functions.
<p>
In the case where one wishes for the C++ side to own an object that was created in Octave (especially a Director object), one can use the __disown() method to invert this logic. Then letting the Octave reference count go to zero will not destroy the object, but destroying the object will invalidate the Octave-side object if it still exists (and call destructors of other C++ bases in the case of multiple inheritance/<tt>subclass()</tt>'ing).
</p>
<H3><a name="Octave_nn25">32.3.16 STL support</a></H3>
<p>
Various STL library files are provided for wrapping STL containers.
</p>
<H3><a name="Octave_nn26">32.3.17 Matrix typemaps</a></H3>
<p>
Octave provides a rich set of classes for dealing with matrices. Currently there are no built-in typemaps to deal with those. However, these are relatively straight forward for users to add themselves (see the docs on typemaps). Without much work (a single typemap decl-- say, 5 lines of code in the interface file), it would be possible to have a function
</p>
<div class="code"><pre>
double my_det(const double* mat, int m, int n);
</pre></div>
<p>
that is accessed from Octave as,
</p>
<div class="targetlang"><pre>
octave:1&gt; my_det(rand(4));
ans = -0.18388
</pre></div>
<tt><br></tt>
</body>
</html>

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,246 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>SWIG and Pike</title>
<link rel="stylesheet" type="text/css" href="style.css">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body bgcolor="#ffffff">
<H1><a name="Pike">35 SWIG and Pike</a></H1>
<!-- INDEX -->
<div class="sectiontoc">
<ul>
<li><a href="#Pike_nn2">Preliminaries</a>
<ul>
<li><a href="#Pike_nn3">Running SWIG</a>
<li><a href="#Pike_nn4">Getting the right header files</a>
<li><a href="#Pike_nn5">Using your module</a>
</ul>
<li><a href="#Pike_nn6">Basic C/C++ Mapping</a>
<ul>
<li><a href="#Pike_nn7">Modules</a>
<li><a href="#Pike_nn8">Functions</a>
<li><a href="#Pike_nn9">Global variables</a>
<li><a href="#Pike_nn10">Constants and enumerated types</a>
<li><a href="#Pike_nn11">Constructors and Destructors</a>
<li><a href="#Pike_nn12">Static Members</a>
</ul>
</ul>
</div>
<!-- INDEX -->
<p>
This chapter describes SWIG support for Pike. As of this writing, the
SWIG Pike module is still under development and is not considered
ready for prime time. The Pike module is being developed against the
Pike 7.4.10 release and may not be compatible with previous versions
of Pike.
</p>
<p>
This chapter covers most SWIG features, but certain low-level details
are covered in less depth than in earlier chapters. At the very
least, make sure you read the "<a href="SWIG.html#SWIG">SWIG Basics</a>"
chapter.<br>
</p>
<H2><a name="Pike_nn2">35.1 Preliminaries</a></H2>
<H3><a name="Pike_nn3">35.1.1 Running SWIG</a></H3>
<p>
Suppose that you defined a SWIG module such as the following:
</p>
<div class="code">
<pre>%module example<br><br>%{<br>#include "example.h"<br>%}<br><br>int fact(int n);<br></pre>
</div>
<p>
To build a C extension module for Pike, run SWIG using the <tt>-pike</tt> option :
</p>
<div class="code">
<pre>$ <b>swig -pike example.i</b><br></pre>
</div>
<p>
If you're building a C++ extension, be sure to add the <tt>-c++</tt> option:
</p>
<div class="code">
<pre>$ <b>swig -c++ -pike example.i</b><br></pre>
</div>
<p>
This creates a single source file named <tt>example_wrap.c</tt> (or <tt>example_wrap.cxx</tt>, if you
ran SWIG with the <tt>-c++</tt> option).
The SWIG-generated 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.
</p>
<p>
The name of the wrapper file is derived from the name of the input
file. For example, if the input file is <tt>example.i</tt>, the name
of the wrapper file is <tt>example_wrap.c</tt>. To change this, you
can use the <tt>-o</tt> option:
</p>
<div class="code">
<pre>$ <b>swig -pike -o pseudonym.c example.i</b><br></pre>
</div>
<H3><a name="Pike_nn4">35.1.2 Getting the right header files</a></H3>
<p>
In order to compile the C/C++ wrappers, the compiler needs to know the
path to the Pike header files. These files are usually contained in a
directory such as
</p>
<div class="code">
<pre>/usr/local/pike/7.4.10/include/pike<br></pre>
</div>
<p>
There doesn't seem to be any way to get Pike itself to reveal the
location of these files, so you may need to hunt around for them.
You're looking for files with the names <tt>global.h</tt>, <tt>program.h</tt>
and so on.
</p>
<H3><a name="Pike_nn5">35.1.3 Using your module</a></H3>
<p>
To use your module, simply use Pike's <tt>import</tt> statement:
</p>
<div class="code"><pre>
$ <b>pike</b>
Pike v7.4 release 10 running Hilfe v3.5 (Incremental Pike Frontend)
&gt; <b>import example;</b>
&gt; <b>fact(4);</b>
(1) Result: 24
</pre></div>
<H2><a name="Pike_nn6">35.2 Basic C/C++ Mapping</a></H2>
<H3><a name="Pike_nn7">35.2.1 Modules</a></H3>
<p>
All of the code for a given SWIG module is wrapped into a single Pike
module. Since the name of the shared library that implements your
module ultimately determines the module's name (as far as Pike is
concerned), SWIG's <tt>%module</tt> directive doesn't really have any
significance.
</p>
<H3><a name="Pike_nn8">35.2.2 Functions</a></H3>
<p>
Global functions are wrapped as new Pike built-in functions. For
example,
</p>
<div class="code"><pre>
%module example
int fact(int n);
</pre></div>
<p>
creates a new built-in function <tt>example.fact(n)</tt> that works
exactly as you'd expect it to:
</p>
<div class="code"><pre>
&gt; <b>import example;</b>
&gt; <b>fact(4);</b>
(1) Result: 24
</pre></div>
<H3><a name="Pike_nn9">35.2.3 Global variables</a></H3>
<p>
Global variables are currently wrapped as a pair of functions, one to get
the current value of the variable and another to set it. For example, the
declaration
</p>
<div class="code"><pre>
%module example
double Foo;
</pre></div>
<p>
will result in two functions, <tt>Foo_get()</tt> and <tt>Foo_set()</tt>:
</p>
<div class="code"><pre>
&gt; <b>import example;</b>
&gt; <b>Foo_get();</b>
(1) Result: 3.000000
&gt; <b>Foo_set(3.14159);</b>
(2) Result: 0
&gt; <b>Foo_get();</b>
(3) Result: 3.141590
</pre></div>
<H3><a name="Pike_nn10">35.2.4 Constants and enumerated types</a></H3>
<p>
Enumerated types in C/C++ declarations are wrapped as Pike constants,
not as Pike enums.
</p>
<H3><a name="Pike_nn11">35.2.5 Constructors and Destructors</a></H3>
<p>
Constructors are wrapped as <tt>create()</tt> methods, and destructors are
wrapped as <tt>destroy()</tt> methods, for Pike classes.
</p>
<H3><a name="Pike_nn12">35.2.6 Static Members</a></H3>
<p>
Since Pike doesn't support static methods or data for Pike classes, static
member functions in your C++ classes are wrapped as regular functions and
static member variables are wrapped as pairs of functions (one to get the
value of the static member variable, and another to set it). The names of
these functions are prepended with the name of the class.
For example, given this C++ class declaration:
</p>
<div class="code"><pre>
class Shape
{
public:
static void print();
static int nshapes;
};
</pre></div>
<p>
SWIG will generate a <tt>Shape_print()</tt> method that invokes the static
<tt>Shape::print()</tt> member function, as well as a pair of methods,
<tt>Shape_nshapes_get()</tt> and <tt>Shape_nshapes_set()</tt>, to get and set
the value of <tt>Shape::nshapes</tt>.
</p>
</body>
</html>

View File

@@ -0,0 +1,459 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Preface</title>
<link rel="stylesheet" type="text/css" href="style.css">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body bgcolor="#ffffff">
<H1><a name="Preface">1 Preface</a></H1>
<!-- INDEX -->
<div class="sectiontoc">
<ul>
<li><a href="#Preface_nn2">Introduction</a>
<li><a href="#Preface_nn4">SWIG Versions</a>
<li><a href="#Preface_license">SWIG License</a>
<li><a href="#Preface_nn5">SWIG resources</a>
<li><a href="#Preface_nn6">Prerequisites</a>
<li><a href="#Preface_nn7">Organization of this manual</a>
<li><a href="#Preface_nn8">How to avoid reading the manual</a>
<li><a href="#Preface_nn9">Backwards compatibility</a>
<li><a href="#Preface_release_notes">Release notes</a>
<li><a href="#Preface_nn10">Credits</a>
<li><a href="#Preface_nn11">Bug reports</a>
<li><a href="#Preface_installation">Installation</a>
<ul>
<li><a href="#Preface_windows_installation">Windows installation</a>
<li><a href="#Preface_unix_installation">Unix installation</a>
<li><a href="#Preface_osx_installation">Macintosh OS X installation</a>
<li><a href="#Preface_testing">Testing</a>
<li><a href="#Preface_examples">Examples</a>
</ul>
</ul>
</div>
<!-- INDEX -->
<H2><a name="Preface_nn2">1.1 Introduction</a></H2>
<p>
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.
</p>
<p>
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.
<H2><a name="Preface_nn4">1.2 SWIG Versions</a></H2>
<p>
In the late 1990's, the most stable version of SWIG was release
1.1p5. Versions 1.3.x were officially development versions and these were released
over a period of 10 years starting from the year 2000. The final version in the 1.3.x
series was 1.3.40, but in truth the 1.3.x series had been stable for many years.
An official stable version was released along with the decision to make SWIG
license changes and this gave rise to version 2.0.0 in 2010.
</p>
<H2><a name="Preface_license">1.3 SWIG License</a></H2>
<p>
The LICENSE file shipped with SWIG in the top level directory contains the SWIG license.
For further insight into the license including the license of SWIG's output code, please visit
the SWIG legal page - <a href="http://www.swig.org/legal.html">http://www.swig.org/legal.html</a>.
</p>
<p>
The license was clarified in version 2.0.0
so that the code that SWIG generated could be distributed
under license terms of the user's choice/requirements and at the same time the SWIG
source was placed under the GNU General Public License version 3.
</p>
<H2><a name="Preface_nn5">1.4 SWIG resources</a></H2>
<p>
The official location of SWIG related material is
</p>
<div class="shell"><pre>
<a href="http://www.swig.org">http://www.swig.org</a>
</pre></div>
<p>
This site contains the latest version of the software, users guide,
and information regarding bugs, installation problems, and
implementation tricks.
<p>
You can also subscribe to the swig-user mailing list by visiting the page
</p>
<div class="shell"><pre>
<a href="http://www.swig.org/mail.html">http://www.swig.org/mail.html</a>
</pre></div>
<p>
The mailing list often discusses some of the more technical aspects of
SWIG along with information about beta releases and future work.
</p>
<p>
Git and Subversion access to the latest version of SWIG is also available. More information
about this can be obtained at:
</p>
<div class="shell"><pre>
<a href="http://www.swig.org/svn.html">SWIG Bleeding Edge</a>
</pre></div>
<H2><a name="Preface_nn6">1.5 Prerequisites</a></H2>
<p>
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.
</p>
<p>
Over time 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.
<H2><a name="Preface_nn7">1.6 Organization of this manual</a></H2>
<p>
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.
</p>
<H2><a name="Preface_nn8">1.7 How to avoid reading the manual</a></H2>
<p>
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.
</p>
<H2><a name="Preface_nn9">1.8 Backwards compatibility</a></H2>
<p>
If you are a previous user of SWIG, don't expect
SWIG to provide complete backwards compatibility.
Although the developers strive to the utmost to keep backwards compatibility,
this isn't always possible as the
primary goal over time is to make SWIG
better---a process that would simply be impossible if the developers
are constantly bogged down with backwards compatibility issues.
Potential incompatibilities are clearly marked in the detailed
<a href="#Preface_release_notes">release notes</a>.
</p>
<p>
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:
</p>
<div class="code"><pre>
#if SWIG_VERSION &gt;= 0x010311
/* Use some fancy new feature */
#endif
</pre></div>
<p>
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.
</p>
<H2><a name="Preface_release_notes">1.9 Release notes</a></H2>
<p>
The CHANGES.current, CHANGES and RELEASENOTES files shipped with SWIG in the top level directory
contain, respectively, detailed release notes for the current version,
detailed release notes for previous releases and summary release notes from SWIG-1.3.22 onwards.
</p>
<H2><a name="Preface_nn10">1.10 Credits</a></H2>
<p>
SWIG is an unfunded project that would not be possible without the
contributions of many people working in their spare time.
If you have benefitted from using SWIG, please consider
<a href="http://www.swig.org/donate.html">Donating to SWIG</a> to keep development going.
There have been a large varied number of people
who have made contributions at all levels over time. Contributors
are mentioned either in the COPYRIGHT file or CHANGES files shipped with SWIG or in submitted bugs.
</p>
<H2><a name="Preface_nn11">1.11 Bug reports</a></H2>
<p>
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 <a href="http://www.swig.org/mail.html">swig-devel mailing list</a> or report a bug
at the <a href="http://www.swig.org/bugs.html">SWIG bug tracker</a>. 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.
</p>
<H2><a name="Preface_installation">1.12 Installation</a></H2>
<H3><a name="Preface_windows_installation">1.12.1 Windows installation</a></H3>
<p>
Please see the dedicated <a href="Windows.html#Windows">Windows chapter</a> for instructions on installing
SWIG on Windows and running the examples. The Windows distribution is
called swigwin and includes a prebuilt SWIG executable, swig.exe, included in
the top level directory. Otherwise it is exactly the same as
the main SWIG distribution. There is no need to download anything else.
</p>
<H3><a name="Preface_unix_installation">1.12.2 Unix installation</a></H3>
<p>
These installation instructions are for using the distributed tarball,
for example, <tt>swig-3.0.8.tar.gz</tt>.
If you wish to build and install from source on Github, extra steps are required.
Please see the <a href="http://swig.org/svn.html">Bleeding Edge</a> page on the SWIG website.
</p>
<p>
You must use <a href="http://www.gnu.org/software/make/">GNU make</a> to build and install SWIG.
</p>
<p>
<a href="http://www.pcre.org/">PCRE</a>
needs to be installed on your system to build SWIG, in particular
pcre-config must be available. If you have PCRE headers and libraries but not
pcre-config itself or, alternatively, wish to override the compiler or linker
flags returned by pcre-config, you may set PCRE_LIBS and PCRE_CFLAGS variables
to be used instead. And if you don't have PCRE at all, the configure script
will provide instructions for obtaining it.
</p>
<p>
To build and install SWIG, simply type the following:
</p>
<div class="shell"><pre>
$ ./configure
$ make
$ make install
</pre></div>
<p>
By default SWIG installs itself in /usr/local. If you need to install SWIG in
a different location or in your home directory, use the <tt>--prefix</tt> option
to <tt>./configure</tt>. For example:
</p>
<div class="shell"><pre>
$ ./configure --prefix=/home/yourname/projects
$ make
$ make install
</pre></div>
<p>
Note: the directory given to <tt>--prefix</tt> must be an absolute pathname. Do <b>not</b> use
the ~ shell-escape to refer to your home directory. SWIG won't work properly
if you do this.
</p>
<p>
The INSTALL file shipped in the top level directory details more about using configure. Also try
</p>
<div class="shell"><pre>
$ ./configure --help.
</pre></div>
<p>
The configure script will attempt to locate various packages on your machine
including Tcl, Perl5, Python and all the other target languages that SWIG
supports. Don't panic if you get 'not found' messages -- SWIG does not need these
packages to compile or run. The configure script is actually looking for
these packages so that you can try out the SWIG examples contained
in the 'Examples' directory without having to hack Makefiles.
Note that the <tt>--without-xxx</tt> options, where xxx is a target language, have
minimal effect. All they do is reduce the amount of testing done with
'make check'. The SWIG executable and library files installed cannot currently
be configured with a subset of target languages.
</p>
<p>
SWIG used to include a set of runtime libraries for some languages for working
with multiple modules. These are no longer built during the installation stage.
However, users can build them just like any wrapper module as described in
the <a href="Modules.html#Modules">Modules chapter</a>.
The CHANGES file shipped with SWIG in the top level directory
also lists some examples which build the runtime library.
</p>
<p>
Note:
</p>
<ul>
<li>
If you checked the code out via Git, you will have to run <tt>./autogen.sh</tt>
before <tt>./configure</tt>. In addition, a full build of SWIG requires
a number of packages to be installed. Full instructions at
<a href="http://www.swig.org/svn.html">SWIG bleeding edge</a>.
</li>
</ul>
<H3><a name="Preface_osx_installation">1.12.3 Macintosh OS X installation</a></H3>
<p>
SWIG is known to work on various flavors of OS X. Follow the Unix installation
instructions above. However, as of this writing, there is still great deal of
inconsistency with how shared libaries are handled by various scripting languages
on OS X.
</p>
<p>
Users of OS X should be aware that Darwin handles shared libraries and linking in
a radically different way than most Unix systems. In order to test SWIG and run
the examples, SWIG configures itself to use flat namespaces and to allow undefined
symbols (<tt>-flat_namespace -undefined suppress</tt>). This mostly closely follows the Unix
model and makes it more likely that the SWIG examples will work with whatever
installation of software you might have. However, this is generally not the recommended
technique for building larger extension modules. Instead, you should utilize
Darwin's two-level namespaces. Some details about this can be found here
<a href="https://developer.apple.com/library/mac/documentation/Porting/Conceptual/PortingUnix/compiling/compiling.html#//apple_ref/doc/uid/TP40002850-BCIHJBBF">Understanding Two-Level Namespaces</a>.
</p>
<p>
Needless to say, you might have to experiment a bit to get things working at first.
</p>
<H3><a name="Preface_testing">1.12.4 Testing</a></H3>
<p>
If you want to test SWIG after building it, a check can be performed on Unix operating systems.
Type the following:
</p>
<div class="shell"><pre>
$ make -k check
</pre></div>
<p>
This step can be performed either before or after installation.
The check requires at least one of the target languages to be
installed. If it fails, it may mean that you have an uninstalled
language module or that the file 'Examples/Makefile' has been
incorrectly configured. It may also fail due to compiler issues such
as a broken C++ compiler. Even if the check fails, there is a
pretty good chance SWIG still works correctly --- you will just have to
mess around with one of the examples and some makefiles to get it to work.
Some tests may also fail due to missing dependency packages, eg PCRE
or Boost, but this will require careful analysis of the configure output
done during configuration.
</p>
<p>
The test suite executed by the check is designed to stress-test
many parts of the implementation including obscure corner cases. If some
of these tests fail or generate warning messages, there is no reason for
alarm --- the test may be related to some new SWIG feature or a difficult bug
that we're trying to resolve. Chances are that SWIG will work just fine
for you. Note that if you have more than one CPU/core, then you can use
parallel make to speed up the check as it does take quite some time to run,
for example:
</p>
<div class="shell"><pre>
$ make -j2 -k check
</pre></div>
<p>
Also, SWIG's support for C++ is sufficiently advanced that certain
tests may fail on older C++ compilers (for instance if your compiler
does not support member templates). These errors are harmless if you
don't intend to use these features in your own programs.
</p>
<p>
Note: The test-suite currently contains over 500 tests. If you
have many different target languages installed and a slow machine, it
might take more than an hour to run the test-suite.
</p>
<H3><a name="Preface_examples">1.12.5 Examples</a></H3>
<p>
The Examples directory contains a variety of examples of using SWIG
and it has some browsable documentation. Simply point your browser to
the file "Example/index.html".
</p>
<p>
The Examples directory also includes Visual C++ project 6 (.dsp) files for
building some of the examples on Windows. Later versions of Visual Studio
will convert these old style project files into a current solution file.
</p>
</body>
</html>

View File

@@ -0,0 +1,506 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>SWIG Preprocessor</title>
<link rel="stylesheet" type="text/css" href="style.css">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body bgcolor="#ffffff">
<H1><a name="Preprocessor">8 Preprocessing</a></H1>
<!-- INDEX -->
<div class="sectiontoc">
<ul>
<li><a href="#Preprocessor_nn2">File inclusion</a>
<li><a href="#Preprocessor_nn3">File imports</a>
<li><a href="#Preprocessor_condition_compilation">Conditional Compilation</a>
<li><a href="#Preprocessor_nn5">Macro Expansion</a>
<li><a href="#Preprocessor_nn6">SWIG Macros</a>
<li><a href="#Preprocessor_nn7">C99 and GNU Extensions</a>
<li><a href="#Preprocessor_delimiters">Preprocessing and delimiters</a>
<ul>
<li><a href="#Preprocessor_nn8">Preprocessing and %{ ... %} &amp; " ... " delimiters</a>
<li><a href="#Preprocessor_nn9">Preprocessing and { ... } delimiters</a>
</ul>
<li><a href="#Preprocessor_typemap_delimiters">Preprocessor and Typemaps</a>
<li><a href="#Preprocessor_nn10">Viewing preprocessor output</a>
<li><a href="#Preprocessor_warning_error">The #error and #warning directives</a>
</ul>
</div>
<!-- INDEX -->
<p>
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.
</p>
<H2><a name="Preprocessor_nn2">8.1 File inclusion</a></H2>
<p>
To include another file into a SWIG interface, use the <tt>%include</tt> directive
like this:
</p>
<div class="code">
<pre>
%include "pointer.i"
</pre>
</div>
<p>
Unlike, <tt>#include</tt>, <tt>%include</tt> includes each file once (and will not
reload the file on subsequent <tt>%include</tt> declarations). Therefore, it
is not necessary to use include-guards in SWIG interfaces.
</p>
<p>
By default, the <tt>#include</tt> is ignored unless you run SWIG with the
<tt>-includeall</tt> 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.
<H2><a name="Preprocessor_nn3">8.2 File imports</a></H2>
<p>
SWIG provides another file inclusion directive with the <tt>%import</tt> directive.
For example:
</p>
<div class="code">
<pre>
%import "foo.i"
</pre>
</div>
<p>
The purpose of <tt>%import</tt> 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., <tt>typedef</tt>) as well as
C++ classes that might be used as base-classes for class declarations in the interface.
The use of <tt>%import</tt> 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 later in the <a href="Modules.html#Modules">Working with Modules</a> chapter.
</p>
<P>
The <tt>-importall</tt> directive tells SWIG to follow all <tt>#include</tt> statements
as imports. This might be useful if you want to extract type definitions from system
header files without generating any wrappers.
<H2><a name="Preprocessor_condition_compilation">8.3 Conditional Compilation</a></H2>
<p>
SWIG fully supports the use of <tt>#if</tt>, <tt>#ifdef</tt>,
<tt>#ifndef</tt>, <tt>#else</tt>, <tt>#endif</tt> to conditionally
include parts of an interface. The following symbols are predefined
by SWIG when it is parsing the interface:
</p>
<div class="code"><pre>
SWIG Always defined when SWIG is processing a file
SWIGIMPORTED Defined when SWIG is importing a file with <tt>%import</tt>
SWIG_VERSION Hexadecimal (binary-coded decimal) number containing SWIG version,
such as 0x010311 (corresponding to SWIG-1.3.11).
SWIGALLEGROCL Defined when using Allegro CL
SWIGCFFI Defined when using CFFI
SWIGCHICKEN Defined when using CHICKEN
SWIGCLISP Defined when using CLISP
SWIGCSHARP Defined when using C#
SWIGGUILE Defined when using Guile
SWIGJAVA Defined when using Java
SWIGJAVASCRIPT Defined when using Javascript
SWIG_JAVASCRIPT_JSC Defined when using Javascript for JavascriptCore
SWIG_JAVASCRIPT_V8 Defined when using Javascript for v8 or node.js
SWIGLUA Defined when using Lua
SWIGMODULA3 Defined when using Modula-3
SWIGMZSCHEME Defined when using Mzscheme
SWIGOCAML Defined when using Ocaml
SWIGOCTAVE Defined when using Octave
SWIGPERL Defined when using Perl
SWIGPHP Defined when using PHP5 or PHP7
SWIGPHP5 Defined when using PHP5
SWIGPHP7 Defined when using PHP7
SWIGPIKE Defined when using Pike
SWIGPYTHON Defined when using Python
SWIGR Defined when using R
SWIGRUBY Defined when using Ruby
SWIGSCILAB Defined when using Scilab
SWIGSEXP Defined when using S-expressions
SWIGTCL Defined when using Tcl
SWIGXML Defined when using XML
</pre></div>
<p>
In addition, SWIG defines the following set of standard C/C++ macros:
</p>
<div class="code">
<pre>
__LINE__ Current line number
__FILE__ Current file name
__STDC__ Defined to indicate ANSI C
__cplusplus Defined when -c++ option used
</pre>
</div>
<p>
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 `<tt>SWIG</tt>' which is only defined
within the SWIG compiler).
</p>
<H2><a name="Preprocessor_nn5">8.4 Macro Expansion</a></H2>
<p>
Traditional preprocessor macros can be used in SWIG interfaces. Be aware that the <tt>#define</tt> statement
is also used to try and detect constants. Therefore, if you have something like this in your file,
</p>
<div class="code">
<pre>
#ifndef _FOO_H 1
#define _FOO_H 1
...
#endif
</pre>
</div>
<p>
you may get some extra constants such as <tt>_FOO_H</tt> showing up in the scripting interface.
</p>
<p>
More complex macros can be defined in the standard way. For example:
</p>
<div class="code">
<pre>
#define EXTERN extern
#ifdef __STDC__
#define _ANSI(args) (args)
#else
#define _ANSI(args) ()
#endif
</pre>
</div>
<p>
The following operators can appear in macro definitions:
</p>
<ul>
<li><tt>#x</tt><br>
Converts macro argument <tt>x</tt> to a string surrounded by double quotes ("x").
</li>
<li><tt>x ## y</tt><br>
Concatenates x and y together to form <tt>xy</tt>.
</li>
<li><tt>`x`</tt><br>
If <tt>x</tt> is a string surrounded by double quotes, do nothing. Otherwise, turn into a string
like <tt>#x</tt>. This is a non-standard SWIG extension.
</li>
</ul>
<H2><a name="Preprocessor_nn6">8.5 SWIG Macros</a></H2>
<p>
SWIG provides an enhanced macro capability with the <tt>%define</tt> and <tt>%enddef</tt> directives.
For example:
</p>
<div class="code">
<pre>
%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)
</pre>
</div>
<p>
The primary purpose of <tt>%define</tt> 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 <tt>%enddef</tt>. 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 <tt>%define</tt> statements.
</p>
<p>
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).
</p>
<H2><a name="Preprocessor_nn7">8.6 C99 and GNU Extensions</a></H2>
<p>
SWIG-1.3.12 and newer releases support variadic preprocessor macros. For example:
</p>
<div class="code">
<pre>
#define DEBUGF(fmt, ...) fprintf(stderr, fmt, __VA_ARGS__)
</pre>
</div>
<p>
When used, any extra arguments to <tt>...</tt> are placed into the
special variable <tt>__VA_ARGS__</tt>. This also works with special SWIG
macros defined using <tt>%define</tt>.
</p>
<p>
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:
</p>
<div class="code">
<pre>
DEBUGF("hello"); --&gt; fprintf(stderr, "hello", );
</pre>
</div>
<p>
To get rid of the extra comma, use <tt>##</tt> like this:
</p>
<div class="code">
<pre>
#define DEBUGF(fmt, ...) fprintf(stderr, fmt, ##__VA_ARGS__)
</pre>
</div>
<p>
SWIG also supports GNU-style variadic macros. For example:
</p>
<div class="code">
<pre>
#define DEBUGF(fmt, args...) fprintf(stdout, fmt, args)
</pre>
</div>
<p>
<b>Comment:</b> 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.
</p>
<H2><a name="Preprocessor_delimiters">8.7 Preprocessing and delimiters</a></H2>
<p>
The preprocessor handles { }, " " and %{ %} delimiters differently.
</p>
<H3><a name="Preprocessor_nn8">8.7.1 Preprocessing and %{ ... %} &amp; " ... " delimiters</a></H3>
<p>
The SWIG preprocessor does not process any text enclosed in a code block %{ ... %}. Therefore,
if you write code like this,
</p>
<div class="code">
<pre>
%{
#ifdef NEED_BLAH
int blah() {
...
}
#endif
%}
</pre>
</div>
<p>
the contents of the <tt>%{ ... %}</tt> block are copied without
modification to the output (including all preprocessor directives).
</p>
<H3><a name="Preprocessor_nn9">8.7.2 Preprocessing and { ... } delimiters</a></H3>
<p>
SWIG always runs the preprocessor on text appearing inside <tt>{ ... }</tt>. However,
sometimes it is desirable to make a preprocessor directive pass through to the output
file. For example:
</p>
<div class="code">
<pre>
%extend Foo {
void bar() {
#ifdef DEBUG
printf("I'm in bar\n");
#endif
}
}
</pre>
</div>
<p>
By default, SWIG will interpret the <tt>#ifdef DEBUG</tt> statement. However, if you really wanted that code
to actually go into the wrapper file, prefix the preprocessor directives with <tt>%</tt> like this:
</p>
<div class="code">
<pre>
%extend Foo {
void bar() {
%#ifdef DEBUG
printf("I'm in bar\n");
%#endif
}
}
</pre>
</div>
<p>
SWIG will strip the extra <tt>%</tt> and leave the preprocessor directive in the code.
</p>
<H2><a name="Preprocessor_typemap_delimiters">8.8 Preprocessor and Typemaps</a></H2>
<p>
<a href="Typemaps.html#Typemaps">Typemaps</a> support a special attribute called <tt>noblock</tt> where the { ... } delimiters can be used,
but the delimiters are not actually generated into the code.
The effect is then similar to using "" or %{ %} delimiters but the code <b>is</b> run through the preprocessor. For example:
</p>
<div class="code">
<pre>
#define SWIG_macro(CAST) (CAST)$input
%typemap(in) Int {$1= SWIG_macro(int);}
</pre>
</div>
<p>
might generate
</p>
<div class="code">
<pre>
{
arg1=(int)jarg1;
}
</pre>
</div>
<p>
whereas
</p>
<div class="code">
<pre>
#define SWIG_macro(CAST) (CAST)$input
%typemap(in, noblock=1) Int {$1= SWIG_macro(int);}
</pre>
</div>
<p>
might generate
</p>
<div class="code">
<pre>
arg1=(int)jarg1;
</pre>
</div>
<p>
and
</p>
<div class="code">
<pre>
#define SWIG_macro(CAST) (CAST)$input
%typemap(in) Int %{$1=SWIG_macro(int);%}
</pre>
</div>
<p>
would generate
</p>
<div class="code">
<pre>
arg1=SWIG_macro(int);
</pre>
</div>
<H2><a name="Preprocessor_nn10">8.9 Viewing preprocessor output</a></H2>
<p>
Like many compilers, SWIG supports a <tt>-E</tt> command line option to display the output from the preprocessor.
When the <tt>-E</tt> 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.
</p>
<H2><a name="Preprocessor_warning_error">8.10 The #error and #warning directives</a></H2>
<p>
SWIG supports the commonly used <tt>#warning</tt> and <tt>#error</tt> preprocessor directives.
The <tt>#warning</tt> directive will cause SWIG to issue a warning then continue processing.
The <tt>#error</tt> directive will cause SWIG to exit with a fatal error.
Example usage:
</p>
<div class="code">
<pre>
#error "This is a fatal error message"
#warning "This is a warning message"
</pre>
</div>
<p>
The <tt>#error</tt> behaviour can be made to work like <tt>#warning</tt> if the <tt>-cpperraswarn</tt>
commandline option is used. Alternatively, the <tt>#pragma</tt> directive can be used to the same effect, for example:
</p>
<div class="code">
<pre>
/* 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
</pre>
</div>
</body>
</html>

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,198 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>SWIG and R</title>
<link rel="stylesheet" type="text/css" href="style.css">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body bgcolor="#ffffff">
<H1><a name="R">37 SWIG and R</a></H1>
<!-- INDEX -->
<div class="sectiontoc">
<ul>
<li><a href="#R_nn2">Bugs</a>
<li><a href="#R_nn3">Using R and SWIG</a>
<li><a href="#R_nn4">Precompiling large R files</a>
<li><a href="#R_nn5">General policy</a>
<li><a href="#R_language_conventions">Language conventions</a>
<li><a href="#R_nn6">C++ classes</a>
<li><a href="#R_nn7">Enumerations</a>
</ul>
</div>
<!-- INDEX -->
<p>
R is a GPL'ed open source statistical and plotting environment.
Information about R can be found at <a
href="http://www.r-project.org/">www.r-project.org</a>.
The R bindings are under active development. They have been used to
compile and run an R interface to QuantLib running on Mandriva Linux
with gcc. The R bindings also work on Microsoft Windows using Visual C++.
</p>
<H2><a name="R_nn2">37.1 Bugs</a></H2>
<p>
Currently the following features are not implemented or broken:
</p>
<ul>
<li>Garbage collection of created objects
<li>C Array wrappings
</ul>
<H2><a name="R_nn3">37.2 Using R and SWIG</a></H2>
<p>
To use R and SWIG in C mode, execute the following commands where
example.c is the name of the file with the functions in them
</p>
<div class="shell">
<pre>
swig -r example.i
R CMD SHLIB example_wrap.c example.c
</pre>
</div>
<p>
The corresponding options for C++ mode are
</p>
<div class="shell">
<pre>
swig -c++ -r -o example_wrap.cpp example.i
R CMD SHLIB example_wrap.cpp example.cpp
</pre>
</div>
<p>
Note that R is sensitive to the names of the files.
The name of the wrapper file must be the
name of the library unless you use the -o option to R when building the library, for example:
</p>
<div class="shell">
<pre>
swig -c++ -r -o example_wrap.cpp example.i
R CMD SHLIB -o example.so example_wrap.cpp example.cpp
</pre>
</div>
<p>
R is also sensitive to the name of the file
extension in C and C++ mode. In C++ mode, the file extension must be .cpp
rather than .cxx for the R compile command to recognize it. If your C++ code is
in a file using something other than a .cpp extension, then it may still work using PKG_LIBS:
</p>
<div class="shell">
<pre>
swig -c++ -r -o example_wrap.cpp example.i
PKG_LIBS="example.cxx" R CMD SHLIB -o example example_wrap.cpp
</pre>
</div>
<p>
The commands produces two files. A dynamic shared object file called
example.so, or example.dll, and an R wrapper file called example.R. To load these
files, start up R and type in the following commands
</p>
<div class="shell">
<pre>
dyn.load(paste("example", .Platform$dynlib.ext, sep=""))
source("example.R")
cacheMetaData(1)
</pre>
</div>
The cacheMetaData(1) will cause R to refresh its object tables.
Without it, inheritance of wrapped objects may fail.
<p>
These two files can be loaded in any order
</p>
<p>
If you are compiling code yourself (not using R itself), there are a few things to watch out for:
</p>
<ul>
<li>The output shared library name (to the left of the file extension) MUST match the module name, or alternatively, you can also set the -package NAME command line argument. See swig -r -help for more information
<li>If you do not set the output file name appropriately, you might see errors like
<div class="shell">
<pre>
> fact(4)
Error in .Call("R_swig_fact", s_arg1, as.logical(.copy), PACKAGE = "example") :
"R_swig_fact" not available for .Call() for package "example"
</pre>
</div>
<li>Make sure the architecture of the shared library(x64 for instance), matches the architecture of the R program you want to load your shared library into
</ul>
<H2><a name="R_nn4">37.3 Precompiling large R files</a></H2>
In cases where the R file is large, one make save a lot of loading
time by precompiling the R wrapper. This can be done by creating the
file makeRData.R which contains the following
<pre>
source('BigFile.R')
save(list=ls(all=TRUE), file="BigFile.RData", compress=TRUE)
q(save="no")
</pre>
This will generate a compiled R file called BigFile.RData that
will save a large amount of loading time.
<H2><a name="R_nn5">37.4 General policy</a></H2>
<p>
The general policy of the module is to treat the C/C++ as a basic
wrapping over the underlying functions and rely on the R type system
to provide R syntax.
</p>
<H2><a name="R_language_conventions">37.5 Language conventions</a></H2>
<p>
getitem and setitem use C++ conventions (i.e. zero based indices). [<-
and [ are overloaded to allow for R syntax (one based indices and
slices)
</p>
<H2><a name="R_nn6">37.6 C++ classes</a></H2>
<p>
C++ objects are implemented as external pointer objects with the class
being the mangled name of the class. The C++ classes are encapsulated
as an SEXP with an external pointer type. The class is the mangled
name of the class. The nice thing about R is that is allows you to
keep track of the pointer object which removes the necessity for a lot
of the proxy class baggage you see in other languages.
</p>
<H2><a name="R_nn7">37.7 Enumerations</a></H2>
<p>
enumerations are characters which are then converted back and forth to
ints before calling the C routines. All of the enumeration code is
done in R.
</p>
</body>
</html>

View File

@@ -0,0 +1,21 @@
This directory contains the HTML for the SWIG users manual.
All of this HTML is hand-written. However, section numbering, indices,
and the table of contents are generated automatically by the 'maketoc.py'
script. The Makefile has further information on how the various alternative
forms of the documentation are generated from the hand-written HTML.
There are 4 types of boxes that code or whatever can be inside:
- <div class="shell">...</div>
This is for text that shows the output of running commands on the shell.
- <div class="code">...</div>
This is for either C, C++, or SWIG code
- <div class="targetlang">...</div>
This is for code in a target scripting language
- <div class="diagram">...</div>
This is for text that is not code or a shell
The general format is
<div class="foo"><pre>
whatever here
</pre></div>

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,471 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Scripting Languages</title>
<link rel="stylesheet" type="text/css" href="style.css">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body bgcolor="#ffffff">
<H1><a name="Scripting">4 Scripting Languages</a></H1>
<!-- INDEX -->
<div class="sectiontoc">
<ul>
<li><a href="#Scripting_nn2">The two language view of the world</a>
<li><a href="#Scripting_nn3">How does a scripting language talk to C?</a>
<ul>
<li><a href="#Scripting_nn4">Wrapper functions</a>
<li><a href="#Scripting_nn5">Variable linking</a>
<li><a href="#Scripting_nn6">Constants</a>
<li><a href="#Scripting_nn7">Structures and classes</a>
<li><a href="#Scripting_nn8">Proxy classes</a>
</ul>
<li><a href="#Scripting_nn9">Building scripting language extensions</a>
<ul>
<li><a href="#Scripting_nn10">Shared libraries and dynamic loading</a>
<li><a href="#Scripting_nn11">Linking with shared libraries</a>
<li><a href="#Scripting_nn12">Static linking</a>
</ul>
</ul>
</div>
<!-- INDEX -->
<p>
This chapter provides a brief overview of scripting language extension
programming and the mechanisms by which scripting language interpreters
access C and C++ code.
</p>
<H2><a name="Scripting_nn2">4.1 The two language view of the world</a></H2>
<p>
When a scripting language is used to control a C program, the
resulting system tends to look as follows:
</p>
<center><img src="ch2.1.png" alt="Scripting language input - C/C++ functions output"></center>
<p>
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.
</p>
<p>
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. </p>
<H2><a name="Scripting_nn3">4.2 How does a scripting language talk to C?</a></H2>
<p>
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.
</p>
<p>
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.
</p>
<H3><a name="Scripting_nn4">4.2.1 Wrapper functions</a></H3>
<p>
Suppose you have an ordinary C function like this :</p>
<div class="code"><pre>
int fact(int n) {
if (n &lt;= 1)
return 1;
else
return n*fact(n-1);
}
</pre></div>
<p>
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 :</p>
<ul>
<li>Gather function arguments and make sure they are valid.
<li>Call the C function.
<li>Convert the return value into a form recognized by the scripting language.
</ul>
<p>
As an example, the Tcl wrapper function for the <tt>fact()</tt>
function above example might look like the following : </p>
<div class="code"><pre>
int wrap_fact(ClientData clientData, Tcl_Interp *interp, int argc, char *argv[]) {
int result;
int arg0;
if (argc != 2) {
interp-&gt;result = "wrong # args";
return TCL_ERROR;
}
arg0 = atoi(argv[1]);
result = fact(arg0);
sprintf(interp-&gt;result, "%d", result);
return TCL_OK;
}
</pre></div>
<p>
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 :</p>
<div class="code"><pre>
int Wrap_Init(Tcl_Interp *interp) {
Tcl_CreateCommand(interp, "fact", wrap_fact, (ClientData) NULL,
(Tcl_CmdDeleteProc *) NULL);
return TCL_OK;
}
</pre></div>
<p>
When executed, Tcl will now have a new command called "<tt>fact</tt>"
that you can use like any other Tcl command.</p>
<p>
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.</p>
<H3><a name="Scripting_nn5">4.2.2 Variable linking</a></H3>
<p>
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:</p>
<div class="code"><pre>
double Foo = 3.5;
</pre></div>
<p>
It might be nice to access it from a script as follows (shown for Perl):</p>
<div class="targetlang"><pre>
$a = $Foo * 2.3; # Evaluation
$Foo = $a + 2.0; # Assignment
</pre></div>
<p>
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.
</p>
<p>
In many languages, calls to the get/set functions can be attached to
evaluation and assignment operators. Therefore, evaluating a variable
such as <tt>$Foo</tt> might implicitly call the get function. Similarly,
typing <tt>$Foo = 4</tt> would call the underlying set function to change
the value.
</p>
<H3><a name="Scripting_nn6">4.2.3 Constants</a></H3>
<p>
In many cases, a C program or library may define a large collection of
constants. For example:
</p>
<div class="code"><pre>
#define RED 0xff0000
#define BLUE 0x0000ff
#define GREEN 0x00ff00
</pre></div>
<p>
To make constants available, their values can be stored in scripting
language variables such as <tt>$RED</tt>, <tt>$BLUE</tt>, and
<tt>$GREEN</tt>. Virtually all scripting languages provide C
functions for creating variables so installing constants is usually
a trivial exercise.
</p>
<H3><a name="Scripting_nn7">4.2.4 Structures and classes</a></H3>
<p>
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?
</p>
<p>
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,
</p>
<div class="code"><pre>
struct Vector {
Vector();
~Vector();
double x, y, z;
};
</pre></div>
<p>
can be transformed into the following set of functions :
</p>
<div class="code"><pre>
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);
</pre></div>
<p>
Now, from an interpreter these function might be used as follows:
</p>
<div class="targetlang"><pre>
% set v [new_Vector]
% Vector_x_set $v 3.5
% Vector_y_get $v
% delete_Vector $v
% ...
</pre></div>
<p>
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 <tt>Vector</tt>.
</p>
<H3><a name="Scripting_nn8">4.2.5 Proxy classes</a></H3>
<p>
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 :</p>
<div class="code"><pre>
class Vector {
public:
Vector();
~Vector();
double x, y, z;
};
</pre></div>
<p>
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:
</p>
<div class="targetlang"><pre>
&gt;&gt;&gt; v = Vector()
&gt;&gt;&gt; v.x = 3
&gt;&gt;&gt; v.y = 4
&gt;&gt;&gt; v.z = -13
&gt;&gt;&gt; ...
&gt;&gt;&gt; del v
</pre></div>
<p>
Similarly, in Perl5 you may want the interface to work like this:</p>
<div class="targetlang"><pre>
$v = new Vector;
$v-&gt;{x} = 3;
$v-&gt;{y} = 4;
$v-&gt;{z} = -13;
</pre></div>
<p>
Finally, in Tcl :
</p>
<div class="targetlang"><pre>
Vector v
v configure -x 3 -y 4 -z -13
</pre></div>
<p>
When proxy classes are used, two objects are really at 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.
</p>
<H2><a name="Scripting_nn9">4.3 Building scripting language extensions</a></H2>
<p>
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 of a shared library. Alternatively, you can
recompile the scripting language interpreter with your extensions
added to it.
</p>
<H3><a name="Scripting_nn10">4.3.1 Shared libraries and dynamic loading</a></H3>
<p>
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 platforms is shown below:</p>
<div class="shell"><pre>
# Build a shared library for Solaris
gcc -fpic -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
</pre></div>
<p>
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:
</p>
<div class="targetlang"><pre>
% load ./example.so
% fact 4
24
%
</pre></div>
<p>
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 :</p>
<div class="shell"><pre>
c++ -shared example.o example_wrap.o -o example.so
</pre></div>
<H3><a name="Scripting_nn11">4.3.2 Linking with shared libraries</a></H3>
<p>
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 :</p>
<div class="targetlang"><pre>
&gt;&gt;&gt; import graph
Traceback (innermost last):
File "&lt;stdin&gt;", 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:
&gt;&gt;&gt;
</pre></div>
<p>
What this error means is that the extension module created by SWIG
depends upon a shared library called "<tt>libgraph.so</tt>" that the
system was unable to locate. To fix this problem, there are a few
approaches you can take.</p>
<ul>
<li>Link your extension and explicitly tell the linker where the
required libraries are located. Often times, this can be done with a
special linker flag such as <tt>-R</tt>, <tt>-rpath</tt>, etc. This
is not implemented in a standard manner so read the man pages for your
linker to find out more about how to set the search path for shared
libraries.
<li>Put shared libraries in the same directory as the executable. This
technique is sometimes required for correct operation on non-Unix
platforms.
<li>Set the UNIX environment variable <tt>LD_LIBRARY_PATH</tt> to the
directory where shared libraries are located before running Python.
Although this is an easy solution, it is not recommended. Consider setting
the path using linker options instead.
</ul>
<H3><a name="Scripting_nn12">4.3.3 Static linking</a></H3>
<p>
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.
</p>
<p>
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.
</p>
</body>
</html>

View File

@@ -0,0 +1,72 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>SWIG-3.0 Documentation</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body bgcolor="#ffffff">
<H1><a name="Sections">SWIG-3.0 Documentation</a></H1>
<p>
Last update : SWIG-3.0.12 (27 Jan 2017)
</p>
<H2><a name="Sections_Sections">Sections</a></H2>
<H3><a name="Sections_core_docs">SWIG Core Documentation</a></H3>
<ul>
<li><a href="Preface.html#Preface">Preface</a></li>
<li><a href="Introduction.html#Introduction">Introduction</a></li>
<li><a href="Windows.html#Windows">Getting started on Windows</a></li>
<li><a href="Scripting.html#Scripting">Scripting</a></li>
<li><a href="SWIG.html#SWIG">SWIG Basics</a> (Read this!)</li>
<li><a href="SWIGPlus.html#SWIGPlus">SWIG and C++</a></li>
<li><a href="CPlusPlus11.html#CPlusPlus11">SWIG and C++11</a></li>
<li><a href="Preprocessor.html#Preprocessor">The SWIG preprocessor</a></li>
<li><a href="Library.html#Library">The SWIG library</a></li>
<li><a href="Arguments.html#Arguments">Argument handling</a></li>
<li><a href="Typemaps.html#Typemaps">Typemaps</a></li>
<li><a href="Customization.html#Customization">Customization features</a></li>
<li><a href="Contract.html#Contract">Contracts</a></li>
<li><a href="Varargs.html#Varargs">Variable length arguments</a></li>
<li><a href="Warnings.html#Warnings">Warning messages</a></li>
<li><a href="Modules.html#Modules">Working with Modules</a></li>
<li><a href="CCache.html#CCache">Using SWIG with ccache</a></li>
</ul>
<H3><a name="Sections_language_modules">Language Module Documentation</a></H3>
<ul>
<li><a href="Allegrocl.html#Allegrocl">Allegro Common Lisp support</a></li>
<li><a href="Android.html#Android">Android support</a></li>
<li><a href="CSharp.html#CSharp">C# support</a></li>
<li><a href="Chicken.html#Chicken">Chicken support</a></li>
<li><a href="D.html#D">D support</a></li>
<li><a href="Go.html#Go">Go support</a></li>
<li><a href="Guile.html#Guile">Guile support</a></li>
<li><a href="Java.html#Java">Java support</a></li>
<li><a href="Javascript.html#Javascript">Javascript support</a></li>
<li><a href="Lisp.html#Lisp">Common Lisp support</a></li>
<li><a href="Lua.html#Lua">Lua support</a></li>
<li><a href="Modula3.html#Modula3">Modula3 support</a></li>
<li><a href="Mzscheme.html#Mzscheme">MzScheme/Racket support</a></li>
<li><a href="Ocaml.html#Ocaml">Ocaml support</a></li>
<li><a href="Octave.html#Octave">Octave support</a></li>
<li><a href="Perl5.html#Perl5">Perl5 support</a></li>
<li><a href="Php.html#Php">PHP support</a></li>
<li><a href="Pike.html#Pike">Pike support</a></li>
<li><a href="Python.html#Python">Python support</a></li>
<li><a href="R.html#R">R support</a></li>
<li><a href="Ruby.html#Ruby">Ruby support</a></li>
<li><a href="Scilab.html#Scilab">Scilab support</a></li>
<li><a href="Tcl.html#Tcl">Tcl support</a></li>
</ul>
<H3><a name="Sections_developers_docs">Developer Documentation</a></H3>
<ul>
<li><a href="Extending.html#Extending">Extending SWIG</a></li>
</ul>
</body>
</html>

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,604 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Warning Messages</title>
<link rel="stylesheet" type="text/css" href="style.css">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body bgcolor="#ffffff">
<H1><a name="Warnings">15 Warning Messages</a></H1>
<!-- INDEX -->
<div class="sectiontoc">
<ul>
<li><a href="#Warnings_nn2">Introduction</a>
<li><a href="#Warnings_suppression">Warning message suppression</a>
<li><a href="#Warnings_nn4">Enabling extra warnings</a>
<li><a href="#Warnings_nn5">Issuing a warning message</a>
<li><a href="#Warnings_symbolic_symbols">Symbolic symbols</a>
<li><a href="#Warnings_nn6">Commentary</a>
<li><a href="#Warnings_nn7">Warnings as errors</a>
<li><a href="#Warnings_nn8">Message output format</a>
<li><a href="#Warnings_nn9">Warning number reference</a>
<ul>
<li><a href="#Warnings_nn10">Deprecated features (100-199)</a>
<li><a href="#Warnings_nn11">Preprocessor (200-299)</a>
<li><a href="#Warnings_nn12">C/C++ Parser (300-399)</a>
<li><a href="#Warnings_nn13">Types and typemaps (400-499) </a>
<li><a href="#Warnings_nn14">Code generation (500-599)</a>
<li><a href="#Warnings_nn15">Language module specific (700-899) </a>
<li><a href="#Warnings_nn16">User defined (900-999)</a>
</ul>
<li><a href="#Warnings_nn17">History</a>
</ul>
</div>
<!-- INDEX -->
<H2><a name="Warnings_nn2">15.1 Introduction</a></H2>
<p>
During compilation, SWIG may generate a variety of warning messages. For example:
</p>
<div class="shell">
<pre>
example.i:16: Warning 501: Overloaded declaration ignored. bar(double)
example.i:15: Warning 501: Previous declaration is bar(int)
</pre>
</div>
<p>
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.
</p>
<H2><a name="Warnings_suppression">15.2 Warning message suppression</a></H2>
<p>
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 <tt>-w</tt> command line option. For example:
</p>
<div class="shell">
<pre>
% swig -python -w501 example.i
% swig -python -w501,505,401 example.i
</pre>
</div>
<p>
Alternatively, warnings can be suppressed by inserting a special preprocessor pragma
into the input file:
</p>
<div class="code">
<pre>
%module example
#pragma SWIG nowarn=501
#pragma SWIG nowarn=501,505,401
</pre>
</div>
<p>
Finally, code-generation warnings can be disabled on a declaration by declaration basis using
the <tt>%warnfilter</tt> directive. For example:
</p>
<div class="code">
<pre>
%module example
%warnfilter(501) foo;
...
int foo(int);
int foo(double); // Silently ignored.
</pre>
</div>
<p>
The <tt>%warnfilter</tt> directive has the same semantics as other declaration modifiers like
<tt>%rename</tt>, <tt>%ignore</tt> and <tt>%feature</tt>, see the
<a href="Customization.html#Customization_features">%feature directive</a> section. For example, if you wanted to
suppress a warning for a method in a class hierarchy, you could do this:
</p>
<div class="code">
<pre>
%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
...
};
</pre>
</div>
<p>
Warnings can be suppressed for an entire class by supplying a class name. For example:
</p>
<div class="code">
<pre>
%warnfilter(501) Object;
class Object {
public:
... // All 501 warnings ignored in class
};
</pre>
</div>
<p>
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 <em>broken</em> in
your interface. Ignore the warning messages at your own peril.
</p>
<H2><a name="Warnings_nn4">15.3 Enabling extra warnings</a></H2>
<p>
Some warning messages are disabled by default and are generated only
to provide additional diagnostics. These warnings can be turned on using the
<tt>-Wextra</tt> option. For example:
</p>
<div class="shell">
<pre>
% swig -Wextra -python example.i
</pre>
</div>
<p>
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:
</p>
<div class="shell">
<pre>
% swig -w+309,+452 example.i
</pre>
</div>
<p>
or in your interface file use either
</p>
<div class="code">
<pre>
#pragma SWIG nowarn=+309,+452
</pre>
</div>
<p>
or
</p>
<div class="code">
<pre>
%warnfilter(+309,+452) foo;
</pre>
</div>
<p>
Note: selective enabling of warnings with <tt>%warnfilter</tt> overrides any global settings you might have
made using <tt>-w</tt> or <tt>#pragma</tt>.
</p>
<p>
You can of course also enable all warnings and suppress a select few, for example:
</p>
<div class="shell">
<pre>
% swig -Wextra -w309,452 example.i
</pre>
</div>
<p>
The warnings on the right take precedence over the warnings on the left, so in the above example <tt>-Wextra</tt> adds numerous warnings including 452, but then <tt>-w309,452</tt> overrides this and so 452 is suppressesed.
</p>
<p>
If you would like all warnings to appear, regardless of the warning filters used, then use the <tt>-Wall</tt> option.
The <tt>-Wall</tt> option also turns on the extra warnings that <tt>-Wextra</tt> adds, however, it is subtely different.
When <tt>-Wall</tt> is used, it also disables all other warning filters,
that is, any warnings suppressed or added in <tt>%warnfilter</tt>, <tt>#pragma SWIG nowarn</tt>
or the <tt>-w</tt> option.
</p>
<H2><a name="Warnings_nn5">15.4 Issuing a warning message</a></H2>
<p>
Warning messages can be issued from an interface file using a number of directives. The
<tt>%warn</tt> directive is the most simple:
</p>
<div class="code">
<pre>
%warn "900:This is your last warning!"
</pre>
</div>
<p>
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.
</p>
<p>
The <tt>%ignorewarn</tt> directive is the same as <tt>%ignore</tt> except that it issues a
warning message whenever a matching declaration is found. For example:
</p>
<div class="code">
<pre>
%ignorewarn("362:operator= ignored") operator=;
</pre>
</div>
<p>
Warning messages can be associated with typemaps using the
<tt>warning</tt> attribute of a typemap declaration. For example:
</p>
<div class="code">
<pre>
%typemap(in, warning="901:You are really going to regret this usage of $1_type $1_name") blah * {
...
}
</pre>
</div>
<p>
In this case, the warning message will be printed whenever the typemap is actually used and the <a href="Typemaps.html#Typemaps_special_variables">special variables</a> will be expanded as appropriate, for example:
</p>
<div class="shell">
<pre>
example.i:23: Warning 901: You are really going to regret this usage of blah * self
example.i:24: Warning 901: You are really going to regret this usage of blah * stuff
</pre>
</div>
<H2><a name="Warnings_symbolic_symbols">15.5 Symbolic symbols</a></H2>
<p>
The <tt>swigwarn.swg</tt> file that is installed with SWIG contains symbol constants that could also be
used in <tt>%warnfilter</tt> and <tt>#pragma SWIG nowarn</tt>.
For example this file contains the following line:
</p>
<div class="code">
<pre>
%define SWIGWARN_TYPE_UNDEFINED_CLASS 401 %enddef
</pre>
</div>
<p>
so <tt>SWIGWARN_TYPE_UNDEFINED_CLASS</tt> could be used instead of 401, for example:
</p>
<div class="code">
<pre>
#pragma SWIG nowarn=SWIGWARN_TYPE_UNDEFINED_CLASS
</pre>
</div>
<p>
or
</p>
<div class="code">
<pre>
%warnfilter(SWIGWARN_TYPE_UNDEFINED_CLASS) Foo;
</pre>
</div>
<H2><a name="Warnings_nn6">15.6 Commentary</a></H2>
<p>
The ability to suppress warning messages is really only provided for
advanced users and is not recommended in normal use. You are advised
to modify your interface to fix the problems highlighted by the warnings
wherever possible instead of suppressing warnings.
</p>
<p>
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.
</p>
<H2><a name="Warnings_nn7">15.7 Warnings as errors</a></H2>
<p>
Warnings can be handled as errors by using the <tt>-Werror</tt> command line
option. This will cause SWIG to exit with a non successful exit code if a
warning is encountered.
</p>
<H2><a name="Warnings_nn8">15.8 Message output format</a></H2>
<p>
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:
</p>
<div class="shell"><pre>
$ swig -python -Fstandard example.i
example.i:4: Syntax error in input(1).
$ swig -python -Fmicrosoft example.i
example.i(4) : Syntax error in input(1).
</pre></div>
<H2><a name="Warnings_nn9">15.9 Warning number reference</a></H2>
<H3><a name="Warnings_nn10">15.9.1 Deprecated features (100-199)</a></H3>
<ul>
<li>101. Deprecated <tt>%extern</tt> directive.
<li>102. Deprecated <tt>%val</tt> directive.
<li>103. Deprecated <tt>%out</tt> directive.
<li>104. Deprecated <tt>%disabledoc</tt> directive.
<li>105. Deprecated <tt>%enabledoc</tt> directive.
<li>106. Deprecated <tt>%doconly</tt> directive.
<li>107. Deprecated <tt>%style</tt> directive.
<li>108. Deprecated <tt>%localstyle</tt> directive.
<li>109. Deprecated <tt>%title</tt> directive.
<li>110. Deprecated <tt>%section</tt> directive.
<li>111. Deprecated <tt>%subsection</tt> directive.
<li>112. Deprecated <tt>%subsubsection</tt> directive.
<li>113. Deprecated <tt>%addmethods</tt> directive.
<li>114. Deprecated <tt>%readonly</tt> directive.
<li>115. Deprecated <tt>%readwrite</tt> directive.
<li>116. Deprecated <tt>%except</tt> directive.
<li>117. Deprecated <tt>%new</tt> directive.
<li>118. Deprecated <tt>%typemap(except)</tt>.
<li>119. Deprecated <tt>%typemap(ignore)</tt>.
<li>120. Deprecated command line option (-runtime, -noruntime).
<li>121. Deprecated <tt>%name</tt> directive.
<li>126. The 'nestedworkaround' feature is deprecated.
</ul>
<H3><a name="Warnings_nn11">15.9.2 Preprocessor (200-299)</a></H3>
<ul>
<li>201. Unable to find <em>filename</em>.
<li>202. Could not evaluate expression <em>expr</em>.
<li>203. Both includeall and importall are defined: using includeall.
<li>204. CPP #warning, "<em>warning</em>".
<li>205. CPP #error, "<em>error</em>".
<li>206. Unexpected tokens after #<em>directive</em> directive.
</ul>
<H3><a name="Warnings_nn12">15.9.3 C/C++ Parser (300-399)</a></H3>
<ul>
<li>301. <tt>class</tt> keyword used, but not in C++ mode.
<li>302. Identifier '<em>name</em>' redefined (ignored).
<li>303. <tt>%extend</tt> defined for an undeclared class '<em>name</em>'.
<li>304. Unsupported constant value (ignored).
<li>305. Bad constant value (ignored).
<li>306. '<em>identifier</em>' is private in this context.
<li>307. Can't set default argument value (ignored)
<li>308. Namespace alias '<em>name</em>' not allowed here. Assuming '<em>name</em>'
<li>309. [private | protected] inheritance ignored.
<li>310. Template '<em>name</em>' was already wrapped as '<em>name</em>' (ignored)
<li>312. Unnamed nested class not currently supported (ignored).
<li>313. Unrecognized extern type "<em>name</em>" (ignored).
<li>314. '<em>identifier</em>' is a <em>lang</em> keyword.
<li>315. Nothing known about '<em>identifier</em>'.
<li>316. Repeated %module directive.
<li>317. Specialization of non-template '<em>name</em>'.
<li>318. Instantiation of template '<em>name</em>' is ambiguous, instantiation <em>templ</em> used, instantiation <em>templ</em> ignored.
<li>319. No access specifier given for base class <em>name</em> (ignored).
<li>320. Explicit template instantiation ignored.
<li>321. <em>identifier</em> conflicts with a built-in name.
<li>322. Redundant redeclaration of '<em>name</em>'.
<li>323. Recursive scope inheritance of '<em>name</em>'.
<li>324. Named nested template instantiations not supported. Processing as if no name was given to %template().
<li>325. Nested <em>kind</em> not currently supported (<em>name</em> ignored).
<li>326. Deprecated %extend name used - the <em>kind</em> name '<em>name</em>' should be used instead of the typedef name '<em>name</em>'.
<li>350. operator new ignored.
<li>351. operator delete ignored.
<li>352. operator+ ignored.
<li>353. operator- ignored.
<li>354. operator* ignored.
<li>355. operator/ ignored.
<li>356. operator% ignored.
<li>357. operator^ ignored.
<li>358. operator&amp; ignored.
<li>359. operator| ignored.
<li>360. operator~ ignored.
<li>361. operator! ignored.
<li>362. operator= ignored.
<li>363. operator&lt; ignored.
<li>364. operator&gt; ignored.
<li>365. operator+= ignored.
<li>366. operator-= ignored.
<li>367. operator*= ignored.
<li>368. operator/= ignored.
<li>369. operator%= ignored.
<li>370. operator^= ignored.
<li>371. operator&amp;= ignored.
<li>372. operator|= ignored.
<li>373. operator&lt;&lt; ignored.
<li>374. operator&gt;&gt;ignored.
<li>375. operator&lt;&lt;= ignored.
<li>376. operator&gt;&gt;= ignored.
<li>377. operator== ignored.
<li>378. operator!= ignored.
<li>379. operator&lt;= ignored.
<li>380. operator&gt;= ignored.
<li>381. operator&amp;&amp; ignored.
<li>382. operator|| ignored.
<li>383. operator++ ignored.
<li>384. operator-- ignored.
<li>385. operator, ignored.
<li>386. operator-&lt;* ignored.
<li>387. operator-&lt; ignored.
<li>388. operator() ignored.
<li>389. operator[] ignored.
<li>390. operator+ ignored (unary).
<li>391. operator- ignored (unary).
<li>392. operator* ignored (unary).
<li>393. operator&amp; ignored (unary).
<li>394. operator new[] ignored.
<li>395. operator delete[] ignored.
</ul>
<H3><a name="Warnings_nn13">15.9.4 Types and typemaps (400-499) </a></H3>
<ul>
<li>401. Nothing known about class 'name'. Ignored.
<li>402. Base class 'name' is incomplete.
<li>403. Class 'name' might be abstract.
<li>450. Deprecated typemap feature ($source/$target).
<li>451. Setting const char * variable may leak memory.
<li>452. Reserved
<li>453. Can't apply (pattern). No typemaps are defined.
<li>460. Unable to use type <em>type</em> as a function argument.
<li>461. Unable to use return type <em>type</em> in function <em>name</em>.
<li>462. Unable to set variable of type <em>type</em>.
<li>463. Unable to read variable of type <em>type</em>.
<li>464. Unsupported constant value.
<li>465. Unable to handle type <em>type</em>.
<li>466. Unsupported variable type <em>type</em>.
<li>467. Overloaded <em>declaration</em> not supported (incomplete type checking rule - no precedence level in typecheck typemap for '<em>type</em>')
<li>468. No 'throw' typemap defined for exception type <em>type</em>
<li>469. No or improper directorin typemap defined for <em>type</em>
<li>470. Thread/reentrant unsafe wrapping, consider returning by value instead.
<li>471. Unable to use return type <em>type</em> in director method
<li>474. Method <em>method</em> usage of the optimal attribute ignored in the out typemap as the following cannot be used to generate optimal code: <em>code</em>
<li>475. Multiple calls to <em>method</em> might be generated due to optimal attribute usage in the out typemap.
<li>476. Initialization using std::initializer_list.
<li>477. No directorthrows typemap defined for <em>type</em>
</ul>
<H3><a name="Warnings_nn14">15.9.5 Code generation (500-599)</a></H3>
<ul>
<li>501. Overloaded declaration ignored. <em>decl</em>. Previous declaration is <em>decl</em>.
<li>502. Overloaded constructor ignored. <em>decl</em>. Previous declaration is <em>decl</em>.
<li>503. Can't wrap '<em>identifier</em>' unless renamed to a valid identifier.
<li>504. Function <em>name</em> must have a return type. Ignored.
<li>505. Variable length arguments discarded.
<li>506. Can't wrap varargs with keyword arguments enabled.
<li>507. Adding native function <em>name</em> not supported (ignored).
<li>508. Declaration of '<em>name</em>' shadows declaration accessible via operator-&gt;(), previous declaration of'<em>declaration</em>'.
<li>509. Overloaded method <em>declaration</em> effectively ignored, as it is shadowed by <em>declaration</em>.
<li>510. Friend function '<em>name</em>' ignored.
<li>511. Can't use keyword arguments with overloaded functions.
<li>512. Overloaded method <em>declaration</em> ignored, using non-const method <em>declaration</em> instead.
<li>513. Can't generate wrappers for unnamed struct/class.
<li>514.
<li>515.
<li>516. Overloaded method <em>declaration</em> ignored, using <em>declaration</em> instead.
<li>517.
<li>518. Portability warning: File <em>file1</em> will be overwritten by <em>file2</em> on case insensitive filesystems such as Windows' FAT32 and NTFS unless the class/module name is renamed.
<li>519. %template() contains no name. Template method ignored: <em>declaration</em>
<li>520. <em>Base/Derived</em> class '<em>classname1</em>' of '<em>classname2</em>' is not similarly marked as a smart pointer.
<li>521. Illegal destructor name <em>name</em>. Ignored.
<li>522. Use of an illegal constructor name '<em>name</em>' in %extend is deprecated, the constructor name should be '<em>name</em>'.
<li>523. Use of an illegal destructor name '<em>name</em>' in %extend is deprecated, the destructor name should be '<em>name</em>'.
</ul>
<H3><a name="Warnings_nn15">15.9.6 Language module specific (700-899) </a></H3>
<ul>
<li>801. Wrong name (corrected to '<em>name</em>'). (Ruby).
</ul>
<ul>
<li>810. No jni typemap defined for <em>type</em> (Java).
<li>811. No jtype typemap defined for <em>type</em> (Java).
<li>812. No jstype typemap defined for <em>type</em> (Java).
<li>813. Warning for <em>classname</em>, base <em>baseclass</em> ignored. Multiple inheritance is not supported in Java. (Java).
<li>814.
<li>815. No javafinalize typemap defined for <em>type</em> (Java).
<li>816. No javabody typemap defined for <em>type</em> (Java).
<li>817. No javaout typemap defined for <em>type</em> (Java).
<li>818. No javain typemap defined for <em>type</em> (Java).
<li>819. No javadirectorin typemap defined for <em>type</em> (Java).
<li>820. No javadirectorout typemap defined for <em>type</em> (Java).
<li>821.
<li>822. Covariant return types not supported in Java. Proxy method will return <em>basetype</em> (Java).
<li>823. No javaconstruct typemap defined for <em>type</em> (Java).
<li>824. Missing JNI descriptor in directorin typemap defined for <em>type</em> (Java).
<li>825. "directorconnect" attribute missing in <em>type</em> "javaconstruct" typemap. (Java).
<li>826. The nspace feature is used on '<em>type</em>' without -package. The generated code may not compile as Java does not support types declared in a named package accessing types declared in an unnamed package. (Java).
</ul>
<ul>
<li>830. No ctype typemap defined for <em>type</em> (C#).
<li>831. No cstype typemap defined for <em>type</em> (C#).
<li>832. No cswtype typemap defined for <em>type</em> (C#).
<li>833. Warning for <em>classname</em>, base <em>baseclass</em> ignored. Multiple inheritance is not supported in C#. (C#).
<li>834.
<li>835. No csfinalize typemap defined for <em>type</em> (C#).
<li>836. No csbody typemap defined for <em>type</em> (C#).
<li>837. No csout typemap defined for <em>type</em> (C#).
<li>838. No csin typemap defined for <em>type</em> (C#).
<li>839.
<li>840.
<li>841.
<li>842. Covariant return types not supported in C#. Proxy method will return <em>basetype</em> (C#).
<li>843. No csconstruct typemap defined for <em>type</em> (C#).
<li>844. C# exception may not be thrown - no $excode or excode attribute in <em>typemap</em> typemap. (C#).
<li>845. Unmanaged code contains a call to a SWIG_CSharpSetPendingException method and C# code does not handle pending exceptions via the canthrow attribute. (C#).
</ul>
<ul>
<li>870. Warning for <em>classname</em>: Base <em>baseclass</em> ignored. Multiple inheritance is not supported in PHP. (Php).
<li>871. Unrecognized pragma <em>pragma</em>. (Php).
</ul>
<H3><a name="Warnings_nn16">15.9.7 User defined (900-999)</a></H3>
<p>
These numbers can be used by your own application.
</p>
<H2><a name="Warnings_nn17">15.10 History</a></H2>
<p>
The ability to control warning messages was first added to SWIG-1.3.12.
</p>
</body>
</html>

View File

@@ -0,0 +1,441 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Getting started on Windows</title>
<link rel="stylesheet" type="text/css" href="style.css">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body bgcolor="#ffffff">
<H1><a name="Windows">3 Getting started on Windows </a></H1>
<!-- INDEX -->
<div class="sectiontoc">
<ul>
<li><a href="#Windows_installation">Installation on Windows</a>
<ul>
<li><a href="#Windows_executable">Windows Executable</a>
</ul>
<li><a href="#Windows_examples">SWIG Windows Examples</a>
<ul>
<li><a href="#Windows_visual_studio">Instructions for using the Examples with Visual Studio</a>
<ul>
<li><a href="#Windows_csharp">C#</a>
<li><a href="#Windows_java">Java</a>
<li><a href="#Windows_perl">Perl</a>
<li><a href="#Windows_python">Python</a>
<li><a href="#Windows_tcl">TCL</a>
<li><a href="#Windows_r">R</a>
<li><a href="#Windows_ruby">Ruby</a>
</ul>
<li><a href="#Windows_other_compilers">Instructions for using the Examples with other compilers</a>
</ul>
<li><a href="#Windows_cygwin_mingw">SWIG on Cygwin and MinGW</a>
<ul>
<li><a href="#Windows_swig_exe">Building swig.exe on Windows</a>
<ul>
<li><a href="#Windows_mingw_msys">Building swig.exe using MinGW and MSYS</a>
<li><a href="#Windows_cygwin">Building swig.exe using Cygwin</a>
<li><a href="#Windows_building_alternatives">Building swig.exe alternatives</a>
</ul>
<li><a href="#Windows_examples_cygwin">Running the examples on Windows using Cygwin</a>
</ul>
<li><a href="#Windows_interface_file">Microsoft extensions and other Windows quirks</a>
</ul>
</div>
<!-- INDEX -->
<p>
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.
</p>
<H2><a name="Windows_installation">3.1 Installation on Windows</a></H2>
<p>
SWIG does not come with the usual Windows type installation program, however it is quite easy to get started. The main steps are:
</p>
<ul>
<li>Download the swigwin zip package from the <a href="http://www.swig.org">SWIG website</a> and unzip into a directory. This is all that needs downloading for the Windows platform.
<li>Set environment variables as described in the <a href="#Windows_examples">SWIG Windows Examples</a> section in order to run examples using Visual C++.
</ul>
<H3><a name="Windows_executable">3.1.1 Windows Executable</a></H3>
<p>
The swigwin distribution contains the SWIG Windows executable, swig.exe, which will run on 32 bit versions of Windows, ie Windows 95 and later.
If you want to build your own swig.exe have a look at <a href="#Windows_swig_exe">Building swig.exe on Windows</a>.
</p>
<H2><a name="Windows_examples">3.2 SWIG Windows Examples</a></H2>
<p>
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.
Newer versions of Visual Studio should be able to open and convert these project files.
Each C# example comes with a Visual Studio 2005 solution and associated 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 <a href="#Windows_examples_cygwin">examples using Cygwin</a>.
<p>
More information on each of the examples is available with the examples distributed with SWIG (Examples/index.html).
<H3><a name="Windows_visual_studio">3.2.1 Instructions for using the Examples with Visual Studio</a></H3>
<p>
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 <b>before</b> 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.
</p>
<p>
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.
</p>
<H4><a name="Windows_csharp">3.2.1.1 C#</a></H4>
<p>
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 or later, select Release Build, and do a Rebuild All from the Build menu.
The accompanying C# and C++ project files are automatically used by the solution file.
</p>
<H4><a name="Windows_java">3.2.1.2 Java</a></H4>
<p>
<b><tt>JAVA_INCLUDE</tt></b> : Set this to the directory containing jni.h<br>
<b><tt>JAVA_BIN</tt></b> : Set this to the bin directory containing javac.exe<p>
Example using JDK1.3:<br>
<tt>
JAVA_INCLUDE: D:\jdk1.3\include<br>
JAVA_BIN: D:\jdk1.3\bin<br>
</tt>
</p>
<H4><a name="Windows_perl">3.2.1.3 Perl</a></H4>
<p>
<b><tt>PERL5_INCLUDE</tt></b> : Set this to the directory containing perl.h<br>
<b><tt>PERL5_LIB</tt></b> : Set this to the Perl library including path for linking<p>
Example using nsPerl 5.004_04:<p>
<tt>
PERL5_INCLUDE: D:\nsPerl5.004_04\lib\CORE<br>
PERL5_LIB: D:\nsPerl5.004_04\lib\CORE\perl.lib<br>
</tt>
</p>
<H4><a name="Windows_python">3.2.1.4 Python</a></H4>
<p>
<b><tt>PYTHON_INCLUDE</tt></b> : Set this to the directory that contains Python.h<br>
<b><tt>PYTHON_LIB</tt></b> : Set this to the python library including path for linking<p>
Example using Python 2.1.1:<br>
<tt>
PYTHON_INCLUDE: D:\python21\include<br>
PYTHON_LIB: D:\python21\libs\python21.lib<br>
</tt>
</p>
<H4><a name="Windows_tcl">3.2.1.5 TCL</a></H4>
<p>
<b><tt>TCL_INCLUDE</tt></b> : Set this to the directory containing tcl.h<br>
<b><tt>TCL_LIB</tt></b> : Set this to the TCL library including path for linking<p>
Example using ActiveTcl 8.3.3.3<br>
<tt>
TCL_INCLUDE: D:\tcl\include<br>
TCL_LIB: D:\tcl\lib\tcl83.lib<br>
</tt>
</p>
<H4><a name="Windows_r">3.2.1.6 R</a></H4>
<p>
<b><tt>R_INCLUDE</tt></b> : Set this to the directory containing R.h<br>
<b><tt>R_LIB</tt></b> : Set this to the R library (Rdll.lib) including path for linking. The library needs to be built as described in the R README.packages file (the pexports.exe approach is the easiest).<p>
Example using R 2.5.1:<br>
<tt>
R_INCLUDE: C:\Program Files\R\R-2.5.1\include<br>
R_LIB: C:\Program Files\R\R-2.5.1\bin\Rdll.lib<br>
</tt>
</p>
<H4><a name="Windows_ruby">3.2.1.7 Ruby</a></H4>
<p>
<b><tt>RUBY_INCLUDE</tt></b> : Set this to the directory containing ruby.h<br>
<b><tt>RUBY_LIB</tt></b> : Set this to the ruby library including path for linking<p>
Example using Ruby 1.6.4:<br>
<tt>
RUBY_INCLUDE: D:\ruby\lib\ruby\1.6\i586-mswin32<br>
RUBY_LIB: D:\ruby\lib\mswin32-ruby16.lib<br>
</tt>
</p>
<H3><a name="Windows_other_compilers">3.2.2 Instructions for using the Examples with other compilers</a></H3>
<p>
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.
</p>
<H2><a name="Windows_cygwin_mingw">3.3 SWIG on Cygwin and MinGW</a></H2>
<p>
SWIG can also be compiled and run using <a href="http://www.cygwin.com">Cygwin</a> or <a href="http://www.mingw.org">MinGW</a> 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.
</p>
<H3><a name="Windows_swig_exe">3.3.1 Building swig.exe on Windows</a></H3>
<p>
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.
</p>
<H4><a name="Windows_mingw_msys">3.3.1.1 Building swig.exe using MinGW and MSYS</a></H4>
<p>
The short abbreviated instructions follow...
</p>
<ul>
<li>Install MinGW and MSYS from the <a href="http://www.mingw.org">MinGW</a> site. This provides a Unix environment on Windows.
<li>Follow the usual Unix instructions in the README file in the SWIG root directory to build swig.exe from the MinGW command prompt.
</ul>
<p>
The step by step instructions to download and install MinGW and MSYS, then download and build the latest version of SWIG from Github follow...
Note that the instructions for obtaining SWIG from Github are also online at <a href="http://www.swig.org/svn.html">SWIG Bleeding Edge</a>.
</p>
<p>
<b>Pitfall note:</b>
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.
</p>
<ol>
<li>
Download the following packages from the <a href="http://www.mingw.org/download.shtml">MinGW download page</a>
or <a href="http://sourceforge.net/projects/mingw/files/">MinGW SourceForge download page</a>.
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.
<ul>
<li>MinGW-3.1.0-1.exe</li>
<li>MSYS-1.0.11-2004.04.30-1.exe</li>
<li>msysDTK-1.0.1.exe</li>
<li>bison-2.0-MSYS.tar.gz</li>
<li>msys-autoconf-2.59.tar.bz2</li>
<li>msys-automake-1.8.2.tar.bz2</li>
</ul>
</li>
<li>
Install MinGW-3.1.0-1.exe (C:\MinGW is default location.)
</li>
<li>
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,
<ul>
<li>Answer y to the "do you wish to continue with the post install?"</li>
<li>Answer y to the "do you have MinGW installed?"</li>
<li>Type in the folder in which you installed MinGW (C:/MinGW is default)</li>
</ul>
</li>
<li>
Install msysDTK-1.0.1.exe to the same folder that you installed MSYS (C:\msys\1.0 is default).
</li>
<li>
Copy the following to the MSYS install folder (C:\msys\1.0 is default):
<ul>
<li>msys-automake-1.8.2.tar.bz2</li>
<li>msys-autoconf-2.59.tar.bz2</li>
<li>bison-2.0-MSYS.tar.gz</li>
</ul>
</li>
<li>
Start the MSYS command prompt and execute:
<div class="shell"><pre>
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
</pre></div>
</li>
<li>
The very latest development version of SWIG is available from <a href="https://github.com/swig/swig">SWIG on Github</a>
and can be downloaded as a zip file or if you have Git installed, via Git.
Either download the latest <a href="https://github.com/swig/swig/archive/master.zip">Zip file</a> snapshot and unzip and rename the top level folder to /usr/src/swig.
Otherwise if using Git, type in the following:
<div class="shell"><pre>
mkdir /usr/src
cd /usr/src
git clone https://github.com/swig/swig.git
</pre></div>
<b>Pitfall note:</b>
If you want to place SWIG in 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.
</li>
<li>
The PCRE third party library needs to be built next.
Download the latest PCRE source tarball, such as <tt>pcre-8.10.tar.bz2</tt>, from
<a href=http://www.pcre.org>PCRE</a> and place in the <tt>/usr/src/swig</tt> directory.
Build PCRE as a static library using the Tools/pcre-build.sh script as follows:
<div class="shell"><pre>
cd /usr/src/swig
Tools/pcre-build.sh
</pre></div>
</li>
<li>
You are now ready to build SWIG. Execute the following commands to build swig.exe:
<div class="shell"><pre>
cd /usr/src/swig
./autogen.sh
./configure
make
</pre></div>
</li>
</ol>
<H4><a name="Windows_cygwin">3.3.1.2 Building swig.exe using Cygwin</a></H4>
<p>
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 <tt>autogen.sh</tt> script and will only need regenerating in circumstances such as changing the build system.
</p>
<H4><a name="Windows_building_alternatives">3.3.1.3 Building swig.exe alternatives</a></H4>
<p>
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.
</p>
<H3><a name="Windows_examples_cygwin">3.3.2 Running the examples on Windows using Cygwin</a></H3>
<p>
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.
</p>
<H2><a name="Windows_interface_file">3.4 Microsoft extensions and other Windows quirks</a></H2>
<p>
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 <tt>__declspec(dllimport)</tt>, <tt>__stdcall</tt> etc.
There is a Windows interface file, <tt>windows.i</tt>, to deal with these calling conventions though.
The file also contains typemaps for handling commonly used Windows specific types such as <tt>__int64</tt>, <tt>BOOL</tt>, <tt>DWORD</tt> etc.
Include it like you would any other interface file, for example:
</p>
<div class="code"><pre>
%include &lt;windows.i&gt;
__declspec(dllexport) ULONG __stdcall foo(DWORD, __int32);
</pre></div>
<p>Note that if you follow Microsoft's recommendation of wrapping the
<tt>__declspec</tt> calls in a preprocessor definition, you will need to
make sure that the definition is included by SWIG as well, by either defining it
manually or via a header. For example, if you have specified the
preprocessor definition in a header named <tt>export_lib.h</tt> and include
other headers which depend on it, you should use the <tt>%include</tt> directive
to include the definition explicitly. For example, if you had a header file,
<tt>bar.h</tt>, which depended on <tt>export_lib.h</tt>, your SWIG definition
file might look like:</p>
<div class="code"><pre>
// bar.i
%module bar
%include &lt;windows.i&gt;
%include "export_lib.h"
%include "bar.h"
</pre></div>
<p>
where export_lib.h may contain:
</p>
<div class="code"><pre>
// export_lib.h
#define BAR_API __declspec(dllexport)
</pre></div>
<p>
and bar.h may look like:
</p>
<div class="code"><pre>
// bar.h
#include "export_lib.h"
BAR_API void bar_function(int, double);
</pre></div>
<p>
Using the preprocessor to remove BAR_API is a popular simpler solution:
</p>
<div class="code"><pre>
// bar.i
%module bar
#define BAR_API
%include "bar.h"
</pre></div>
</body>
</html>

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.1 KiB

View File

@@ -0,0 +1,41 @@
Preface.html
Introduction.html
Windows.html
Scripting.html
SWIG.html
SWIGPlus.html
CPlusPlus11.html
Preprocessor.html
Library.html
Arguments.html
Typemaps.html
Customization.html
Contract.html
Varargs.html
Warnings.html
Modules.html
CCache.html
Allegrocl.html
Android.html
CSharp.html
Chicken.html
D.html
Go.html
Guile.html
Java.html
Javascript.html
Lisp.html
Lua.html
Modula3.html
Mzscheme.html
Ocaml.html
Octave.html
Perl5.html
Php.html
Pike.html
Python.html
R.html
Ruby.html
Scilab.html
Tcl.html
Extending.html

View File

@@ -0,0 +1,30 @@
#!/usr/bin/python
# Replace the inline htmldoc stylesheet with the SWIG stylesheet
import sys
import string
filename = sys.argv[1]
data = open(filename).read()
open(filename+".bak","w").write(data)
swigstyle = "\n" + open("style.css").read()
lines = data.splitlines()
result = [ ]
skip = False
for s in lines:
if not skip:
result.append(s)
if s == "<STYLE TYPE=\"text/css\"><!--":
result.append(swigstyle)
skip = True
elif s == "--></STYLE>":
result.append(s)
skip = False
data = "\n".join(result)
open(filename,"w").write(data)

View File

@@ -0,0 +1,19 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>SWIG-3.0 Documentation</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body bgcolor="#ffffff">
<H1><a name="index">SWIG-3.0 Documentation</a></H1>
The SWIG documentation is available in one of the following formats.
<ul>
<li>HTML documentation with one chapter per page.
Please start with either the <a href="Sections.html#Sections">Sections summary</a> or the <a href="Contents.html#Contents">Detailed table of contents</a>.</li>
<li>HTML documentation on a <a href="SWIGDocumentation.html">single HTML page</a>.</li>
<li><a href="SWIGDocumentation.pdf">PDF document</a>.</li>
</ul>
</body>
</html>

View File

@@ -0,0 +1,3 @@
[filtering]
ignorewarnings=http-robots-denied
ignorewarnings=https-certificate-error

View File

@@ -0,0 +1,226 @@
#!/usr/bin/env python
###############################################################################
# Takes a chapter as input and adds internal links and numbering to all
# of the H1, H2, H3, H4 and H5 sections.
#
# Every heading HTML tag (H1, H2 etc) is given an autogenerated name to link
# to. However, if the name is not an autogenerated name from a previous run,
# it will be kept. If it is autogenerated, it might change on subsequent runs
# of this program. Thus if you want to create links to one of the headings,
# then change the heading link name to something that does not look like an
# autogenerated link name.
###############################################################################
import sys
import re
import string
###############################################################################
# Functions
###############################################################################
# Regexs for <a name="..."></a>
alink = re.compile(r"<a *name *= *\"(.*)\">.*</a>", re.IGNORECASE)
heading = re.compile(r"(_nn\d)", re.IGNORECASE)
def getheadingname(m):
autogeneratedheading = True;
if m.group(1) != None:
amatch = alink.match(m.group(1))
if amatch:
# A non-autogenerated heading - keep it
headingname = amatch.group(1)
autogeneratedheading = heading.match(headingname)
if autogeneratedheading:
# The heading name was either non-existent or autogenerated,
# We can create a new heading / change the existing heading
headingname = "%s_nn%d" % (filenamebase, nameindex)
return headingname
# Return heading - 1.1. Introduction in the examples below:
# old style example: <H2><a name="Preface_nn2"></a>1.1 Introduction</H2>
# new style example: <H2><a name="Preface_nn2">1.1 Introduction</a></H2>
def getheadingtext(m, s):
prevheadingtext_newstyle = m.group(2)
prevheadingtext_oldstyle = m.group(3)
if len(prevheadingtext_oldstyle) == 0 and len(prevheadingtext_newstyle) == 0:
raise RuntimeError("No heading text in line:\n%s" % s)
if len(prevheadingtext_oldstyle) > 0 and len(prevheadingtext_newstyle) > 0:
raise RuntimeError("Two heading texts, only one should be specified in line:\n%s" % s)
prevheadingtext = prevheadingtext_oldstyle if len(prevheadingtext_oldstyle) > 0 else prevheadingtext_newstyle
return prevheadingtext
###############################################################################
# Main program
###############################################################################
if len(sys.argv) != 3:
print "usage: makechap.py filename num"
sys.exit(1)
filename = sys.argv[1]
filenamebase = string.split(filename,".")[0]
num = int(sys.argv[2])
section = 0
subsection = 0
subsubsection = 0
nameindex = 0
name = ""
# Regexs for <h1>,... <h5> sections
h1 = re.compile(r".*?<H1>(<a.*?>\s*[\d\s]*(.*?)</a>)*[\d\s]*(.*?)</H1>", re.IGNORECASE)
h2 = re.compile(r".*?<H2>(<a.*?>\s*[\d\.\s]*(.*?)</a>)*[\d\.\s]*(.*?)</H2>", re.IGNORECASE)
h3 = re.compile(r".*?<H3>(<a.*?>\s*[\d\.\s]*(.*?)</a>)*[\d\.\s]*(.*?)</H3>", re.IGNORECASE)
h4 = re.compile(r".*?<H4>(<a.*?>\s*[\d\.\s]*(.*?)</a>)*[\d\.\s]*(.*?)</H4>", re.IGNORECASE)
h5 = re.compile(r".*?<H5>(<a.*?>\s*[\d\.\s]*(.*?)</a>)*[\d\.\s]*(.*?)</H5>", re.IGNORECASE)
data = open(filename).read() # Read data
open(filename+".bak","w").write(data) # Make backup
lines = data.splitlines()
result = [ ] # This is the result of postprocessing the file
index = "<!-- INDEX -->\n<div class=\"sectiontoc\">\n" # index contains the index for adding at the top of the file. Also printed to stdout.
skip = 0
skipspace = 0
for s in lines:
if s == "<!-- INDEX -->":
if not skip:
skip = 1
else:
skip = 0
continue;
if skip:
continue
if not s and skipspace:
continue
if skipspace:
result.append("")
result.append("")
skipspace = 0
m = h1.match(s)
if m:
prevheadingtext = getheadingtext(m, s)
nameindex += 1
headingname = getheadingname(m)
result.append("""<H1><a name="%s">%d %s</a></H1>""" % (headingname,num,prevheadingtext))
result.append("@INDEX@")
section = 0
subsection = 0
subsubsection = 0
subsubsubsection = 0
name = prevheadingtext
skipspace = 1
continue
m = h2.match(s)
if m:
prevheadingtext = getheadingtext(m, s)
nameindex += 1
section += 1
headingname = getheadingname(m)
result.append("""<H2><a name="%s">%d.%d %s</a></H2>""" % (headingname,num,section, prevheadingtext))
if subsubsubsection:
index += "</ul>\n"
if subsubsection:
index += "</ul>\n"
if subsection:
index += "</ul>\n"
if section == 1:
index += "<ul>\n"
index += """<li><a href="#%s">%s</a>\n""" % (headingname,prevheadingtext)
subsection = 0
subsubsection = 0
subsubsubsection = 0
skipspace = 1
continue
m = h3.match(s)
if m:
prevheadingtext = getheadingtext(m, s)
nameindex += 1
subsection += 1
headingname = getheadingname(m)
result.append("""<H3><a name="%s">%d.%d.%d %s</a></H3>""" % (headingname,num,section, subsection, prevheadingtext))
if subsubsubsection:
index += "</ul>\n"
if subsubsection:
index += "</ul>\n"
if subsection == 1:
index += "<ul>\n"
index += """<li><a href="#%s">%s</a>\n""" % (headingname,prevheadingtext)
subsubsection = 0
skipspace = 1
continue
m = h4.match(s)
if m:
prevheadingtext = getheadingtext(m, s)
nameindex += 1
subsubsection += 1
headingname = getheadingname(m)
result.append("""<H4><a name="%s">%d.%d.%d.%d %s</a></H4>""" % (headingname,num,section, subsection, subsubsection, prevheadingtext))
if subsubsubsection:
index += "</ul>\n"
if subsubsection == 1:
index += "<ul>\n"
index += """<li><a href="#%s">%s</a>\n""" % (headingname,prevheadingtext)
subsubsubsection = 0
skipspace = 1
continue
m = h5.match(s)
if m:
prevheadingtext = getheadingtext(m, s)
nameindex += 1
subsubsubsection += 1
headingname = getheadingname(m)
result.append("""<H5><a name="%s">%d.%d.%d.%d.%d %s</a></H5>""" % (headingname,num,section, subsection, subsubsection, subsubsubsection, prevheadingtext))
if subsubsubsection == 1:
index += "<ul>\n"
index += """<li><a href="#%s">%s</a>\n""" % (headingname,prevheadingtext)
skipspace = 1
continue
result.append(s)
if subsubsubsection:
index += "</ul>\n"
if subsubsection:
index += "</ul>\n"
if subsection:
index += "</ul>\n"
if section:
index += "</ul>\n"
index += "</div>\n<!-- INDEX -->\n"
data = "\n".join(result)
data = data.replace("@INDEX@",index) + "\n";
# Write the file back out
open(filename,"w").write(data)
# Print the TOC data to stdout correcting the anchor links for external referencing
index = index.replace("<li><a href=\"#","<li><a href=\"%s#" % filename)
print """<h3><a href="%s#%s">%d %s</a></h3>\n""" % (filename,filenamebase,num,name)
print index

View File

@@ -0,0 +1,39 @@
#!/usr/bin/env python
import sys
import os
chs = open("chapters").readlines()
f = open("Contents.html","w")
print >>f, """
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<HTML>
<HEAD>
<TITLE>SWIG Users Manual</TITLE>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</HEAD>
<BODY BGCOLOR="#ffffff">
<H1><a name="Contents"></a>SWIG Users Manual</H1>
<p>
"""
f.close()
num = 1
for c in chs:
c = c.strip()
print "Processing %s" % c
if c:
os.system("python makechap.py %s %d >> Contents.html" % (c,num))
num += 1
f = open("Contents.html","a")
print >>f, """
</BODY>
</HTML>
"""

View File

@@ -0,0 +1,92 @@
div.sectiontoc {
border-style: dotted;
border-width: 2px;
padding: 2pt;
}
h2 {
padding: 3px;
color: #000000;
border-bottom: 2px
solid #dddddd;
}
h3, h4 {
margin-left: 1em;
}
p,li,table,dl {
margin-left: 2em;
margin-right: 2em;
}
div.indent {
margin-left: 4em;
margin-right: 4em;
}
div.code {
border-style: solid;
border-width: 1px;
padding: 2pt;
margin-left: 4em;
margin-right: 4em;
background-color: #F0FFFF;
font-family: "Courier New", Courier, "Courier 10 Pitch", monospace;
}
div.targetlang {
border-style: solid;
border-width: 1px;
padding: 2pt;
margin-left: 4em;
margin-right: 4em;
background-color: #d7f6bb;
font-family: "Courier New", Courier, "Courier 10 Pitch", monospace;
}
div.shell {
border-style: solid;
border-width: 1px;
padding: 2pt;
margin-left: 4em;
margin-right: 4em;
background-color: #DCDCDC;
font-family: "Courier New", Courier, "Courier 10 Pitch", monospace;
}
div.diagram {
border-style: solid;
border-width: 1px;
padding: 2pt;
margin-left: 4em;
margin-right: 4em;
background-color: #FFEBCD;
font-family: "Courier New", Courier, "Courier 10 Pitch", monospace;
}
ul li p {
margin-left: 0;
margin-right: 0;
}
ol li p {
margin-left: 0;
margin-right: 0;
}
dl dd p {
margin-left: 0;
margin-right: 0;
}
div.indent p {
margin-left: 0;
margin-right: 0;
}
pre, code, tt {
font-family: "Courier New", Courier, "Courier 10 Pitch", monospace;
}
body { font-family: serif; }

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.4 KiB

View File

@@ -0,0 +1,44 @@
#HTMLDOC 1.8.24
-t html -f SWIGDocumentation.html --book --toclevels 4 --no-numbered --toctitle "Table of Contents" --title --titleimage swig16.png --linkcolor #0000ff --linkstyle underline --size Universal --left 0.50in --right 0.50in --top 0.50in --bottom 0.50in --header .t. --footer h.1 --nup 1 --tocheader .t. --tocfooter ..i --portrait --color --no-pscommands --no-xrxcomments --compression=1 --jpeg=0 --fontsize 10.0 --fontspacing 1.2 --headingfont Helvetica --bodyfont Times --headfootsize 10.0 --headfootfont Helvetica --charset iso-8859-1 --links --no-embedfonts --pagemode outline --pagelayout single --firstpage c1 --pageeffect none --pageduration 10 --effectduration 1.0 --no-encryption --permissions all --owner-password "" --user-password "" --browserwidth 680
Sections.html
Preface.html
Introduction.html
Windows.html
Scripting.html
SWIG.html
SWIGPlus.html
CPlusPlus11.html
Preprocessor.html
Library.html
Arguments.html
Typemaps.html
Customization.html
Contract.html
Varargs.html
Warnings.html
Modules.html
CCache.html
Allegrocl.html
Android.html
CSharp.html
Chicken.html
D.html
Go.html
Guile.html
Java.html
Javascript.html
Lisp.html
Lua.html
Modula3.html
Mzscheme.html
Ocaml.html
Octave.html
Perl5.html
Php.html
Pike.html
Python.html
R.html
Ruby.html
Scilab.html
Tcl.html
Extending.html