diff --git a/.gitignore b/.gitignore
new file mode 100644
index 000000000..800ac4669
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,127 @@
+# Compiled Source
+*.o
+*.class
+
+# Editor files and various other junk
+*.sw?
+*.bak
+
+# Local PCRE
+pcre
+*.gz
+
+# C/C++ object files, based on:
+# https://github.com/github/gitignore/blob/master/C.gitignore
+# https://github.com/github/gitignore/blob/master/C%2B%2B.gitignore
+*.slo
+*.lo
+
+# C/C++ dynamic libraries, based on:
+# https://github.com/github/gitignore/blob/master/C.gitignore
+# https://github.com/github/gitignore/blob/master/C%2B%2B.gitignore
+*.dll
+*.so
+*.so.*
+*.dylib
+
+# C/C++ static libraries, based on:
+# https://github.com/github/gitignore/blob/master/C.gitignore
+# https://github.com/github/gitignore/blob/master/C%2B%2B.gitignore
+*.lib
+*.lai
+*.la
+*.a
+
+# C/C++ executables, based on:
+# https://github.com/github/gitignore/blob/master/C.gitignore
+# https://github.com/github/gitignore/blob/master/C%2B%2B.gitignore
+*.exe
+*.out
+*.app
+
+# Generated by autogen.sh
+CCache/autom4te.cache/
+CCache/config.h.in
+CCache/configure
+Source/Include/swigconfig.h.in
+Source/Makefile.in
+Tools/config/compile
+Tools/config/config.guess
+Tools/config/config.sub
+Tools/config/depcomp
+Tools/config/install-sh
+Tools/config/missing
+Tools/config/ylwrap
+aclocal.m4
+autom4te.cache/
+configure
+
+# Generated by ./configure
+CCache/Makefile
+CCache/ccache_swig_config.h
+CCache/config.h
+CCache/config.log
+CCache/config.status
+Examples/Makefile
+Examples/guile/Makefile
+Examples/test-suite/*/Makefile
+Examples/xml/Makefile
+Lib/ocaml/swigp4.ml
+/Makefile
+Source/Include/stamp-h1
+Source/Include/swigconfig.h
+Source/Makefile
+.deps
+config.log
+config.status
+preinst-swig
+swig.spec
+
+# Build Artifacts
+.dirstamp
+CCache/ccache-swig
+Source/CParse/parser.c
+Source/CParse/parser.h
+Source/eswig
+swig
+
+# Generated documentation
+Doc/Manual/CCache.html
+Doc/Manual/SWIGDocumentation.html
+Doc/Manual/SWIGDocumentation.pdf
+Doc/Manual/*.book
+
+# Test Suite Generated Files
+Examples/test-suite/allegrocl/*/
+Examples/test-suite/cffi/*/
+Examples/test-suite/chicken/*/
+Examples/test-suite/clisp/*/
+Examples/test-suite/csharp/*/
+Examples/test-suite/d/*/
+Examples/test-suite/go/*/
+Examples/test-suite/guile/*/
+Examples/test-suite/guilescm/*/
+Examples/test-suite/java/*/
+Examples/test-suite/lua/*/
+Examples/test-suite/mzscheme/*/
+Examples/test-suite/ocaml/*/
+Examples/test-suite/octave/*/
+Examples/test-suite/perl5/*/
+Examples/test-suite/php/*/
+Examples/test-suite/pike/*/
+Examples/test-suite/python/*/
+Examples/test-suite/r/*/
+Examples/test-suite/ruby/*/
+Examples/test-suite/tcl/*/
+Examples/test-suite/uffi/*/
+
+# Python generated files, based on:
+# https://github.com/github/gitignore/blob/master/Python.gitignore
+*.py[cod]
+*/__pycache__/
+/__pycache__/
+
+# C# generated files
+*_runme.exe.mdb
+*_runme.exe
+
diff --git a/.project b/.project
deleted file mode 100644
index 86af75213..000000000
--- a/.project
+++ /dev/null
@@ -1,11 +0,0 @@
-
-
-Each file should include a short abstract, license information and
-a SVN revision tag like this:
+Each file should include a short abstract and license information
+like this:
As a general rule, files start to get unmanageable once they exceed
about 2000 lines. Files larger than this should be broken up into
@@ -379,10 +371,10 @@ making your changes.
These are largely covered in the main documentation in the Extending.html file.
-
There are two types of tags, internal (aka personal) and external.
Internal tags are used by SWIG developers primarily, whereas external
-tags are used when communicating with people w/ anonymous svn access.
+tags are used when communicating with people w/ anonymous git access.
-David M. Beazley
+The DOH types used in the SWIG source code are all typedefined to void.
+Consequently, it is impossible for debuggers to automatically extract any information about DOH objects.
+The easiest approach to debugging and viewing the contents of DOH objects is to make a call into one of the family of SWIG print functions from the debugger.
+The "Debugging Functions" section in SWIG Parse Tree Handling lists them.
+It is sometimes easier to debug by placing a few calls to these functions in code of interest and recompile, especially if your debugger cannot easily make calls into functions within a debugged binary.
+
+The SWIG distribution comes with some additional support for the gdb debugger in the Tools/swig.gdb file.
+Follow the instructions in this file for 'installing'.
+This support file provides an easy way to call into some of the family of SWIG print functions via additional user-defined gdb commands.
+Some usage of the swigprint and locswigprint user-defined commands are demonstrated below.
+
+More often than not, a parse tree node needs to be examined.
+The session below displays the node n in one of the Java language module wrapper functions.
+The swigprint method is used to show the symbol name (symname - a DOH String type) and the node (n - a DOH Hash type).
+
+Note that all the attributes in the Hash are shown, including the 'sym:name' attribute which was assigned to the symname variable.
+
+Hash types can be shown either expanded or collapsed.
+When a Hash is shown expanded, all the attributes are displayed along with their values, otherwise a '.' replaces each attribute when collapsed.
+Therefore a count of the dots provides the number of attributes within an unexpanded Hash.
+Below shows the 'parms' Hash being displayed with the default Hash expansion of 1, then with 2 provided as the second argument to swigprint to expand to two Hash levels in order to view the contents of the collapsed 'nextSibling' Hash.
+
+The same Hash can also be displayed with file and line location information via the locswigprint command.
+
+Tip: Commands in gdb can be shortened with whatever makes them unique and can be command completed with the tab key.
+Thus swigprint can usually be shortened to sw and locswigprint to loc.
+The help for each command can also be obtained within the debugging session, for example, 'help swigprint'.
+
+The sub-section below gives pointers for debugging DOH objects using casts and provides an insight into why it can be hard to debug SWIG without the family of print functions.
-The DOH types are all typedefined to void.
-Consequently, it is impossible for debuggers to extract any information about DOH objects.
-Most debuggers will be able to display useful variable information when an object is cast to the appropriate type.
-Below are some tips for displaying some of the DOH objects.
-Be sure to compile with compiler optimisations turned off before attempting the casts shown in a debugger window else they are unlikely to work.
-Even displaying the underlying string in a String* doesn't work straight off in all debuggers due to the multiple definition of String as a struct and a void.
+
+
Below are a list of common SWIG types.
@@ -1033,34 +1156,56 @@ With each is the cast that can be used in the debugger to extract the underlying
-Please also read the Debugging Functions section in SWIG Parse Tree Handling for the Swig_print_node(), Swig_print_tree() and Swig_print_tags() functions for displaying node contents. It is often easier to place a few calls to these functions in code of interest and recompile than use the debugger.
+The DOH objects are reference counted and use pools for memory allocation.
+The implementation is in memory.c. When there are memory corruption problems,
+various memory allocator tools are normally used to diagnose problems. These can be used
+on SWIG and can be very useful. However, they won't necessarily find use of stale DOH objects,
+that is, DOH objects
+that are used after they have been deleted. This is because the DOH memory allocator
+grabs a chunk of memory from the C memory allocator and manages the usage internally.
+Stale DOH object usage can be checked for by defining DOH_DEBUG_MEMORY_POOLS in
+memory.c. If an attempt to use an object is made after the reference count is
+zero, an assertion is triggered instead of quietly re-using the stale object...
+
+This can be memory intensive as previously used memory in the pool is not re-used so is
+only recommended for diagnosing memory corruption problems.
-David M. Beazley
+The following functions can be used to help debug any SWIG DOH object.
+
+The following functions can be used to help debug SWIG parse trees.
+
void Swig_print_tags(Node *node, String_or_char *prefix)
diff --git a/Doc/Manual/Allegrocl.html b/Doc/Manual/Allegrocl.html
index 5d00c4cd0..283ff7e2c 100644
--- a/Doc/Manual/Allegrocl.html
+++ b/Doc/Manual/Allegrocl.html
@@ -1118,7 +1118,7 @@ namespace BAR {
function that returns an object (or pointer/reference) of C/C++
type X, the wrapping defun (or defmethod) on the Lisp
side will automatically wrap the pointer returned in an instance
- of the apropriate class. This makes it much easier to write and
+ of the appropriate class. This makes it much easier to write and
debug code than if pointers were passed around as a jumble of
integer values.
+This chapter describes SWIG's support of Android.
+
+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 Java chapter applies to generating code for access from Android Java code.
+This chapter contains a few Android specific notes and examples.
+
+The examples require the Android SDK and Android NDK 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):
+
+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.
+
+The following examples are shipped with SWIG under the Examples/android directory and include a Makefile to build and install each example.
+
+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 SwigSimple in a subdirectory called simple using the commands below.
+Adjust the --target id as mentioned earlier in the Examples introduction.
+Managing Projects from the Command Line on the Android developer's site is a useful reference for these steps.
+
+Modify src/org/swig/simple/SwigSimple.java from the default to:
+
+The above simply adds a Run button and scrollable text view as the GUI aspects of the program.
+The associated resources need to be created, modify res/layout/main.xml as follows:
+
+Rebuild the project with your changes:
+
+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 Using hardware devices on the Android developer's site.
+When complete your device should be listed in those attached, something like:
+
+This means you are now ready to install the application...
+
+The newly installed 'SwigSimple' app will be amongst all your other applications on the home screen. Run the app and it will show a Run button text box below it.
+Press the Run button to see the simple text output.
+
+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:
+
+Now that you have a pure Java Android app working, let's add some JNI code generated from SWIG.
+
+First create a jni subdirectory and then create some C source code in jni/example.c:
+
+Create a SWIG interface file for this C code, jni/example.i:
+
+Invoke SWIG as follows:
+
+SWIG generates the following files:
+
+Next we need to create a standard Android NDK build system file jni/Android.mk:
+
+See the Android NDK documentation 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:
+
+Now that the C JNI layer has been built, we can write Java code to call into the this layer.
+Modify the nativeCall method in src/org/swig/simple/SwigSimple.java to call the JNI code as follows and add the static constructor to load the system library containing the compiled JNI C code:
+
+Compile the Java code as usual, uninstall the old version of the app if still installed and re-install the new app:
+
+Run the app again and this time you will see the output pictured below, showing the result of calls into the C code:
+
+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.
+
+First create an Android project called SwigClass in a subdirectory called class.
+The steps below create and build a the JNI C++ app.
+Adjust the --target id as mentioned earlier in the Examples introduction.
+
+Now create a jni subdirectory and then create a C++ header file jni/example.h which defines our
+hierarchy of shape classes:
+
+and create the implementation in the jni/example.cpp file:
+
+Create a SWIG interface file for this C++ code in jni/example.i:
+
+Invoke SWIG as follows, note that the -c++ option is required for C++ code:
+
+SWIG generates the following files:
+
+Next we need to create an Android NDK build system file for compiling the C++ code jni/Android.mk.
+The -frtti compiler flag isn't strictly needed for this example, but is needed for any code that uses C++ RTTI:
+
+A simple invocation of ndk-build will compile the .cpp files and generate a shared object/system library. Output will be similar to:
+
+Now that the C JNI layer has been built, we can write Java code to call into this layer.
+Modify src/org/swig/classexample/SwigClass.java from the default to:
+
+Note the static constructor and the interesting JNI code is in the nativeCall method.
+The remaining code deals with the GUI aspects which are identical to the previous C simple example. Modify res/layout/main.xml to contain the xml for the 'Run' button and scrollable text view:
+
+Compile the Java code as usual, uninstall the old version of the app if installed and re-install the new app:
+
+Run the app to see the result of calling the C++ code from Java:
+
+The Examples/android directory contains further examples which can be run and installed in a similar manner to the previous two examples.
+
+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.
+
+Should the C++ Standard Template Library (STL) be required, an Application.mk file needs to be created
+in the same directory as the Android.mk 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 Application.mk file to make the STLport static library available for use:
+
@@ -57,7 +60,7 @@ PInvoke is part of the ECMA/ISO C# specification.
It is also better suited for robust production environments due to the Managed C++ flaw called the
Mixed DLL Loading Problem.
SWIG C# works equally well on non-Microsoft operating systems such as Linux, Solaris and Apple Mac using
-Mono and Portable.NET.
+Mono and Portable.NET.
@@ -66,7 +69,7 @@ The Microsoft Developer Network (MSDN) h
Monodoc, available from the Mono project, has a very useful section titled Interop with native libraries.
@@ -169,6 +172,14 @@ javadestruct_derived -> csdestruct_derived
Typemap macros: Additional typemaps: Additional typemap attributes:
+The "null" attribute in the "out" typemap can be specified to provide a value for $null to expand into for wrapped functions that return non-void. Normally the default value of 0 is used.
+For example this is needed if you change the return type to void:
+ Feature equivalent names:
Unlike the "javain" typemap, the "csin" typemap does not support the 'pgcpp' attribute as the C# module does not have a premature garbage collection prevention parameter.
The "csin" typemap supports additional optional attributes called 'cshin' and 'terminator'.
+The "csdirectorin" typemap supports additional optional attributes called 'terminator'.
The 'cshin' attribute should contain the parameter type and name whenever a constructor helper function is generated due to the 'pre' or 'post' attributes.
The 'terminator' attribute normally just contains a closing brace for when the 'pre' attribute contains an opening brace, such as when a C# using or fixed block is started.
Note that 'pre', 'post', 'terminator' and 'cshin' attributes are not used for marshalling the property set.
Please see the Date marshalling example and Date marshalling of properties example for further understanding of these "csin" applicable attributes.
+Please see the Date marshalling director example for further understanding of the "csdirectorin" attributes.
+By default SWIG treats void * as any other pointer and hence marshalls it as a type wrapper class called SWIGTYPE_p_void.
+If you want to marshall with the .NET System.IntPtr type instead, there is a simple set of named typemaps called
+void *VOID_INT_PTR that can be used.
+They can be applied like any other named typemaps:
+
@@ -467,7 +512,7 @@ with one of the following three approaches; namely the SWIG C arrays library, P/
pinned arrays.
@@ -504,7 +549,7 @@ example.print_array(c.cast()); // Pass to C
@@ -575,7 +620,8 @@ marshalling for the arrays:
-and intermediate class method
+and intermediary class method
@@ -696,7 +743,8 @@ As a result, we get the following method in the module class:
fixed ( int *swig_ptrTo_sourceArray = sourceArray ) {
fixed ( int *swig_ptrTo_targetArray = targetArray ) {
{
- examplePINVOKE.myArrayCopy((IntPtr)swig_ptrTo_sourceArray, (IntPtr)swig_ptrTo_targetArray, nitems);
+ examplePINVOKE.myArrayCopy((IntPtr)swig_ptrTo_sourceArray, (IntPtr)swig_ptrTo_targetArray,
+ nitems);
}
}
}
@@ -710,7 +758,7 @@ marshalling is the "unsafe" quantifier, which is required because we are handlin
-Also the intermediate class method looks a little different from the default marshalling
+Also the intermediary class method looks a little different from the default marshalling
example - the method is expecting an IntPtr as the parameter type.
@@ -820,7 +868,7 @@ set so should only be used when a C# exception is not created.
@@ -1002,7 +1050,7 @@ method and C# code does not handle pending exceptions via the canthrow attribute
Actually it will issue this warning for any function beginning with SWIG_CSharpSetPendingException.
@@ -1067,7 +1115,7 @@ The managed code generated does check for the pending exception as mentioned ear
-
@@ -1124,7 +1172,7 @@ SWIGEXPORT void SWIGSTDCALL CSharp_evensonly(int jarg1) {
Multiple catch handlers are generated should there be more than one exception specifications declared.
@@ -1258,7 +1306,7 @@ try {
-
@@ -1271,7 +1319,7 @@ The following sections provide information on the C# director implementation and
However, the Java directors section should also be read in order to gain more insight into directors.
@@ -1392,7 +1440,7 @@ CSharpDerived - UIntMethod(123)
-
@@ -1578,7 +1626,7 @@ void SwigDirector_Base::BaseBoolMethod(Base const &b, bool flag) {
-
@@ -1626,7 +1674,42 @@ However, a call from C# to CSharpDefaults.DefaultMethod() will of cours
should pass the call on to CSharpDefaults.DefaultMethod(int)using the C++ default value, as shown above.
+When using multiple modules it is is possible to compile each SWIG generated wrapper
+into a different assembly.
+However, by default the generated code may not compile if
+generated classes in one assembly use generated classes in another assembly.
+The visibility of the
+getCPtr() and pointer constructor generated from the csbody typemaps needs changing.
+The default visibility is internal but it needs to be public for access from a different assembly.
+Just changing 'internal' to 'public' in the typemap achieves this.
+Two macros are available in csharp.swg to make this easier and using them is the preferred approach
+over simply copying the typemaps and modifying as this is forward compatible with any changes in
+the csbody typemap in future versions of SWIG.
+The macros are for the proxy and typewrapper classes and can respectively be used to
+to make the method and constructor public:
+
+Alternatively, instead of exposing these as public, consider
+using the [assembly:InternalsVisibleTo("Name")] attribute available in the .NET framework when you
+know which assemblies these can be exposed to.
+Another approach would be to make these public, but also to hide them from intellisense by using
+the [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] attribute
+if you don't want users to easily stumble upon these so called 'internal workings' of the wrappers.
+
@@ -1758,7 +1841,7 @@ public class Bike : IDisposable {
Note the addReference call.
@@ -1877,7 +1960,7 @@ The 'cscode' typemap simply adds in the specified code into the C# proxy class.
-
@@ -1974,13 +2057,13 @@ The typemaps to achieve this are shown below.
@@ -2189,7 +2274,7 @@ Console.WriteLine("Important date: " + importantDate);
-When SWIG wraps a variable that is a class/struct/union, it is wrapped using a pointer to the type for the reasons given in Stucture data members.
+When SWIG wraps a variable that is a class/struct/union, it is wrapped using a pointer to the type for the reasons given in Structure data members.
The typemap type required is thus CDate *. Given that the previous section already designed CDate * typemaps, we'll use those same typemaps plus the 'csvarin' and 'csvarout' typemaps.
+The 'pre' and 'post' attributes in the "csdirectorin" typemap act like the attributes of the same name in the "csin" typemap.
+For example if we modify the Date marshalling example like this:
+
+and declare %feature ("director") for the Action class, we would have to define additional
+marshalling rules for CDate & parameter. The typemap may look like this:
+
+The generated proxy class code will then contain the following wrapper for calling user-overloaded someCallback():
+
+Pay special attention to the memory management issues, using these attributes.
+
@@ -2362,7 +2508,7 @@ demonstrating that the class contains methods calling both unmanaged code -
The following example is an alternative approach to adding managed code to the generated proxy class.
@@ -2401,7 +2547,7 @@ public class ExtendMe : IDisposable {
diff --git a/Doc/Manual/Chicken.html b/Doc/Manual/Chicken.html
index 006b648d6..4e43b9b90 100644
--- a/Doc/Manual/Chicken.html
+++ b/Doc/Manual/Chicken.html
@@ -8,7 +8,7 @@
@@ -89,7 +89,7 @@
directory for the basic steps to run SWIG CHICKEN.
@@ -122,7 +122,7 @@
object files and linked into your project.
@@ -151,10 +151,10 @@
object files and linked into your project.
@@ -170,7 +170,7 @@
%rename SWIG directive in the SWIG interface file.
@@ -192,7 +192,7 @@
(uses modulename)) CHICKEN Scheme form.
@@ -229,7 +229,7 @@
for info on how to apply the %feature.
@@ -248,7 +248,7 @@
parameters). The return values can then be accessed with The SWIG chicken module has support for exceptions thrown from
@@ -290,7 +290,7 @@
@@ -333,7 +333,7 @@
@@ -354,7 +354,7 @@
We can easily use csc to build a static binary.
-The SVN revision tag should be placed into a static string as shown
-above mangled with the name of the file.
-This adds the revision information to the SWIG executable and
-makes it possible to extract version information from a raw binary
-(sometimes useful in debugging).
-
@@ -137,8 +137,6 @@ a SVN revision tag like this:
* This file defines ...
* ----------------------------------------------------------------------------- */
-static char cvs[] = "$Id$ xxx.c";
-
#include "swig.h"
/* Declarations */
@@ -159,12 +157,6 @@ static int avariable;
11. SVN Tagging Conventions
+11. Git Tagging Conventions
-Use svn tag to declare some set of file revisions as related in some
+Use git tag to declare some set of file revisions as related in some
symbolic way. This eases reference, retrieval and manipulation of these files
later. At the moment (2001/01/16 14:02:53), the conventions are very simple;
let's hope they stay that way!
@@ -390,10 +382,10 @@ let's hope they stay that way!
That's all there is to it. Some example tags:
@@ -402,10 +394,8 @@ That's all there is to it. Some example tags:
diff --git a/Doc/Devel/index.html b/Doc/Devel/index.html
index 55c612ec3..4ddc63a76 100644
--- a/Doc/Devel/index.html
+++ b/Doc/Devel/index.html
@@ -21,6 +21,7 @@ The following documentation describe the internal APIs used by SWIG. These may
diff --git a/Doc/Devel/internals.html b/Doc/Devel/internals.html
index 6ac3947f7..94a82519d 100644
--- a/Doc/Devel/internals.html
+++ b/Doc/Devel/internals.html
@@ -7,11 +7,6 @@
SWIG Internals Manual
-Thien-Thi Nguyen
-
-
-
7. Debugging SWIG
-Warning. Debugging SWIG is for the very patient.
+
+
+
+
+
+Breakpoint 1, JAVA::functionWrapper (this=0x97ea5f0, n=0xb7d2afc8) at Modules/java.cxx:799
+799 String *symname = Getattr(n, "sym:name");
+(gdb) next
+800 SwigType *t = Getattr(n, "type");
+(gdb) swigprint symname
+Shape_x_set
+(gdb) swigprint n
+Hash(0xb7d2afc8) {
+ 'membervariableHandler:view' : variableHandler,
+ 'feature:except' : 0,
+ 'name' : x,
+ 'ismember' : 1,
+ 'sym:symtab' : Hash(0xb7d2aca8) {......},
+ 'nodeType' : cdecl,
+ 'nextSibling' : Hash(0xb7d2af98) {.............},
+ 'kind' : variable,
+ 'variableHandler:feature:immutable' : <Object 'VoidObj' at 0xb7cfa008>,
+ 'sym:name' : Shape_x_set,
+ 'view' : membervariableHandler,
+ 'membervariableHandler:sym:name' : x,
+ 'membervariableHandler:type' : double,
+ 'membervariableHandler:parms' : <Object 'VoidObj' at 0xb7cfa008>,
+ 'parentNode' : Hash(0xb7d2abc8) {..............................},
+ 'feature:java:enum' : typesafe,
+ 'access' : public,
+ 'parms' : Hash(0xb7cb9408) {......},
+ 'wrap:action' : if (arg1) (arg1)->x = arg2;,
+ 'type' : void,
+ 'memberset' : 1,
+ 'sym:overname' : __SWIG_0,
+ 'membervariableHandler:name' : x,
+}
+
+
+
+
+
+(gdb) swigprint 0xb7cb9408
+Hash(0xb7cb9408) {
+ 'name' : self,
+ 'type' : p.Shape,
+ 'self' : 1,
+ 'nextSibling' : Hash(0xb7cb9498) {...},
+ 'hidden' : 1,
+ 'nodeType' : parm,
+}
+(gdb) swigprint 0xb7cb9408 2
+Hash(0xb7cb9408) {
+ 'name' : self,
+ 'type' : p.Shape,
+ 'self' : 1,
+ 'nextSibling' : Hash(0xb7cb9498) {
+ 'name' : x,
+ 'type' : double,
+ 'nodeType' : parm,
+ },
+ 'hidden' : 1,
+ 'nodeType' : parm,
+}
+
+
+
+
+
+(gdb) locswigprint 0xb7cb9408
+example.h:11: [Hash(0xb7cb9408) {
+Hash(0xb7cb9408) {
+ 'name' : self,
+ 'type' : p.Shape,
+ 'self' : 1,
+ 'nextSibling' : Hash(0xb7cb9498) {...},
+ 'hidden' : 1,
+ 'nodeType' : parm,
+}]
+
+7.1 Debugging DOH Types The Hard Way
+
+The DOH types used in SWIG are all typedefined to void and hence the lack of type information for inspecting types within a debugger.
+Most debuggers will however be able to display useful variable information when an object is cast to the appropriate type.
+Getting at the underlying C string within DOH types is cumbersome, but possible with appropriate casts.
+The casts below can be used in a debugger windows, but be sure to compile with compiler optimisations turned off before attempting the casts else they are unlikely to work.
+Even displaying the underlying string in a String * doesn't work straight off in all debuggers due to the multiple definitions of String as a struct and a void.
-(struct String *)((DohBase *)s)->data
+(struct String *)((DohBase *)s)->data
The underlying char * string can be displayed with
-(*(struct String *)(((DohBase *)s)->data)).str
+(*(struct String *)(((DohBase *)s)->data)).str
-(struct String *)((DohBase *)t)->data
+(struct String *)((DohBase *)t)->data
The underlying char * string can be displayed with
-(*(struct String *)(((DohBase *)t)->data)).str
+(*(struct String *)(((DohBase *)t)->data)).str
-(*(struct String *)(((DohBase *)sc)->data)).str
+(*(struct String *)(((DohBase *)sc)->data)).str
or
-(char *)sc
+(char *)sc
will work depending on whether the underlying type is really a String * or char *.
+
+7.2 Debugging DOH memory allocation problems
+
+
+
+
+
+swig: DOH/memory.c:91: DohCheck: Assertion `!DOH_object_already_deleted' failed.
+
+
diff --git a/Doc/Devel/tree.html b/Doc/Devel/tree.html
index 43ad191f6..db3c6fee4 100644
--- a/Doc/Devel/tree.html
+++ b/Doc/Devel/tree.html
@@ -6,13 +6,6 @@
SWIG Parse Tree Handling
-
-
-dave-swig@dabeaz.com
-December, 2006
-
-
Introduction
@@ -210,7 +203,33 @@ This function restores a node to the state it was in prior to the last Swig_
Debugging Functions
-The following functions are used to help debug SWIG parse trees.
+
+Prints to stdout a string representation of any DOH type.
+The number of nested Hash types to expand is set by count (default is 1 if count<0). See Swig_set_max_hash_expand() to change default.
+
+
+void Swig_print_with_location(DOH *object, int count = -1)
+
+
+
+
+Prints to stdout a string representation of any DOH type, within [] brackets
+for Hash and List types, prefixed by line and file information.
+The number of nested Hash types to expand is set by count (default is 1 if count<0). See Swig_set_max_hash_expand() to change default.
+
+
+
+
+
+18 SWIG and Android
+
+18.1 Overview
+
+
+18.2 Android examples
+
+
+18.2.1 Examples introduction
+
+
+
+$ 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 AnrdoidApps
+
+
+$ android list targets
+
+18.2.2 Simple C example
+
+
+
+$ android create project --target 1 --name SwigSimple --path ./simple --activity SwigSimple --package org.swig.simple
+$ cd simple
+$ ant debug
+
+
+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
+ }
+}
+
+
+<?xml version="1.0" encoding="utf-8"?>
+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+ android:orientation="vertical"
+ android:layout_width="fill_parent"
+ android:layout_height="fill_parent"
+ >
+<Button
+ android:id="@+id/RunButton"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:text="Run..."
+ android:onClick="onRunButtonClick"
+ />
+<ScrollView
+ android:id="@+id/Scroller"
+ android:layout_width="fill_parent"
+ android:layout_height="fill_parent"
+ >
+<TextView
+ android:id="@+id/OutputText"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ />
+</ScrollView>
+</LinearLayout>
+
+
+$ ant debug
+
+
+$ adb devices
+List of devices attached
+A32-6DBE0001-9FF80000-015D62C3-02018028 device
+
+
+$ adb install bin/SwigSimple-debug.apk
+95 KB/s (4834 bytes in 0.049s)
+ pkg: /data/local/tmp/SwigSimple-debug.apk
+Success
+
+
+$ adb uninstall org.swig.simple
+Success
+
+
+/* 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 > 0) {
+ g = x;
+ x = y % x;
+ y = g;
+ }
+ return g;
+}
+
+
+/* File : example.i */
+%module example
+
+%inline %{
+extern int gcd(int x, int y);
+extern double Foo;
+%}
+
+
+$ swig -java -package org.swig.simple -outdir src/org/swig/simple -o jni/example_wrap.c jni/example.i
+
+
+
+
+
+# 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)
+
+
+$ ndk-build
+Compile thumb : example <= example_wrap.c
+Compile thumb : example <= example.c
+SharedLibrary : libexample.so
+Install : libexample.so => libs/armeabi/libexample.so
+
+
+ /** 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");
+ }
+
+
+$ ant debug
+$ adb uninstall org.swig.simple
+$ adb install bin/SwigSimple-debug.apk
+
+
18.2.3 C++ class example
+
+
+
+$ android create project --target 1 --name SwigClass --path ./class --activity SwigClass --package org.swig.classexample
+$ cd class
+
+
+/* File : example.h */
+
+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);
+};
+
+
+/* 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(void) {
+ return M_PI*radius*radius;
+}
+
+double Circle::perimeter(void) {
+ return 2*M_PI*radius;
+}
+
+double Square::area(void) {
+ return width*width;
+}
+
+double Square::perimeter(void) {
+ return 4*width;
+}
+
+
+/* File : example.i */
+%module example
+
+%{
+#include "example.h"
+%}
+
+/* Let's just grab the original header file here */
+%include "example.h"
+
+
+$ swig -c++ -java -package org.swig.classexample -outdir src/org/swig/classexample -o jni/example_wrap.cpp jni/example.i
+
+
+
+
+
+# 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)
+
+
+$ ndk-build
+Compile++ thumb : example <= example_wrap.cpp
+Compile++ thumb : example <= example.cpp
+StaticLibrary : libstdc++.a
+SharedLibrary : libexample.so
+Install : libexample.so => libs/armeabi/libexample.so
+
+
+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<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");
+ }
+}
+
+
+<?xml version="1.0" encoding="utf-8"?>
+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+ android:orientation="vertical"
+ android:layout_width="fill_parent"
+ android:layout_height="fill_parent"
+ >
+<Button
+ android:id="@+id/RunButton"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:text="Run..."
+ android:onClick="onRunButtonClick"
+ />
+<ScrollView
+ android:id="@+id/Scroller"
+ android:layout_width="fill_parent"
+ android:layout_height="fill_parent"
+ >
+<TextView
+ android:id="@+id/OutputText"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ />
+</ScrollView>
+</LinearLayout>
+
+
+$ ant debug
+$ adb uninstall org.swig.classexample
+$ adb install bin/SwigClass-debug.apk
+
+
18.2.4 Other examples
+
+
+18.3 C++ STL
+
+
+
+# File: Application.mk
+APP_STL := gnustl_static
+
+18 SWIG and C#
+19 SWIG and C#
+
18.1 Introduction
+19.1 Introduction
18.2 Differences to the Java module
+19.2 Differences to the Java module
+SWIG_JAVABODY_PROXY -> SWIG_CSBODY_PROXY
+SWIG_JAVABODY_TYPEWRAPPER -> SWIG_CSBODY_TYPEWRAPPER
+
+%typemap(ctype) Status "void"
+%typemap(out, null="") Status { ... }
+
@@ -217,10 +242,12 @@ $jnicall -> $imcall
18.3 C# Arrays
+19.3 Void pointers
+
+
+
+%apply void *VOID_INT_PTR { void * }
+void * f(void *v);
+
+19.4 C# Arrays
18.3.1 The SWIG C arrays library
+19.4.1 The SWIG C arrays library
18.3.2 Managed arrays using P/Invoke default array marshalling
+19.4.2 Managed arrays using P/Invoke default array marshalling
[DllImport("example", EntryPoint="CSharp_myArrayCopy")]
public static extern void myArrayCopy([In, MarshalAs(UnmanagedType.LPArray)]int[] jarg1,
- [Out, MarshalAs(UnmanagedType.LPArray)]int[] jarg2, int jarg3);
+ [Out, MarshalAs(UnmanagedType.LPArray)]int[] jarg2,
+ int jarg3);
[DllImport("example", EntryPoint="CSharp_myArraySwap")]
public static extern void myArraySwap([In, Out, MarshalAs(UnmanagedType.LPArray)]int[] jarg1,
- [In, Out, MarshalAs(UnmanagedType.LPArray)]int[] jarg2, int jarg3);
+ [In, Out, MarshalAs(UnmanagedType.LPArray)]int[] jarg2,
+ int jarg3);
18.3.3 Managed arrays using pinning
+19.4.3 Managed arrays using pinning
18.4 C# Exceptions
+19.5 C# Exceptions
18.4.1 C# exception example using "check" typemap
+19.5.1 C# exception example using "check" typemap
18.4.2 C# exception example using %exception
+19.5.2 C# exception example using %exception
18.4.3 C# exception example using exception specifications
+19.5.3 C# exception example using exception specifications
18.4.4 Custom C# ApplicationException example
+19.5.4 Custom C# ApplicationException example
18.5 C# Directors
+19.6 C# Directors
18.5.1 Directors example
+19.6.1 Directors example
18.5.2 Directors implementation
+19.6.2 Directors implementation
18.5.3 Director caveats
+19.6.3 Director caveats
18.6 C# Typemap examples
+19.7 Multiples modules
+
+
+
+ SWIG_CSBODY_PROXY(public, public, SWIGTYPE)
+ SWIG_CSBODY_TYPEWRAPPER(public, public, public, SWIGTYPE)
+
+19.8 C# Typemap examples
This section includes a few examples of typemaps. For more examples, you
@@ -1634,7 +1717,7 @@ might look at the files "csharp.swg" and "typemaps.i" in
the SWIG library.
-18.6.1 Memory management when returning references to member variables
+19.8.1 Memory management when returning references to member variables
18.6.2 Memory management for objects passed to the C++ layer
+19.8.2 Memory management for objects passed to the C++ layer
18.6.3 Date marshalling using the csin typemap and associated attributes
+19.8.3 Date marshalling using the csin typemap and associated attributes
-%typemap(cstype) const CDate& "System.DateTime"
+%typemap(cstype) const CDate & "System.DateTime"
%typemap(csin,
pre=" CDate temp$csinput = new CDate($csinput.Year, $csinput.Month, $csinput.Day);"
) const CDate &
"$csclassname.getCPtr(temp$csinput)"
-%typemap(cstype) CDate& "out System.DateTime"
+%typemap(cstype) CDate & "out System.DateTime"
%typemap(csin,
pre=" CDate temp$csinput = new CDate();",
post=" $csinput = new System.DateTime(temp$csinput.getYear(),"
@@ -2109,7 +2192,8 @@ public class example {
try {
examplePINVOKE.addYears(CDate.getCPtr(temppDate), years);
} finally {
- pDate = new System.DateTime(temppDate.getYear(), temppDate.getMonth(), temppDate.getDay(), 0, 0, 0);
+ pDate = new System.DateTime(temppDate.getYear(), temppDate.getMonth(), temppDate.getDay(),
+ 0, 0, 0);
}
}
...
@@ -2126,13 +2210,13 @@ The subtractYears method is nearly identical to the above addYears<
%typemap(csin,
- pre=" using (CDate temp$csinput = new CDate($csinput.Year, $csinput.Month, $csinput.Day)) {",
- post=" $csinput = new System.DateTime(temp$csinput.getYear(),"
- " temp$csinput.getMonth(), temp$csinput.getDay(), 0, 0, 0);",
- terminator=" } // terminate temp$csinput using block",
- cshin="ref $csinput"
- ) CDate *
- "$csclassname.getCPtr(temp$csinput)"
+ pre=" using (CDate temp$csinput = new CDate($csinput.Year, $csinput.Month, $csinput.Day)) {",
+ post=" $csinput = new System.DateTime(temp$csinput.getYear(),"
+ " temp$csinput.getMonth(), temp$csinput.getDay(), 0, 0, 0);",
+ terminator=" } // terminate temp$csinput using block",
+ cshin="ref $csinput"
+ ) CDate *
+ "$csclassname.getCPtr(temp$csinput)"
void subtractYears(CDate *pDate, int years) {
*pDate = CDate(pDate->getYear() - years, pDate->getMonth(), pDate->getDay());
@@ -2152,7 +2236,8 @@ public class example {
try {
examplePINVOKE.subtractYears(CDate.getCPtr(temppDate), years);
} finally {
- pDate = new System.DateTime(temppDate.getYear(), temppDate.getMonth(), temppDate.getDay(), 0, 0, 0);
+ pDate = new System.DateTime(temppDate.getYear(), temppDate.getMonth(), temppDate.getDay(),
+ 0, 0, 0);
}
} // terminate temppDate using block
}
@@ -2161,7 +2246,7 @@ public class example {
18.6.4 A date example demonstrating marshalling of C# properties
+19.8.4 A date example demonstrating marshalling of C# properties
19.8.5 Date example demonstrating the 'pre' and 'post' typemap attributes for directors
-18.6.5 Turning wrapped classes into partial classes
+
+
+class CDate {
+ ...
+ void setYear(int);
+ void setMonth(int);
+ void setDay(int);
+};
+struct Action {
+ virtual void someCallback(CDate &date);
+ virtual ~Action();
+ ...
+};
+
+%typemap(csdirectorin,
+ pre="System.DateTime temp$iminput = new System.DateTime();",
+ post="CDate temp2$iminput = new CDate($iminput, false);\n"
+ "temp2$iminput.setYear(tempdate.Year);\n"
+ "temp2$iminput.setMonth(tempdate.Month);\n"
+ "temp2$iminput.setDay(tempdate.Day);"
+ ) CDate &date "out temp$iminput"
+
+...
+ private void SwigDirectorsomeCallback(IntPtr date) {
+ System.DateTime tempdate = new System.DateTime();
+ try {
+ someCallback(out tempdate);
+ } finally {
+ // we create a managed wrapper around the existing C reference, just for convenience
+ CDate temp2date = new CDate(date, false);
+ temp2date.setYear(tempdate.Year);
+ temp2date.setMonth(tempdate.Month);
+ temp2date.setDay(tempdate.Day);
+ }
+ }
+...
+19.8.6 Turning wrapped classes into partial classes
18.6.6 Extending proxy classes with additional C# code
+19.8.7 Extending proxy classes with additional C# code
18.6.7 Underlying type for enums
+19.8.8 Underlying type for enums
19 SWIG and Chicken
+20 SWIG and Chicken
@@ -72,7 +72,7 @@
-
19.1 Preliminaries
+20.1 Preliminaries
19.1.1 Running SWIG in C mode
+20.1.1 Running SWIG in C mode
19.1.2 Running SWIG in C++ mode
+20.1.2 Running SWIG in C++ mode
19.2 Code Generation
+20.2 Code Generation
-19.2.1 Naming Conventions
+20.2.1 Naming Conventions
19.2.2 Modules
+20.2.2 Modules
19.2.3 Constants and Variables
+20.2.3 Constants and Variables
19.2.4 Functions
+20.2.4 Functions
(call-with-values).
19.2.5 Exceptions
+20.2.5 Exceptions
19.3 TinyCLOS
+20.3 TinyCLOS
19.4 Linkage
+20.4 Linkage
19.4.1 Static binary or shared library linked at compile time
+20.4.1 Static binary or shared library linked at compile time
Building a shared library like in the above section only works if the library @@ -453,7 +453,7 @@ distributed and used by anyone, even if SWIG is not installed.
See the Examples/chicken/egg directory in the SWIG source for an example that builds two eggs, one using the first method and one using the second method.
-Linking together multiple modules that share type information using the %import
@@ -477,7 +477,7 @@ with (declare (uses ...)).
To create an extension library or an egg, just create a module_load.scm file that (declare (uses ...))
all the modules.
@@ -486,7 +486,7 @@ all the modules.
Lib/chicken/chicken.swg.
-@@ -519,7 +519,7 @@ all the modules.
type. flags is either zero or SWIG_POINTER_DISOWN (see below). -If the owner flag passed to SWIG_NewPointerObj is 1, NewPointerObj will add a
@@ -550,7 +550,7 @@ all the modules.
In Chicken versions equal to or below 1.92, TinyCLOS has a limitation such that generic methods do not properly work on methods diff --git a/Doc/Manual/Contents.html b/Doc/Manual/Contents.html index 66bf41264..42e135140 100644 --- a/Doc/Manual/Contents.html +++ b/Doc/Manual/Contents.html @@ -5,7 +5,7 @@
@@ -152,6 +152,12 @@
@@ -704,6 +719,11 @@ depends on the target language on implementing the 'disown' mechanism properly.
++The use of %newobject is also integrated with reference counting and is covered in the +C++ reference counted objects section. +
+Compatibility note: Previous versions of SWIG had a special %new directive. However, unlike %newobject, it only applied to the next declaration. For example: diff --git a/Doc/Manual/D.html b/Doc/Manual/D.html new file mode 100644 index 000000000..43fa69196 --- /dev/null +++ b/Doc/Manual/D.html @@ -0,0 +1,454 @@ + + +
+From the D Programming Language web site: 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. As such, it is not very surprising that D is able to directly interface with C libraries. Why would a SWIG module for D be needed then in the first place?
+ +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 \0-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.
+ +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 extern(C++) has been added to D2, the support is still very limited, and a custom wrapper layer is still required in many cases.
+ +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 C# (and also on Java, since the C# module was in turn forked from it).
+ + +To activate the D module, pass the -d 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:
+ +By default, SWIG generates code for D1/Tango. Use the -d2 flag to target D2/Phobos instead.
+By default, SWIG generates two D modules: the proxy module, named like the source module (either specified via the %module directive or via the module command line switch), which contains all the proxy classes, functions, enums, etc., and the intermediary module (named like the proxy module, but suffixed with _im), which contains all the extern(C) function declarations and other private parts only used internally by the proxy module.
+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.
+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.
+The code SWIG generates to dynamically load the C/C++ wrapper layer looks for a library called $module_wrap by default. With this switch, you can override the name of the file the wrapper code loads at runtime (the lib prefix and the suffix for shared libraries are appended automatically, depending on the OS).
+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.
+If you already know the SWIG C# module, you might find the following name comparison table useful:
+ ++ ctype <-> ctype + imtype <-> imtype + cstype <-> dtype + csin <-> din + csout <-> dout + csdirectorin <-> ddirectorin + csdirectorout <-> ddirectorout + csinterfaces <-> dinterfaces + csinterfaces_derived <-> dinterfaces_derived + csbase <-> dbase + csclassmodifiers <-> dclassmodifiers + cscode <-> dcode + csimports <-> dimports + csbody <-> dbody + csfinalize <-> ddestructor + csdestruct <-> ddispose + csdestruct_derived <-> ddispose_derived +
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.
+ +The ctype typemap is used to determine the types to use in the C wrapper functions. The types from the imtype typemap are used in the extern(C) declarations of these functions in the intermediary D module. The dtype typemap contains the D types used in the D proxy module/class.
+ + +Used for converting between the types for C/C++ and D when generating the code for the wrapper functions (on the C++ side).
+ +The code from the in typemap is used to convert arguments to the C wrapper function to the type used in the wrapped code (ctype->original C++ type), the out typemap is utilized to convert values from the wrapped code to wrapper function return types (original C++ type->ctype).
+ +The directorin typemap is used to convert parameters to the type used in the D director callback function, its return value is processed by directorout (see below).
+ + +Typemaps for code generation in D proxy and type wrapper classes.
+ +The din 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 $dinput macro is replaced). To inject further parameter processing code before or after the call to the intermediary layer, the pre, post and terminator attributes can be used (please refer to the C# date marshalling example for more information on these).
+ +The dout 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 $excode special variable in dout typemaps is replaced by the excode typemap attribute code if the method can throw any exceptions from unmanaged code, otherwise by nothing (the $imcall and $owner macros are replaced).
+ +The code from the ddirectorin and ddirectorout 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 ddirectorin, the proxy class method return value is converted to the type the C++ code expects via the ddirectorout typemap (the $dcall and $winput macros are replaced).
+ +The full chain of type conversions when a director callback is invoked looks like this:
+ ++ type CPPClass::method(type a) + ↑ ↓ + <directorout> <directorin> + ↑ ↓ + ctype methodCallback(ctype a) C++ + ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: + imtype methodCallback(imtype a) D + ↑ ↓ + <ddirectorout> <ddirectorin> + ↑ ↓ + dtype DClass.method(dtype a)
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).
+ + +These typemaps are used for generating the skeleton of proxy classes for C++ types.
+ +By overriding dbase, dinterfaces or dinterfaces_derived, the inheritance chain of the generated proxy class for a type can be modified. dclassmodifiers allows you to add any custom modifiers around the class keyword.
+ +Using dcode and dimports, 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.
+ +dconstructor, ddestructor, ddispose and ddispose_derived are used to generate the class constructor, destructor and dispose() method, respectively. The auxiliary code for handling the pointer to the C++ object is stored in dbody and dbody_derived. You can override them for specific types.
+ + +The standard SWIG special variables are available for use within typemaps as described in the Typemaps documentation, for example $1, $input, $result etc.
+ +When generating D wrappers, a few additional macros are available:
+This special variable works similar to $n_type 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, SWIGTYPE_p_p_SomeCppClass is generated when wrapping SomeCppClass **.
+There are two other variants available, $&dclassname and $*dclassname. The former adds a level of indirection, while the latter removes one. For instance, when wrapping Foo **, $*dclassname would be replaced by the proxy class name corresponding to Foo *.
+This special variable expands the fully qualified C++ class into the package name, if used by the nspace feature, and the proxy class name, mangled for use as a function name. For example, Namespace1::Namespace2::Klass is expanded into Namespace1_Namespace2_Klass_.
+This special variable might be useful for calling certain functions in the wrapper layer (e.g. upcast wrappers) which are mangled like this.
+In code inserted into the generated C/C++ wrapper functions, this variable is replaced by either 0 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 (return $null;).
This variable is used in din typemaps and is replaced by the expression which is to be passed to C/C++.
+For example, this input
+
+%typemap(din) SomeClass * "SomeClass.getCPointer($dinput)"
+
+%inline %{
+ class SomeClass {};
+ void foo(SomeClass *arg);
+%}leads to the following D proxy code being generated:
+
+void foo(SomeClass arg) {
+ example_im.foo(SomeClass.getCPointer(arg));
+}These variables are used in dout typemaps. $imcall contains the call to the intermediary module which provides the value to be used, and $owner 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 %newobject).
+Consider the following example:
+
+%typemap(dout) SomeClass * {
+ return new SomeClass($imcall, $owner);
+}
+
+%inline %{
+ class SomeClass;
+ SomeClass *foo();
+
+ %newobject bar();
+ SomeClass *bar();
+%}The code generated for foo() and bar() looks like this:
+
+SomeClass foo() {
+ return new SomeClass(example_im.foo(), false);
+}
+
+SomeClass bar() {
+ return new SomeClass(example_im.bar(), true);
+}
+These variables are used in the director-specific typemaps ddirectorin and ddirectorout. They are more or less the reverse of the $imcall and $dinput macros: $dcall contains the invocation of the D proxy method of which the return value is to be passed back to C++, $winput contains the parameter value from C++.
This variable is used in dout and dconstructor typemaps and is filled with the contents of the excode typemap attribute if an exception could be thrown from the C++ side. See the C# documentation for details.
Currently for internal use only, it contains the D name of the C++ base class (if any) inside proxy classes.
This macro is only valid inside the dconstructor typemap and contains the value of the dconstructor typemap attribute if the currently wrapped class has directors enabled.
+This is how the default dconstructor typemap looks like (you usually do not want to specify a custom one):
+
+%typemap(dconstructor, excode=SWIGEXCODE,
+ directorconnect="\n swigDirectorConnect();") SWIGTYPE {
+ this($imcall, true);$excode$directorconnect
+}
+This macro is used in the dimports typemap if a dependency on another D type generated by SWIG is added by a custom typemap.
+Consider the following code snippet:
++%typemap(dinterfaces) SomeClass "AnInterface, AnotherInterface"; +
This causes SWIG to add AnInterface and AnotherInterface to the base class list of SomeClass:
+
+class SomeClass : AnInterface, AnotherInterface {
+ ...
+}
+For this to work, AnInterface and AnotherInterface 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 dimports typemap. Additionally, the import statement depends on the package SWIG is configured to emit the modules to.
+The $importtype macro helps you to elegantly solve this problem:
+
+%typemap(dimports) RemoteMpe %{
+$importtype(AnInterface)
+$importtype(AnotherInterface)
+%}
+If SWIG is in split proxy mode, it expands to an import statement for the specified type, to nothing if not.
+Expands to the name of the main proxy D module.
Contains the fully qualified name of the intermediary D module.
The D module defines a number of directives which modify the SWIG features set globally or for a specific declaration:
+ + +Out of the box, SWIG generates accessor methods for C #defines and C++ constants. The %dmanifestconst directive enables wrapping these constants as D manifest constants (const in D1, enum in D2).
+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 %dconstvalue directive, passing the new value as parameter.
+For enums, again %dconstvalue can be used to override the value of an enum item if the initializer should not compile in D.
+This directive can be used to override the modifiers for a proxy function. For instance, you could make a public C++ member function private in D like this:
+
+%dmethodmodifiers A::foo "private";
+
+%inline %{
+struct A {
+ void foo();
+};
+%}
+There are a few SWIG pragmas specific to the D module, which you can use to influence the D code SWIG generates:
+ +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.
Additional code to be emitted to the imports section of the intermediary D module (the $importtype macro can be used here). You probably want to use this in conjunction with the imdmodulecode pragma.
Just like proxydmodulecode, the argument is copied to the proxy D module (if SWIG is in split proxy mode and/or the nspace feature is used, it is emitted to the main proxy D module only).
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 all proxy modules if in split proxy mode), you can use the globalproxyimports directive.
+For example:
++%typemap(din) char[] "($dinput ? tango.stdc.stringz.toStringz($dinput) : null)" +%pragma(d) globalproxyimports = "static import tango.stdc.stringz;"; +
The D code for loading the wrapper library (it is copied to the intermediary D module). The $wrapperloaderbindcode variable is replaced by the list of commands for binding the functions from the wrapper library to the symbols in the intermediary D module.
+Each time this pragma is specified, the previous value is overwritten.
+The D command to use for binding the wrapper functions from the C/C++ library to the symbols in the intermediary D module. The $function variable contains the name of the D function in the wrap module, the $symbol variable is replaced by the name of the symbol in the library.
+Each time this pragma is specified, the previous value is overwritten.
+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.
+ +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 throw(...) exception specification).
+ +As this feature is implemented in exactly the same way it is for C#, please see the C# documentation for a more detailed explanation.
+ + +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++.
+ +There is no D specific documentation yet, but the way the feature is implemented is very similar to how it is done in Java and C#. +
+ + +By default, SWIG flattens all C++ namespaces into a single target language namespace, but as for Java and C#, the nspace 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, free variables and functions are not supported yet; currently, they are all allows written to the main proxy D module.
+ + +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 primitive type below.
+ +Central to this custom pointer handling scheme are two typemap attributes: the cprimitive attribute on the dtype typemap and the nativepointer attribute on all the typemaps which influence the D side of the code (dtype, din, dout, ...). When a D typemap is looked up, the following happens behind the scenes:
+ +First, the matching typemap is determined by the usual typemap lookup rules. Then, it is checked if the result has the nativepointer attribute set. If it is present, it means that its value should replace the typemap value if and only if 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.
+ +To determine if a type should be considered primitive, the cprimitive attribute on its dtype attribute is used. For example, the dtype typemap for float has cprimitive="1", so the code from the nativepointer attribute is taken into account e.g. for float ** or the function pointer float (*)(float *).
+ + +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:
+ +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.
+ +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 && and ||, but also !, and prefix increment/decrement operators in D1 resp. their postfix pendants in D2.
+ +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, [], in combination with assignments - while operator [] in C++ simply returns a reference which is then written to, D resorts to a separate opIndexAssign method -, or implicit casting (which was introduced in D2 via alias this). Despite the lack of automatic support, manually handling these cases should be perfectly possible.
+ + +As with any other language, the SWIG test-suite can be built for D using the *-d-test-suite targets of the top-level Makefile. By default, D1 is targeted, to build it with D2, use the optional D_VERSION variable, e.g. make check-d-test-suite D_VERSION=2.
+ +Note: If you want to use GDC on Linux or another platform which requires you to link libdl for dynamically loading the shared library, you might have to add -ldl manually to the d_compile target in Examples/Makefile, because GDC does not currently honor the pragma(lib,...) statement.
+ + +There are no D-specific typemap examples yet. However, with the above name comparison table, you should be able to get an idea what can be done by looking at the corresponding C# section.
+ + + +There are a couple of features which are not implemented yet, but would be very useful and might be added in the near future:
+ +Some generated code might also be a bit rough around the edges, particularly in the following areas:
+ +@@ -91,7 +91,7 @@ Also, this chapter is not meant to be a hand-holding tutorial. As a starting po you should probably look at one of SWIG's existing modules.
-@@ -121,7 +121,7 @@ obvious, but almost all SWIG directives as well as the low-level generation of wrapper code are driven by C++ datatypes.
-@@ -158,7 +158,7 @@ role in making the system work. For example, both typemaps and declaration anno based on pattern matching and interact heavily with the underlying type system.
-@@ -203,7 +203,7 @@ latter stage of compilation. The next few sections briefly describe some of these stages.
-@@ -284,7 +284,7 @@ been expanded as well as everything else that goes into the low-level construction of the wrapper code.
-@@ -385,7 +385,7 @@ returning a foo and taking types a and b as arguments).
-@@ -640,7 +640,7 @@ $ swig -c++ -python -debug-module 4 example.i
@@ -659,7 +659,7 @@ that matches the name of the target language. For example, python:foo perl:foo.
-@@ -750,7 +750,7 @@ example.i:5. Previous declaration is foo_i(int )
@@ -806,7 +806,7 @@ For example, the exception code above is simply stored without any modifications.
-@@ -928,7 +928,7 @@ public : The role of these functions is described shortly.
-@@ -941,7 +941,7 @@ internal data structures, it may be useful to keep XML in the back of your mind as a model.
-@@ -987,7 +987,7 @@ typedef Hash Typetab; -
@@ -1128,7 +1128,7 @@ Returns the number of replacements made (if any). -
@@ -1205,7 +1205,7 @@ Returns the list of hash table keys. -
@@ -1294,7 +1294,7 @@ If t is not a standard object, it is assumed to be a char * and is used to create a String object. -
@@ -1782,7 +1782,7 @@ the attribute is optional. Swig_restore() must always be called after function. -
@@ -1791,7 +1791,7 @@ pointers, references, and pointers to members. A detailed discussion of type theory is impossible here. However, let's cover the highlights.
-@@ -1892,7 +1892,7 @@ make the final type, the two parts are just joined together using string concatenation.
-@@ -2061,7 +2061,7 @@ Returns the prefix of a type. For example, if ty is ty is unmodified. -
@@ -2148,7 +2148,7 @@ Checks if ty is a varargs type. Checks if ty is a templatized type. -
@@ -2250,7 +2250,7 @@ Fully reduces ty according to typedef rules. Resulting datatype will consist only of primitive typenames. -
@@ -2287,7 +2287,7 @@ Literal y; // type = 'Literal', ltype='p.char' -
@@ -2349,7 +2349,7 @@ SWIG, but is most commonly associated with type-descriptor objects that appear in wrappers (e.g., SWIGTYPE_p_double). -
@@ -2448,7 +2448,7 @@ included. Used to emit prototypes. Returns the number of required (non-optional) arguments in p. -
@@ -2463,7 +2463,7 @@ describes the creation of a minimal Python module. You should be able to extra this to other languages.
-@@ -2473,7 +2473,7 @@ the parsing of command line options, all aspects of code generation are controll different methods of the Language that must be defined by your module.
-@@ -2581,7 +2581,7 @@ that activates your module. For example, swig -python foo.i. The messages from your new module should appear.
-@@ -2640,7 +2640,7 @@ to mark the option as valid. If you forget to do this, SWIG will terminate wit unrecognized command line option error.
-@@ -2689,7 +2689,7 @@ an implementation file python.cxx and a configuration file python.swg.
-@@ -2747,22 +2747,23 @@ int Python::top(Node *n) { -
-Within SWIG wrappers, there are four main sections. These are (in order) +Within SWIG wrappers, there are five main sections. These are (in order)
Different parts of the SWIG code will fill different sections, @@ -2895,7 +2896,7 @@ functionWrapper : void Shape_y_set(Shape *self,double y) -
virtual int functionWrapper(Node *n) {
- /* get useful atributes */
+ /* get useful attributes */
String *name = Getattr(n,"sym:name");
SwigType *type = Getattr(n,"type");
ParmList *parms = Getattr(n,"parms");
@@ -3049,7 +3050,7 @@ but without the typemaps, there is still work to do.
-36.10.8 Configuration files
+38.10.8 Configuration files
@@ -3193,7 +3194,7 @@ politely displays the ignoring language message.
-36.10.9 Runtime support
+38.10.9 Runtime support
@@ -3202,7 +3203,7 @@ Discuss the kinds of functions typically needed for SWIG runtime support (e.g.
the SWIG files that implement those functions.
-36.10.10 Standard library files
+38.10.10 Standard library files
@@ -3221,7 +3222,7 @@ The following are the minimum that are usually supported:
Please copy these and modify for any new language.
-36.10.11 User examples
+38.10.11 User examples
@@ -3250,7 +3251,7 @@ during this process, see the section on .
-36.10.12 Test driven development and the test-suite
+38.10.12 Test driven development and the test-suite
@@ -3309,7 +3310,7 @@ It is therefore essential that the runtime tests are written in a manner that di
but error/exception out with an error message on stderr on failure.
-36.10.12.1 Running the test-suite
+38.10.12.1 Running the test-suite
@@ -3477,7 +3478,25 @@ A debugger can also be invoked easily on an individual test, for example gdb:
make ret_by_value.ctest RUNTOOL="gdb --args"
+SWIG reads the SWIG_FEATURES environment variable to obtain options in addition to those passed on the command line. +This is particularly useful as the entire test-suite or a particular testcase can be run customized by using additional +arguments, for example the -O optimization flag can be added in, as shown below for the bash shell: +
+ ++env SWIG_FEATURES=-O make check-python-test-suite +
+The syntax for setting environment variables varies from one shell to the next, but it also works as shown in the example below, where some typemap debugging is added in: +
+ ++make ret_by_value.ctest SWIG_FEATURES="-debug-tmsearch" +
@@ -3509,7 +3528,7 @@ Some topics that you'll want to be sure to address include: if available. -
@@ -3517,7 +3536,7 @@ If you wish for a new language module to be distributed with SWIG, which we encourage for all popular languages, there are a few requirements. While we appreciate that getting all aspects of a new language working won't happen at the outset, there are a set of minimum requirements before -a module can be committed into the SVN repository for distribution with future +a module can be committed into the official Github repository for distribution with future versions of SWIG. The following are really a summary of this whole section with details being outlined earlier on.
@@ -3559,14 +3578,14 @@ details being outlined earlier on.-Once accepted into SVN, development efforts should concentrate on +Once accepted into the official Git repository, development efforts should concentrate on getting the entire test-suite to work with plenty of runtime tests. Runtime tests should be for existing testcases and new test cases should be added should there be an area not already covered by the existing tests.
-@@ -3590,7 +3609,7 @@ The generated C/C++ code should also follow this style as close as possible. How should be avoided as unlike the SWIG developers, users will never have consistent tab settings.
-@@ -3609,13 +3628,15 @@ There are various command line options which can aid debugging a SWIG interface -debug-top <n> - Display entire parse tree at stages 1-4, <n> is a csv list of stages -debug-typedef - Display information about the types and typedefs in the interface -debug-typemap - Display information for debugging typemaps +-debug-tmsearch - Display typemap search debugging information +-debug-tmused - Display typemaps used debugging information
The complete list of command line options for SWIG are available by running swig -help.
-@@ -4023,7 +4044,7 @@ extern "X" { ... } declaration. -
diff --git a/Doc/Manual/Go.html b/Doc/Manual/Go.html index 5e99a5156..7a55a4364 100644 --- a/Doc/Manual/Go.html +++ b/Doc/Manual/Go.html @@ -5,7 +5,7 @@
-@@ -65,7 +67,7 @@ checking and runtime library are not used with Go. This should be borne in mind when reading the rest of the SWIG documentation.
-@@ -74,7 +76,7 @@ default SWIG will generate code for the gc compilers. To generate code for gccgo, you should also use the -gccgo option.
-@@ -91,10 +93,22 @@ swig -go -help
-soname option passed to the linker.When generating Go code, SWIG will generate the following @@ -163,7 +186,7 @@ A typical command sequence would look like this: % 6l main.6 -
@@ -173,7 +196,7 @@ modifications have to occur. This section briefly covers the essential aspects of this wrapping.
-@@ -183,7 +206,7 @@ directive. You may override this by using SWIG's -package command line option.
-@@ -215,7 +238,7 @@ followed by that name, and the destructor will be named Delete followed by that name.
-@@ -223,7 +246,7 @@ C/C++ constants created via #define or the %constant directive become Go constants, declared with a const declaration. -
@@ -233,7 +256,7 @@ usual). The values of the enumeration will become variables in Go; code should avoid modifying those variables.
-@@ -264,7 +287,7 @@ class.
SWIG will represent static methods of C++ classes as ordinary Go -functions. SWIG will use names like ClassName_MethodName. +functions. SWIG will use names like ClassNameMethodName. SWIG will give static members getter and setter functions with names like GetClassName_VarName.
@@ -280,7 +303,38 @@ to reinterpret_cast. This should only be used for very special cases, such as where C++ would use a dynamic_cast. -Note that C++ pointers to compound objects are represented in go as objects +themselves, not as go pointers. So, for example, if you wrap the following +function:
+
+class MyClass {
+ int MyMethod();
+ static MyClass *MyFactoryFunction();
+};
+
+
+You will get go code that looks like this:
+
+type MyClass interface {
+ Swigcptr() uintptr
+ SwigIsMyClass()
+ MyMethod() int
+}
+
+MyClassMyFactoryFunction() MyClass {
+ // swig magic here
+}
+
+Note that the factory function does not return a go pointer; it actually +returns a go interface. If the returned pointer can be null, you can check +for this by calling the Swigcptr() method. +
+ +@@ -292,7 +346,7 @@ Doing the reverse will require an explicit type assertion, which will be checked dynamically.
-@@ -300,7 +354,7 @@ In order to use C++ templates in Go, you must tell SWIG to create wrappers for a particular template instantation. To do this, use the %template directive. -
@@ -343,7 +397,7 @@ method defined in Go. The Go code may of course call other methods on itself, and those methods may be defined either in Go or in C++.
-@@ -450,5 +504,131 @@ that typemap, or add new values, to control how C/C++ types are mapped into Go types.
+Because of limitations in the way output arguments are processed in swig, +a function with output arguments will not have multiple return values. +Instead, you must pass a pointer into the C++ function to tell it where to +store the output value. In go, you supply a slice in the place of the output +argument.
+ +For example, suppose you were trying to wrap the modf() function in the +C math library which splits x into integral and fractional parts (and +returns the integer part in one of its parameters):
++double modf(double x, double *ip); ++
You could wrap it with SWIG as follows:
++%include <typemaps.i> +double modf(double x, double *OUTPUT); ++
or you can use the %apply directive:
+%include <typemaps.i>
+%apply double *OUTPUT { double *ip };
+double modf(double x, double *ip);
+
+In Go you would use it like this:
+
+ptr := []float64{0.0}
+fraction := modulename.Modf(5.0, ptr)
+
+Since this is ugly, you may want to wrap the swig-generated API with +some additional functions written in go that +hide the ugly details.
+ +There are no char *OUTPUT typemaps. However you can
+apply the signed char * typemaps instead:
+%include <typemaps.i>
+%apply signed char *OUTPUT {char *output};
+void f(char *output);
+
+Often the APIs generated by swig are not very natural in go, especially if
+there are output arguments. You can
+insert additional go wrapping code to add new APIs
+with %insert(go_wrapper), like this:
+%include <typemaps.i>
+// Change name of what swig generates to Wrapped_modf. This function will
+// have the following signature in go:
+// func Wrapped_modf(float64, []float64) float64
+%rename(wrapped_modf) modf(double x, double *ip);
+
+%apply double *OUTPUT { double *ip };
+double modf(double x, double *ip);
+
+%insert(go_wrapper) %{
+
+// The improved go interface to this function, which has two return values,
+// in the more natural go idiom:
+func Modf(x float64) (fracPart float64, intPart float64) {
+ ip := []float64{0.0}
+ fracPart = Wrapped_modf(x, ip)
+ intPart = ip[0]
+ return
+}
+
+%}
+
+For classes, since swig generates an interface, you can add additional +methods by defining another interface that includes the swig-generated +interface. For example,
+
+%rename(Wrapped_MyClass) MyClass;
+%rename(Wrapped_GetAValue) MyClass::GetAValue(int *x);
+%apply int *OUTPUT { int *x };
+
+class MyClass {
+ public:
+ MyClass();
+ int AFineMethod(const char *arg); // Swig's wrapping is fine for this one.
+ bool GetAValue(int *x);
+};
+
+%insert(go_wrapper) %{
+
+type MyClass interface {
+ Wrapped_MyClass
+ GetAValue() (int, bool)
+}
+
+func (arg SwigcptrWrapped_MyClass) GetAValue() (int, bool) {
+ ip := []int{0}
+ ok := arg.Wrapped_GetAValue(ip)
+ return ip[0], ok
+}
+
+%}
+
+Of course, if you have to rewrite most of the methods, instead of just a +few, then you might as well define your own struct that includes the +swig-wrapped object, instead of adding methods to the swig-generated object.
+ +This only works if your wrappers do not need to import other go modules. +There is at present no way to insert import statements in the correct place +in swig-generated go. If you need to do that, you must put your go code +in a separate file.
diff --git a/Doc/Manual/Guile.html b/Doc/Manual/Guile.html index 75c3d3473..6f1300492 100644 --- a/Doc/Manual/Guile.html +++ b/Doc/Manual/Guile.html @@ -8,7 +8,7 @@ -This section details guile-specific support in SWIG. -
@@ -55,7 +55,7 @@ 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". -
The guile module can currently export wrapper files that use the guile GH interface or the @@ -103,7 +103,7 @@ for the specific API. Currently only the guile language module has created a ma but there is no reason other languages (like mzscheme or chicken) couldn't also use this. If that happens, there is A LOT less code duplication in the standard typemaps.
-@@ -111,7 +111,7 @@ Guile support is complicated by a lack of user community cohesiveness, which manifests in multiple shared-library usage conventions. A set of policies implementing a usage convention is called a linkage. -
@@ -206,7 +206,7 @@ placed between the define-module form and the
SWIG_init via a preprocessor define to avoid symbol
clashes. For this case, however, passive linkage is available.
-
Passive linkage is just like simple linkage, but it generates an @@ -216,7 +216,7 @@ package name (see below).
You should use passive linkage rather than simple linkage when you are using multiple modules. -
SWIG can also generate wrapper code that does all the Guile module @@ -257,7 +257,7 @@ Newer Guile versions have a shorthand procedure for this:
Guile used to support an autoloading facility for object-code @@ -283,7 +283,7 @@ option, SWIG generates an exported module initialization function with an appropriate name. -
@@ -308,7 +308,7 @@ my/lib/libfoo.so.X.Y.Z and friends. This scheme is still very experimental; the (hobbit4d link) conventions are not well understood.
-
@@ -320,7 +320,7 @@ complained so far.
%rename to specify the Guile name of the wrapped
functions and variables (see CHANGES).
-
@@ -412,7 +412,7 @@ constant will appear as a scheme variable. See Features and the %feature directive for info on how to apply the %feature.
-
@@ -429,11 +429,11 @@ upper half of the CAR is read from this struct.
To get the pointer represented by a smob, the wrapper code calls the
function SWIG_ConvertPtr(), passing a pointer to a struct
representing the expected pointer type. See also
-The run-time type checker.
+The run-time type checker.
If the Scheme object passed was not a SWIG smob representing a compatible
pointer, a wrong-type-arg exception is raised.
-
@@ -462,7 +462,7 @@ that created them, so the first module we check will most likely be correct. Once we have a swig_type_info structure, we loop through the linked list of casts, using pointer comparisons.
-The SCM interface (using the "-scm" argument to swig) uses swigrun.swg. @@ -477,7 +477,7 @@ in the smob tag. If a generated GOOPS module has been loaded, smobs will be wra GOOPS class.
-Garbage collection is a feature of the new SCM interface, and it is automatically included @@ -491,7 +491,7 @@ is exactly like described in 21.7 Exception Handling +
@@ -517,7 +517,7 @@ mapping: The default when not specified here is to use "swig-error". See Lib/exception.i for details. -
If invoked with the command-line option For global variables, SWIG creates a single wrapper procedure
@@ -581,7 +581,7 @@ struct members, the procedures SWIG can also generate classes and generic functions for use with
@@ -730,7 +730,7 @@ Notice that <Foo> is used before it is defined. The fix is to just put th
As you can see in the example above, there are potential naming conflicts. The default exported
@@ -767,7 +767,7 @@ guile-modules. For example, The guile-modules generated above all need to be linked together. GOOPS support requires
diff --git a/Doc/Manual/Introduction.html b/Doc/Manual/Introduction.html
index 3bac9484e..a8d15a5c2 100644
--- a/Doc/Manual/Introduction.html
+++ b/Doc/Manual/Introduction.html
@@ -195,9 +195,9 @@ extern int my_mod(int n, int m);
The interface file contains ANSI C function prototypes and variable
declarations. The %module directive defines the name of the
-module that will be created by SWIG. The %{,%} block
-provides a location for inserting additional code such as C header
-files or additional C declarations.
+module that will be created by SWIG. The %{ %} block
+provides a location for inserting additional code, such as C header
+files or additional C declarations, into the generated C wrapper code.
If you are using the GNU Autotools
-(Autoconf/
-Automake/
-Libtool)
+(Autoconf/
+Automake/
+Libtool)
to configure SWIG use in your project, the SWIG Autoconf macros can be used.
The primary macro is ax_pkg_swig, see
http://www.gnu.org/software/autoconf-archive/ax_pkg_swig.html#ax_pkg_swig.
diff --git a/Doc/Manual/Java.html b/Doc/Manual/Java.html
index f572ffa32..8245d46eb 100644
--- a/Doc/Manual/Java.html
+++ b/Doc/Manual/Java.html
@@ -5,7 +5,7 @@
-procdoc
@@ -553,7 +553,7 @@ like this:
typemap argument doc. See Lib/guile/typemaps.i for
details.
-21.9 Procedures with setters
+23.9 Procedures with setters
(struct-member-get
pointer) and (struct-member-set pointer
value) are not generated.
-21.10 GOOPS Proxy Classes
+23.10 GOOPS Proxy Classes
%import "foo.h" before the %inline block.
21.10.1 Naming Issues
+23.10.1 Naming Issues
21.10.2 Linking
+23.10.2 Linking
2.3.2 The swig command
@@ -372,9 +372,9 @@ Microsoft Visual Studio.
22 SWIG and Java
+24 SWIG and Java
@@ -86,6 +86,7 @@
@@ -166,7 +168,7 @@ SWIG wraps C/C++ code using Java proxy classes and is very useful if you want to If only one or two JNI functions are needed then using SWIG may be overkill. SWIG enables a Java program to easily call into C/C++ code from Java. Historically, SWIG was not able to generate any code to call into Java code from C++. -However, SWIG now supports full cross language polymorphism and code is generated to call up from C++ to Java when wrapping C++ virtual methods. +However, SWIG now supports full cross language polymorphism and code is generated to call up from C++ to Java when wrapping C++ virtual methods via the director feature.
@@ -189,7 +191,7 @@ Various customisation tips and techniques using SWIG directives are covered. The latter sections cover the advanced techniques of using typemaps for complete control of the wrapping process.
-@@ -205,7 +207,11 @@ Run make -k check from the SWIG root directory after installing SWIG on The Java module requires your system to support shared libraries and dynamic loading. This is the commonly used method to load JNI code so your system will more than likely support this.
-+Android uses Java JNI and also works with SWIG. Please read the Android chapter in conjunction with this one if you are targeting Android. +
+ +@@ -264,7 +270,7 @@ The following sections have further practical examples and details on how you mi compiling and using the generated files.
-@@ -301,7 +307,7 @@ swig -java -help Their use will become clearer by the time you have finished reading this section on SWIG and Java.
-@@ -316,17 +322,18 @@ They are usually in directories like this:
The exact location may vary on your machine, but the above locations are typical.
-The JNI code exists in a dynamic module or shared library (DLL on Windows) and gets loaded by the JVM. -To build a shared library file, you need to compile your module in a manner similar to the following (shown for Solaris):
+Assuming you have code you need to link to in a file called example.c, in order to build a shared library file, you need to compile your module in a manner similar to the following (shown for Solaris):$ swig -java example.i $ gcc -c example_wrap.c -I/usr/java/include -I/usr/java/include/solaris -$ ld -G example_wrap.o -o libexample.so +$ gcc -c example.c +$ ld -G example_wrap.o example.o -o libexample.so
@@ -352,7 +359,7 @@ The name of the shared library output file is important. If the name of your SWIG module is "example", the name of the corresponding shared library file should be "libexample.so" (or equivalent depending on your machine, see Dynamic linking problems for more information). The name of the module is specified using the %module directive or -module command line option.
-@@ -363,7 +370,7 @@ To load your shared native library module in Java, simply use Java's System. public class runme { static { - System.loadLibrary("example"); + System.loadLibrary("example"); } public static void main(String argv[]) { @@ -387,7 +394,7 @@ $ If it doesn't work have a look at the following section which discusses problems loading the shared library.
-@@ -474,7 +481,7 @@ The following section also contains some C++ specific linking problems and solut
-@@ -527,7 +534,7 @@ Finally make sure the version of JDK header files matches the version of Java th
-@@ -536,7 +543,7 @@ You will want to produce a DLL that can be loaded by the Java Virtual Machine. This section covers the process of using SWIG with Microsoft Visual C++ 6 although the procedure may be similar with other compilers. In order for everything to work, you will need to have a JDK installed on your machine in order to read the JNI header files.
-@@ -575,7 +582,7 @@ To run the native code in the DLL (example.dll), make sure that it is in your pa If the library fails to load have a look at Dynamic linking problems.
-@@ -634,7 +641,7 @@ Of course you may want to make changes for it to work for C++ by adding in the -
-@@ -644,7 +651,7 @@ variables are wrapped with JavaBean type getters and setters and so forth. This section briefly covers the essential aspects of this wrapping.
-@@ -680,7 +687,7 @@ swig -java -package com.bloggs.swig -outdir com/bloggs/swig example.i SWIG won't create the directory, so make sure it exists beforehand.
-@@ -714,7 +721,7 @@ System.out.println(example.fact(4)); -
@@ -801,7 +808,7 @@ extern char *path; // Read-only (due to %immutable) -
@@ -941,7 +948,7 @@ Or if you decide this practice isn't so bad and your own class implements ex
-@@ -955,7 +962,7 @@ The final two approaches use simple integers for each enum item. Before looking at the various approaches for wrapping named C/C++ enums, anonymous enums are considered.
-@@ -1018,7 +1025,7 @@ As in the case of constants, you can access them through either the module class
-@@ -1112,7 +1119,7 @@ When upgrading to JDK 1.5 or later, proper Java enums could be used instead, wit The following section details proper Java enum generation.
-@@ -1165,7 +1172,7 @@ The additional support methods need not be generated if none of the enum items h Simpler Java enums for enums without initializers section.
-@@ -1213,7 +1220,7 @@ Note that unlike typesafe enums, this approach requires users to mostly use diff Thus the upgrade path to proper enums provided in JDK 1.5 is more painful.
-@@ -1232,7 +1239,7 @@ SWIG-1.3.21 and earlier versions wrapped all enums using this approach. The type unsafe approach is preferable to this one and this simple approach is only included for backwards compatibility with these earlier versions of SWIG.
-@@ -1320,7 +1327,7 @@ C-style cast may return a bogus result whereas as the C++-style cast will return a NULL pointer if the conversion can't be performed.
-@@ -1488,7 +1495,7 @@ x.setA(3); // Modify x.a - this is the same as b.f.a -
@@ -1551,7 +1558,7 @@ int bar = Spam.getBar(); -
@@ -1612,7 +1619,7 @@ Note that Java does not support multiple inheritance so any multiple inheritance A warning is given when multiple inheritance is detected and only the first base class is used.
-@@ -1667,7 +1674,7 @@ to hold the result and a pointer is returned (Java will release this memory when the returned object's finalizer is run by the garbage collector).
-@@ -1691,7 +1698,7 @@ For spam1 and spam4 above the Java null gets translat The converse also occurs, that is, NULL pointers are translated into null Java objects when returned from a C/C++ function.
-@@ -1806,7 +1813,7 @@ void spam(unsigned short); // Ignored -
@@ -1849,7 +1856,7 @@ Further details on default arguments and how to restore this approach are given
-
@@ -1916,18 +1923,30 @@ The default behaviour described above can be improved via the
+If it is undesirable to have a single top level package, the nspace feature may be used without the -package commandline option
+(and the resulting warning ignored) if all of the types exposed using SWIG are placed in a package using the nspace feature and the
+'jniclasspackage' pragma is used to specify a package for the JNI intermediary class.
+
+If the resulting use of the nspace feature and hence packages results in a proxy class in one package deriving or using a proxy class from another package,
+you will need to open up the visibility for the pointer constructor and getCPtr method from the default 'protected' to 'public' with the SWIG_JAVABODY_PROXY macro. See Java code typemaps.
+
@@ -1976,7 +1995,7 @@ Obviously, there is more to template wrapping than shown in this example.
More details can be found in the SWIG and C++ chapter.
@@ -2060,7 +2079,7 @@ Foo f = p.__deref__(); // Returns underlying Foo *
-
@@ -2075,7 +2094,7 @@ Finally enum classes are covered.
First, the crucial intermediary JNI class is considered.
@@ -2195,7 +2214,7 @@ If name is the same as modulename then the module class name g
from modulename to modulenameModule.
@@ -2211,6 +2230,9 @@ The intermediary JNI class can be tailored through the use of pragmas, but is no
-example.i:16: Error: The nspace feature used on 'MyWorld::Material::Color' is not supported unless a package is specified
-with -package - Java does not support types declared in a named package accessing types declared in an unnamed package.
+example.i:16: Warning 826: The nspace feature is used on 'MyWorld::Material::Color' 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.
-22.3.14 C++ templates
+24.3.14 C++ templates
22.3.15 C++ Smart Pointers
+24.3.15 C++ Smart Pointers
22.4 Further details on the generated Java classes
+24.4 Further details on the generated Java classes
22.4.1 The intermediary JNI class
+24.4.1 The intermediary JNI class
22.4.1.1 The intermediary JNI class pragmas
+24.4.1.1 The intermediary JNI class pragmas
+jniclassbase Base class for the intermediary JNI class
+
jniclasspackage Package in which to place the intermediary JNI class
+
@@ -2274,7 +2296,7 @@ For example, let's change the intermediary JNI class access to just the default
All the methods in the intermediary JNI class will then not be callable outside of the package as the method modifiers have been changed from public access to default access. This is useful if you want to prevent users calling these low level functions.
jniclassclassmodifiers Class modifiers and class type for the intermediary JNI class
@@ -2305,7 +2327,7 @@ example.egg(new Foo()); The primary reason for having the module class wrapping the calls in the intermediary JNI class is to implement static type checking. In this case only a Foo can be passed to the egg function, whereas any long can be passed to the egg function in the intermediary JNI class.
-@@ -2356,7 +2378,7 @@ See The intermediary JNI class pragmas secti
-@@ -2376,7 +2398,7 @@ public class Foo { swigCPtr = cPtr; } - public static long getCPtr(Foo obj) { + protected static long getCPtr(Foo obj) { return (obj == null) ? 0 : obj.swigCPtr; } @@ -2432,7 +2454,7 @@ int y = f.spam(5, new Foo()); -
@@ -2594,7 +2616,7 @@ and
-@@ -2627,7 +2649,7 @@ public class Base { swigCPtr = cPtr; } - public static long getCPtr(Base obj) { + protected static long getCPtr(Base obj) { return (obj == null) ? 0 : obj.swigCPtr; } @@ -2667,7 +2689,7 @@ public class Derived extends Base { swigCPtr = cPtr; } - public static long getCPtr(Derived obj) { + protected static long getCPtr(Derived obj) { return (obj == null) ? 0 : obj.swigCPtr; } @@ -2710,7 +2732,7 @@ However, true cross language polymorphism can be achieved using the 22.4.3.3 Proxy classes and garbage collection +
@@ -2743,7 +2765,7 @@ Call the System.runFinalizersOnExit(true) or Runtime.getRuntime().r This method is inherently unsafe. It may result in finalizers being called on live objects while other threads are concurrently manipulating those objects, resulting in erratic behavior or deadlock.
In many cases you will be lucky and find that it works, but it is not to be advocated. -Have a look at Sun's Java web site and search for runFinalizersOnExit. +Have a look at Java web site and search for runFinalizersOnExit.
@@ -2793,7 +2815,7 @@ The section on Java typemaps details how to specify See the How to Handle Java Finalization's Memory-Retention Issues article for alternative approaches to managing memory by avoiding finalizers altogether.
-@@ -2915,7 +2937,7 @@ For example: Compatibility note: The generation of this additional parameter did not occur in versions prior to SWIG-1.3.30.
-@@ -2946,7 +2968,7 @@ public class Test { swigCPtr = cPtr; } - public static long getCPtr(Test obj) { + protected static long getCPtr(Test obj) { return (obj == null) ? 0 : obj.swigCPtr; } @@ -3003,7 +3025,7 @@ for (int i=0; i<100000; i++) { -
@@ -3090,7 +3112,7 @@ public static void spam(SWIGTYPE_p_int x, SWIGTYPE_p_int y, int z) { ... } -
@@ -3099,7 +3121,7 @@ The Enumerations section discussed these but om The following sub-sections detail the various types of enum classes that can be generated.
-@@ -3183,7 +3205,7 @@ The swigValue method is used for marshalling in the other direction. The toString method is overridden so that the enum name is available.
-@@ -3261,7 +3283,7 @@ These needn't be generated if the enum being wrapped does not have any initializ Simpler Java enums for enums without initializers section describes how typemaps can be used to achieve this.
-@@ -3292,7 +3314,7 @@ public final class Beverage { -
@@ -3314,7 +3336,7 @@ The upshot is that C++ classes can be extended in Java and from C++ these extens Neither C++ code nor Java code needs to know where a particular method is implemented: the combination of proxy classes, director classes, and C wrapper functions transparently takes care of all the cross-language method routing.
-@@ -3342,9 +3364,6 @@ The %feature directive can be applied globally, to specific classes, and to spec // generate directors for all virtual methods in class Foo %feature("director") Foo; - -// generate a director for just Foo::bar() -%feature("director") Foo::bar; @@ -3385,7 +3404,7 @@ public: -
@@ -3412,7 +3431,7 @@ If the correct implementation is in Java, the Java API is used to call the metho
-@@ -3430,7 +3449,7 @@ This situation can be optimized by selectively enabling director methods (using
-@@ -3458,7 +3477,7 @@ void callup(DirectorBase *director) {
The following DirectorDerived Java class is derived from the Java proxy class DirectorBase and overrides upcall_method().
When C++ code invokes upcall_method(), the SWIG-generated C++ code redirects the call via JNI to the Java DirectorDerived subclass.
-Naturally, the SWIG generated C++ code and the generated Java intermediate class marshal and convert arguments between C++ and Java when needed.
+Naturally, the SWIG generated C++ code and the generated Java intermediary class marshal and convert arguments between C++ and Java when needed.
@@ -3515,7 +3534,29 @@ Macros can be defined on the commandline when compiling your C++ code, or altern -
+When a new instance of a director (or subclass) is created in Java, the C++ side of the director performs a runtime check per director method to determine if that particular method is overridden in Java or if it should invoke the C++ base implementation directly. Although this makes initialization slightly more expensive, it is generally a good overall tradeoff. +
+ ++However, if all director methods are expected to usually be overridden by Java subclasses, then initialization can be made faster by avoiding these checks via the assumeoverride attribute. For example: +
+ +
+%feature("director", assumeoverride=1) Foo;
+
++The disadvantage is that invocation of director methods from C++ when Java doesn't actually override the method will require an additional call up into Java and back to C++. As such, this option is only useful when overrides are extremely common and instantiation is frequent enough that its performance is critical. +
+ + +@@ -3611,7 +3652,7 @@ class MyProtectedBase extends ProtectedBase -
@@ -3623,7 +3664,7 @@ be awkward. This section describes some common SWIG features that are used to improve the interface to existing C/C++ code.
-@@ -3689,7 +3730,7 @@ hard to implement. It is possible to improve on this using Java code, typemaps, customization features as covered in later sections, but sometimes helper functions are a quick and easy solution to difficult cases.
-@@ -3752,7 +3793,7 @@ Vector(2,3,4) in any way---the extensions only show up in the Java interface.
-@@ -3911,7 +3952,7 @@ to raise exceptions. See the SWIG Library ch The typemap example Handling C++ exception specifications as Java exceptions provides further exception handling capabilities.
-@@ -3937,7 +3978,7 @@ protected static void protect_me() { -
@@ -3947,7 +3988,7 @@ strings and arrays. This chapter discusses the common techniques for solving these problems.
-@@ -4121,7 +4162,7 @@ void foo(Bar *OUTPUT); will not have the intended effect since typemaps.i does not define an OUTPUT rule for Bar.
-@@ -4187,7 +4228,7 @@ System.out.println("3 + 4 = " + result); See the SWIG Library chapter for further details.
-@@ -4254,7 +4295,7 @@ Please be aware that the typemaps in this library are not efficient as all the e There is an alternative approach using the SWIG array library and this is covered in the next section.
-@@ -4399,7 +4440,51 @@ well suited for applications in which you need to create buffers, package binary data, etc.
-+By default SWIG handles char * as a string but there is a handy multi-argument typemap available as mentioned in Passing binary data. +The following simple example demonstrates using a byte array instead of passing the default string type and length to the wrapped function. +
+ + +
+%apply (char *STRING, size_t LENGTH) { (const char data[], size_t len) }
+%inline %{
+void binaryChar1(const char data[], size_t len) {
+ printf("len: %d data: ", len);
+ for (size_t i=0; i<len; ++i)
+ printf("%x ", data[i]);
+ printf("\n");
+}
+%}
+
++Calling from Java requires just the byte array to be passed in as the multi-argument typemap being applied reduces the number of arguments in the target language to one, from the original two: +
+ ++byte[] data = "hi\0jk".getBytes(); +example.binaryChar1(data); ++
+resulting in the output +
+ ++$ java runme +len: 5 data: 68 69 0 6a 6b +
@@ -4516,7 +4601,7 @@ model and use these functions in place of malloc and free in your own code.
-@@ -4537,7 +4622,7 @@ Before proceeding, it should be stressed that typemaps are not a required part of using SWIG---the default wrapping behavior is enough in most cases. Typemaps are only used if you want to change some aspect of the generated code. -
@@ -4689,7 +4774,7 @@ However, the mappings allow the full range of values for each C type from Java.
-@@ -4704,7 +4789,7 @@ So in summary, the C/C++ pointer to non-primitive types is cast into the 64 bit The Java type is either the proxy class or type wrapper class.
-@@ -4717,7 +4802,7 @@ Unfortunately it won't of course hold true for JNI code.
-@@ -4840,7 +4925,7 @@ int c = example.count('e',"Hello World"); -
@@ -5100,7 +5185,7 @@ These are listed below: -
@@ -5146,7 +5231,7 @@ The "javain" typemap has the optional 'pre', 'post' and 'pgcppname' attributes. Note that when the 'pre' or 'post' attributes are specified and the associated type is used in a constructor, a constructor helper function is generated. This is necessary as the Java proxy constructor wrapper makes a call to a support constructor using a this call. In Java the this call must be the first statement in the constructor body. The constructor body thus calls the helper function and the helper function instead makes the JNI call, ensuring the 'pre' code is called before the JNI call is made. There is a Date marshalling example showing 'pre', 'post' and 'pgcppname' attributes in action.
-@@ -5297,7 +5382,7 @@ This special variable expands to the intermediary class name. Usually this is th unless the jniclassname attribute is specified in the %module directive.
-@@ -5334,7 +5419,7 @@ If you do not intend your code to be targeting both C and C++ then your typemaps
-@@ -5406,12 +5491,28 @@ import statements for Java class: empty default
%typemap(javainterfaces)
%typemap(javafinalize)
+Note that the default javafinalize typemap must contain the full implementation of the finalize method. +Any customization to this typemap must still declare a java finalize method with the correct signature. +Note also that the name of the generated "delete" method may be affected by javadestruct and javadestruct_derived typemaps. +Below shows an example modifying the finalizer, assuming the delete method has been renamed to swig_delete. +
+ +
+%typemap(javafinalize) SWIGTYPE %{
+ protected void finalize() {
+ swig_delete(); // renamed to prevent conflict with existing delete method
+ }
+]%
+@@ -5503,15 +5604,8 @@ The typemap code is the same that is in "java.swg", barring the last tw Note that SWIGTYPE will target all proxy classes, but not the type wrapper classes. Also the above typemap is only used for proxy classes that are potential base classes. To target proxy classes that are derived from a wrapped class as well, the "javabody_derived" typemap should also be overridden. -There is a macro in java.swg that implements this and the above can instead be implemented using:
--SWIG_JAVABODY_METHODS(protected, protected, SWIGTYPE) --
For the typemap to be used in all type wrapper classes, all the different types that type wrapper classes could be used for should be targeted:
@@ -5521,7 +5615,7 @@ For the typemap to be used in all type wrapper classes, all the different types %typemap(javabody) SWIGTYPE *, SWIGTYPE &, SWIGTYPE [], SWIGTYPE (CLASS::*) %{ private long swigCPtr; - public $javaclassname(long cPtr, boolean bFutureUse) { + protected $javaclassname(long cPtr, boolean bFutureUse) { swigCPtr = cPtr; } @@ -5529,7 +5623,7 @@ For the typemap to be used in all type wrapper classes, all the different types swigCPtr = 0; } - public static long getCPtr($javaclassname obj) { + protected static long getCPtr($javaclassname obj) { return (obj == null) ? 0 : obj.swigCPtr; } %} @@ -5540,7 +5634,30 @@ For the typemap to be used in all type wrapper classes, all the different types Again this is the same that is in "java.swg", barring the method modifier for getCPtr. -+When using multiple modules or the nspace feature it is common to invoke SWIG with a different -package +command line option for each module. +However, by default the generated code may not compile if +generated classes in one package use generated classes in another package. +The visibility of the +getCPtr() and pointer constructor generated from the javabody typemaps needs changing. +The default visibility is protected but it needs to be public for access from a different package. +Just changing 'protected' to 'public' in the typemap achieves this. +Two macros are available in java.swg to make this easier and using them is the preferred approach +over simply copying the typemaps and modifying as this is forward compatible with any changes in +the javabody typemap in future versions of SWIG. +The macros are for the proxy and typewrapper classes and can respectively be used to +to make the method and constructor public: +
+ ++ SWIG_JAVABODY_PROXY(public, public, SWIGTYPE) + SWIG_JAVABODY_TYPEWRAPPER(public, public, public, SWIGTYPE) ++
@@ -5765,7 +5882,7 @@ The basic strategy here is to provide a default package typemap for the majority -
@@ -5775,7 +5892,7 @@ the SWIG library.
-@@ -5854,7 +5971,7 @@ This would be done by using the original versions of these typemaps in "enums.sw
-@@ -5979,7 +6096,7 @@ We could alternatively have used %rename to rename what() into
-@@ -6134,7 +6251,7 @@ If we were a martyr to the JNI cause, we could replace the succinct code within If we had, we would have put it in the "in" typemap which, like all JNI and Java typemaps, also supports the 'throws' attribute.
-@@ -6234,7 +6351,7 @@ public class runme { static { try { - System.loadLibrary("example"); + System.loadLibrary("example"); } catch (UnsatisfiedLinkError e) { System.err.println("Native code library failed to load. " + e); System.exit(1); @@ -6278,7 +6395,7 @@ Lastly the "jni", "jtype" and "jstype" typemaps are also required to specify what Java types to use.
-@@ -6360,7 +6477,7 @@ example.foo(new String[]{"red", "green", "blue", "white"}); -
@@ -6453,7 +6570,7 @@ public class runme { static { try { - System.loadLibrary("example"); + System.loadLibrary("example"); } catch (UnsatisfiedLinkError e) { System.err.println("Native code library failed to load. " + e); System.exit(1); @@ -6478,7 +6595,7 @@ $ java runme 1 12.0 340.0 -
@@ -6684,7 +6801,7 @@ SWIG usually generates code which constructs the proxy classes using Java code a Note that the JNI code above uses a number of string lookups to call a constructor, whereas this would not occur using byte compiled Java code.
-@@ -6728,7 +6845,7 @@ System.out.println("foo1? " + foo1.equals(foo2)); -
@@ -6787,7 +6904,7 @@ This example contains some useful functionality which you may want in your code.
@@ -6967,7 +7084,7 @@ The C functional interface has been completely morphed into an object-oriented i the Butler class would behave much like any pure Java class and feel more natural to Java users.
-@@ -7090,7 +7207,7 @@ public class Bike { Note the addReference call.
-@@ -7206,7 +7323,7 @@ The 'javacode' typemap simply adds in the specified code into the Java proxy cla -
@@ -7383,7 +7500,7 @@ A few things to note: -
@@ -7564,10 +7681,10 @@ public abstract class UserVisibleFoo extends Foo {
@@ -7623,7 +7740,7 @@ public class Barmy { -
@@ -7684,7 +7801,7 @@ All destructors have to be called manually for example the delete_Foo(foo)
-@@ -7734,7 +7851,7 @@ This directive is only really useful if you want to mix your own hand crafted JN
-@@ -7755,7 +7872,7 @@ However, you will have to be careful about memory management and make sure that This method normally calls the C++ destructor or free() for C code.
-@@ -7777,7 +7894,7 @@ The -verbose:jni and -verbose:gc are also useful options for monitoring code beh
-@@ -7792,4 +7909,3 @@ Many of these have runtime tests in the java subdirectory.