~ubuntu-branches/ubuntu/hoary/swig1.3/hoary

« back to all changes in this revision

Viewing changes to Doc/Manual/Java.html

  • Committer: Bazaar Package Importer
  • Author(s): Thom May
  • Date: 2004-08-02 15:57:10 UTC
  • mfrom: (1.1.1 upstream)
  • Revision ID: james.westby@ubuntu.com-20040802155710-bm292q1d6x6tw7gc
Tags: 1.3.21-5ubuntu1
Fix linking for ruby, python, perl and tcl bindings

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
1
2
<html>
2
3
<head>
3
4
<title>SWIG and Java</title>
4
5
</head>
5
6
<body bgcolor="#FFFFFF">
6
 
<a name="n0"></a><h1>SWIG and Java</h1><p><ul>
7
 
<li> <a href="#n1">Preliminaries</a>
8
 
<li> <a href="#n2">Building Java Extensions under Windows 95/NT</a>
9
 
<li> <a href="#n3">The low-level Java/C interface</a>
10
 
<li> <a href="#n4">Java shadow classes</a>
11
 
<li> <a href="#n5">Examples</a>
12
 
<li> <a href="#n6">Exception handling </a>
13
 
<li> <a href="#n7">Remapping C datatypes with typemaps</a>
14
 
<li> <a href="#n8">The gory details of shadow classes</a>
15
 
<li> <a href="#n9">Java pragmas</a>
16
 
<li> <a href="#n10">Dynamic linking problems</a>
17
 
<li> <a href="#n11">Tips</a>
18
 
<li> <a href="#n12">Known bugs</a>
19
 
</ul>
20
 
 
21
 
This chapter describes SWIG's support of Java. Java is one of the latest modules to be added to SWIG. The other SWIG modules are primarily scripting languages. Using Java has the advantage over scripting languages of being type safe.  The 100% Pure Java effort is a commendable concept however, in the real world programmers either need to re-use their existing code or in some situations want to take advantage of Java but are forced into using some native (C/C++) code.  With this Java extension to SWIG it is very easy to plumb in existing C/C++ code for access from Java, as SWIG writes the Java Native Interface (JNI) code for you. It is different to using the 'javah' tool as SWIG will wrap existing C/C++ code, whereas javah takes Java functions and creates C/C++ function prototypes.
22
 
<p>
23
 
 
24
 
<a name="n1"></a><h2>Preliminaries</h2>
25
 
SWIG 1.1 works with JDK 1.1 and higher. Given the choice, you should use the latest version of Sun's JDK. The SWIG Java module is known to work on Solaris, the various flavours of Windows including cygwin and Linux using Sun's JDK. It is also known to work on vxWorks using their PJava 3.1. The Kaffe JVM is known to give a few problems and at the time of writing was not a fully fledged JVM with full JNI support. The best way to determine whether your combination of operating system and JDK will work is to test the examples and test-suite that comes with SWIG. Run the <tt>make check</tt> from the SWIG root directory after installing SWIG. <p>
26
 
 
27
 
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 is more than likely to support this.<p>
28
 
 
29
 
<a name="n100"></a><h3>Running SWIG</h3>
30
 
The basics of getting a SWIG Java module up and running can be seen from one of SWIG's example Makefiles, but is also described here. To build a Java module, run SWIG using the <tt>-java</tt> option. Enabling shadow classes <tt>-shadow</tt> is also recommended:<p>
31
 
<p>
32
 
<blockquote><pre>%swig -java -shadow example.i
33
 
</pre></blockquote>
34
 
<p>
35
 
This will produce 2 files. The file <tt>example_wrap.c</tt> contains all of the C code needed to build a Java module. To build a Java module, you will need to compile the file <tt>example_wrap.c</tt> to create a shared library. When shadow classes are enabled, SWIG may also produce many <tt>.java</tt> files, but this is described later.<p>
36
 
 
37
 
<a name="n101"></a><h3>Additional Commandline Options</h3>
 
7
<a name="n1"></a><H1>17 SWIG and Java</H1>
 
8
<!-- INDEX -->
 
9
<ul>
 
10
<li><a href="#n2">Overview</a>
 
11
<li><a href="#n3">Preliminaries</a>
 
12
<ul>
 
13
<li><a href="#n4">Running SWIG</a>
 
14
<li><a href="#n5">Additional Commandline Options</a>
 
15
<li><a href="#n6">Getting the right header files</a>
 
16
<li><a href="#n7">Compiling a dynamic module</a>
 
17
<li><a href="#n8">Using your module</a>
 
18
<li><a href="#n9">Dynamic linking problems</a>
 
19
<li><a href="#n10">Compilation problems and compiling with C++</a>
 
20
<li><a href="#n11">Building on Windows</a>
 
21
<ul>
 
22
<li><a href="#n12">Running SWIG from Visual Studio</a>
 
23
<li><a href="#n13">Using NMAKE</a>
 
24
</ul>
 
25
</ul>
 
26
<li><a href="#n14">A tour of basic C/C++ wrapping</a>
 
27
<ul>
 
28
<li><a href="#n15">Modules, packages and generated Java classes</a>
 
29
<li><a href="#n16">Functions</a>
 
30
<li><a href="#n17">Global variables</a>
 
31
<li><a href="#n18">Constants</a>
 
32
<li><a href="#n19">Enumerations</a>
 
33
<li><a href="#n20">Pointers</a>
 
34
<li><a href="#n21">Structures</a>
 
35
<li><a href="#n22">C++ classes</a>
 
36
<li><a href="#n23">C++ inheritance</a>
 
37
<li><a href="#n24">Pointers, references, arrays and pass by value</a>
 
38
<ul>
 
39
<li><a href="#n25">Null pointers</a>
 
40
</ul>
 
41
<li><a href="#n26">C++ overloaded functions</a>
 
42
<li><a href="#n27">C++ namespaces</a>
 
43
<li><a href="#n28">C++ templates</a>
 
44
<li><a href="#n29">C++ Smart Pointers</a>
 
45
</ul>
 
46
<li><a href="#n30">Further details on the generated Java classes</a>
 
47
<ul>
 
48
<li><a href="#n31">The intermediary JNI class</a>
 
49
<ul>
 
50
<li><a href="#n32">The intermediary JNI class pragmas</a>
 
51
</ul>
 
52
<li><a href="#n33">The Java module class</a>
 
53
<ul>
 
54
<li><a href="#n34">The Java module class pragmas</a>
 
55
</ul>
 
56
<li><a href="#n35">Java proxy classes</a>
 
57
<ul>
 
58
<li><a href="#n36">Memory management</a>
 
59
<li><a href="#n37">Inheritance</a>
 
60
<li><a href="#n38">Proxy classes and garbage collection</a>
 
61
</ul>
 
62
<li><a href="#n39">Type wrapper classes</a>
 
63
</ul>
 
64
<li><a href="#n40">Cross language polymorphism using directors (experimental)</a>
 
65
<ul>
 
66
<li><a href="#n41">Enabling directors</a>
 
67
<li><a href="#n42">Director classes</a>
 
68
<li><a href="#n43">Overhead and code bloat</a>
 
69
<li><a href="#n44">Simple directors example</a>
 
70
</ul>
 
71
<li><a href="#n45">Common customization features</a>
 
72
<ul>
 
73
<li><a href="#n46">C/C++ helper functions</a>
 
74
<li><a href="#n47">Class extension with %extend</a>
 
75
<li><a href="#n48">Exception handling with %exception</a>
 
76
<li><a href="#n49">Method access with %javamethodmodifiers</a>
 
77
</ul>
 
78
<li><a href="#n50">Tips and techniques</a>
 
79
<ul>
 
80
<li><a href="#n51">Input and output parameters using primitive pointers and references</a>
 
81
<li><a href="#n52">Simple pointers</a>
 
82
<li><a href="#n53">Wrapping C arrays with Java arrays</a>
 
83
<li><a href="#n54">Unbounded C Arrays</a>
 
84
</ul>
 
85
<li><a href="#n55">Java typemaps</a>
 
86
<ul>
 
87
<li><a href="#n56">Default primitive type mappings</a>
 
88
<li><a href="#n57">Sixty four bit JVMs</a>
 
89
<li><a href="#n58">What is a typemap?</a>
 
90
<li><a href="#n59">Typemaps for mapping C/C++ types to Java types</a>
 
91
<li><a href="#n60">Java special variables</a>
 
92
<li><a href="#n61">Typemaps for both C and C++ compilation</a>
 
93
<li><a href="#n62">Java code typemaps</a>
 
94
<li><a href="#n63">Director specific typemaps</a>
 
95
</ul>
 
96
<li><a href="#n64">Typemap Examples</a>
 
97
<ul>
 
98
<li><a href="#n65">Converting Java String arrays to char ** </a>
 
99
<li><a href="#n66">Expanding a Java object to multiple arguments</a>
 
100
<li><a href="#n67">Using typemaps to return arguments</a>
 
101
<li><a href="#n68">Adding Java downcasts to polymorphic return types</a>
 
102
<li><a href="#n69">Adding an equals method to the Java classes</a>
 
103
<li><a href="#n70">Void pointers and a common Java base class</a>
 
104
</ul>
 
105
<li><a href="#n71">Living with Java Directors</a>
 
106
<li><a href="#n72">Odds and ends</a>
 
107
<ul>
 
108
<li><a href="#n73">JavaDoc comments</a>
 
109
<li><a href="#n74">Functional interface without proxy classes</a>
 
110
<li><a href="#n75">Using your own JNI functions</a>
 
111
<li><a href="#n76">Performance concerns and hints</a>
 
112
</ul>
 
113
<li><a href="#n77">Examples</a>
 
114
</ul>
 
115
<!-- INDEX -->
 
116
 
 
117
 
 
118
 
 
119
This chapter describes SWIG's support of Java. 
 
120
It covers most SWIG features, but certain low-level details are covered in less depth than in earlier chapters. 
 
121
 
 
122
 
 
123
<a name="overview"></a>
 
124
<a name="n2"></a><H2>17.1 Overview</H2>
 
125
 
 
126
 
 
127
The 100% Pure Java effort is a commendable concept, however in the real world programmers often either need to re-use their existing code or in some situations 
 
128
want to take advantage of Java but are forced into using some native (C/C++) code.
 
129
The Java extension to SWIG makes it very easy to plumb in existing C/C++ code for access from Java, as SWIG writes the Java Native Interface (JNI) code for you. 
 
130
It is different to using the 'javah' tool as SWIG will wrap existing C/C++ code, whereas javah takes 'native' Java function declarations and creates C/C++ function prototypes.
 
131
SWIG wraps C/C++ code using Java proxy classes and is very useful if you want to have access to large amounts of C/C++ code from Java.
 
132
If only one or two JNI functions are needed then using SWIG may be overkill.
 
133
SWIG enables a Java program to easily call into C/C++ code from Java.
 
134
Historically, SWIG was not able to generate any code to call into Java code from C++.
 
135
However, SWIG now supports full cross language polymorphism and code is generated to call up from C++ to Java when wrapping C++ virtual methods.
 
136
 
 
137
<p>
 
138
 
 
139
Java is one of the few non-scripting language modules in SWIG.
 
140
As SWIG utilizes the type safety that the Java language offers, it takes a somewhat different approach to that used for scripting languages.
 
141
In particular runtime type checking and the runtime library are not used by Java.
 
142
This should be borne in mind when reading the rest of the SWIG documentation.
 
143
This chapter on Java is relatively self contained and will provide you with nearly everything you need for using SWIG and Java.
 
144
However, the "<a href="SWIG.html">SWIG Basics</a>" chapter will be a useful read in conjunction with this one.
 
145
<p>
 
146
 
 
147
This chapter starts with a few practicalities on running SWIG and compiling the generated code.
 
148
If you are looking for the minimum amount to read, have a look at the sections up to and including the
 
149
<a href="#java_basic_tour">tour of basic C/C++ wrapping</a> section which explains how to call the various C/C++ code constructs from Java.
 
150
Following this section are details of the C/C++ code and Java classes that SWIG generates.
 
151
Due to the complexities of C and C++ there are different ways in which C/C++ code could be wrapped and called from Java.
 
152
SWIG is a powerful tool and the rest of the chapter details how the default code wrapping can be tailored.
 
153
Various customisation tips and techniques using SWIG directives are covered.
 
154
The latter sections cover the advanced techniques of using typemaps for complete control of the wrapping process.
 
155
 
 
156
<a name="preliminaries"></a>
 
157
<a name="n3"></a><H2>17.2 Preliminaries</H2>
 
158
 
 
159
 
 
160
SWIG 1.1 works with JDKs from JDK 1.1 to JDK1.4 (Java 2 SDK1.4) and should also work with any later versions.
 
161
Given the choice, you should probably use the latest version of Sun's JDK. 
 
162
The SWIG Java module is known to work using Sun's JVM on Solaris, Linux and the various flavours of Microsoft Windows including Cygwin. 
 
163
The Kaffe JVM is known to give a few problems and at the time of writing was not a fully fledged JVM with full JNI support. 
 
164
The generated code is also known to work on vxWorks using WindRiver's PJava 3.1. 
 
165
The best way to determine whether your combination of operating system and JDK will work is to test the examples and test-suite that comes with SWIG. 
 
166
Run <tt>make -k check</tt> from the SWIG root directory after installing SWIG on Unix systems. <p>
 
167
 
 
168
The Java module requires your system to support shared libraries and dynamic loading. 
 
169
This is the commonly used method to load JNI code so your system will more than likely support this.<p>
 
170
 
 
171
<a name="running_swig"></a>
 
172
<a name="n4"></a><H3>17.2.1 Running SWIG</H3>
 
173
 
 
174
 
 
175
Suppose that you defined a SWIG module such as the following:
 
176
 
 
177
<blockquote>
 
178
<pre>
 
179
%module example
 
180
%{
 
181
#include "header.h"
 
182
%}
 
183
int fact(int n);
 
184
</pre>
 
185
</blockquote>
 
186
 
 
187
 
 
188
To build a Java module, run SWIG using the <tt>-java</tt> option :<p>
 
189
 
 
190
<blockquote><pre>%swig -java example.i
 
191
</pre></blockquote>
 
192
<p>
 
193
 
 
194
If building C++, add the <tt>-c++</tt> option:
 
195
 
 
196
<p>
 
197
<blockquote><pre>$ swig -c++ -java example.i
 
198
</pre></blockquote>
 
199
 
 
200
This creates two different files; a C/C++ source file <tt>example_wrap.c</tt> or
 
201
<tt>example_wrap.cxx</tt> and numerous Java files.   The generated
 
202
C/C++ source file contains the JNI wrapper code that needs to be compiled and linked with the
 
203
rest of your C/C++ application. 
 
204
 
 
205
<p>
 
206
The name of the wrapper file is derived from the name of the input file.  For example, if the
 
207
input file is <tt>example.i</tt>, the name of the wrapper file is <tt>example_wrap.c</tt>.
 
208
To change this, you can use the <tt>-o</tt> option. 
 
209
It is also possible to change the <a href="SWIG.html#output">output directory </a> that the Java files are generated into using <tt>-outdir</tt>.
 
210
 
 
211
<a name="commandline"></a>
 
212
<a name="n5"></a><H3>17.2.2 Additional Commandline Options</H3>
 
213
 
 
214
 
38
215
The following table list the additional commandline options available for the Java module. They can also be seen by using: 
39
216
<blockquote><pre>swig -java -help 
40
217
</pre></blockquote>
45
222
</tr>
46
223
 
47
224
<tr>
48
 
<td>-jnic</td>
49
 
<td> use c syntax for JNI calls (default depends on -c++ flag)</td>
50
 
</tr>
51
 
 
52
 
<tr>
53
 
<td>-jnicpp</td>
54
 
<td> use C++ syntax for JNI calls (default depends on -c++ flag)</td>
55
 
</tr>
56
 
 
57
 
<tr>
58
 
<td>-module &lt;module&gt;</td>
59
 
<td>set name of module</td>
60
 
</tr>
61
 
 
62
 
<tr>
63
 
<td>-package &lt;java package&gt;</td>
64
 
<td>set the name of the package for the generated classes</td>
65
 
</tr>
66
 
 
67
 
<tr>
68
 
<td>-shadow</td>
69
 
<td>generate shadow classes</td>
70
 
</tr>
71
 
 
72
 
<tr>
73
 
<td>-nofinalize</td>
74
 
<td>do not generate finalizer methods in shadow classes</td>
 
225
<td>-package &lt;name&gt;</td>
 
226
<td>set name of the Java package to &lt;name&gt;</td>
 
227
</tr>
 
228
 
 
229
<tr>
 
230
<td>-noproxy</td>
 
231
<td>generate the low-level functional interface instead of proxy classes </td>
75
232
</tr>
76
233
 
77
234
</table>
78
235
<br>
79
236
Their use will become clearer by the time you have finished reading this section on SWIG and Java.
80
237
 
81
 
<a name="n102"></a><h3> Getting the right header files</h3>
82
 
In order to compile, you need to locate the "jni.h" and "md.h" header files which are part of the JDK. They are usually in directories like this:<p>
 
238
<a name="getting_right_headers"></a>
 
239
<a name="n6"></a><H3>17.2.3 Getting the right header files</H3>
 
240
 
 
241
 
 
242
In order to compile the C/C++ wrappers, the compiler needs the <tt>jni.h</tt> and <tt>jni_md.h</tt> header files which are part of the JDK. 
 
243
They are usually in directories like this:<p>
83
244
<p>
84
245
<blockquote><pre>
85
246
/usr/java/include
88
249
<p>
89
250
 
90
251
The exact location may vary on your machine, but the above locations are typical. <p>
91
 
<a name="n103"></a><h3> Compiling a dynamic module</h3>
92
 
The JNI code exists in a dynamic module or shared object and gets loaded by the JVM. To build a shared object file, you need to compile your module in a manner similar to the following (shown for Solaris):<p>
 
252
 
 
253
<a name="compiling_dynamic"></a>
 
254
<a name="n7"></a><H3>17.2.4 Compiling a dynamic module</H3>
 
255
 
 
256
 
 
257
The JNI code exists in a dynamic module or shared library (DLL on Windows) and gets loaded by the JVM. 
 
258
To build a shared library file, you need to compile your module in a manner similar to the following (shown for Solaris):<p>
93
259
<p>
94
260
<blockquote><pre>
95
 
$ swig -java -shadow example.i
 
261
$ swig -java example.i
96
262
$ gcc -c example_wrap.c  -I/usr/java/include -I/usr/java/include/solaris
97
263
$ ld -G example_wrap.o  -o libexample.so
98
264
 
99
265
</pre></blockquote>
100
 
Unfortunately, the process of building a shared object file varies on every single machine so you may need to read up on the man pages for your C compiler and linker.<p>
101
 
<p>
102
 
When building a dynamic module, the name of the output file is important. If the name of your SWIG module is "<tt>example</tt>", the name of the corresponding object file should be "<tt>libexample.so</tt>" (or equivalent depending on your machine, see <a href="#n10">Dynamic linking problems</a> for more information). The name of the module is specified using the <tt>%module</tt> directive or<tt> -module</tt> command line option.<p>
103
 
<p>
104
 
 
105
 
<a name="n104"></a><h3> Using your module</h3>
106
 
To use your module in Java, simply use Java's <tt>import</tt> command and <tt>System.loadLibrary</tt> method in a Java class:<p>
 
266
The exact commands for doing this vary from platform to platform. 
 
267
However, SWIG tries to guess the right options when it is installed.  Therefore, 
 
268
you may want to start with one of the examples in the <tt>Examples/java</tt> 
 
269
directory.   If that doesn't work, you will need to read the man-pages for
 
270
your compiler and linker to get the right set of options.  You might also
 
271
check the <a href="http://swig.cs.uchicago.edu/cgi-bin/wiki.pl">SWIG Wiki</a> for
 
272
additional information.
 
273
<p>
 
274
 
 
275
The name of the shared library output file is important. 
 
276
If the name of your SWIG module is "<tt>example</tt>", the name of the corresponding shared library file should be "<tt>libexample.so</tt>" (or equivalent depending on your machine, see <a href="#dynamic_linking_problems">Dynamic linking problems</a> for more information). 
 
277
The name of the module is specified using the <tt>%module</tt> directive or<tt> -module</tt> command line option.<p>
 
278
<p>
 
279
 
 
280
<a name="using_module"></a>
 
281
<a name="n8"></a><H3>17.2.5 Using your module</H3>
 
282
 
 
283
 
 
284
To load your shared native library module in Java, simply use Java's <tt>System.loadLibrary</tt> method in a Java class:<p>
107
285
<p>
108
286
<blockquote><pre>
109
287
// main.java
110
 
import example;
111
288
 
112
289
public class main {
113
290
  static {
128
305
$
129
306
</pre></blockquote>
130
307
 
131
 
<a name="n105"></a><h3> Compilation problems and compiling with C++</h3>
132
 
For the most part, compiling a Java module is straightforward, but there are a number of potential problems :<p>
133
 
<p>
134
 
<ul>
135
 
<li>In order to build C++ modules, you may need to link with the C++ compile using a command like `<tt>c++ -shared example_wrap.o example.o -o libexample.so</tt>'
136
 
<li>If building a dynamic C++ module using g++, you may also need to link against <tt>libgcc.a</tt>, <tt>libg++.a</tt>, and <tt>libstc++.a</tt> libraries.
137
 
<li>Make sure you are using the version of JDK header files matches the version of Java that you are running.
138
 
</ul>
139
 
 
140
 
<a name="n2"></a><h2>Building Java Extensions under Windows 95/NT</h2>
141
 
Building a SWIG extension to Java under Windows 95/NT is roughly similar to the process used with Unix.  You will want to produce a DLL that can be loaded by the Java Virtual Machine.  This section covers the process of using SWIG with Microsoft Visual C++ 6 although the procedure may be similar with other compilers.  In order to build extensions, you will need to have a JDK installed on your machine in order to read the JNI header files.<p>
142
 
<a name="n106"></a><h3> Running SWIG from Developer Studio</h3>
143
 
If you are developing your application within Microsoft developer studio, SWIG can be invoked as a custom build option. The process roughly follows these steps:<p>
 
308
If it doesn't work have a look at the following section which discusses problems loading the shared library.
 
309
 
 
310
<a name="dynamic_linking_problems"></a>
 
311
<a name="n9"></a><H3>17.2.6 Dynamic linking problems</H3>
 
312
 
 
313
 
 
314
As shown in the previous section the code to load a native library (shared library) is <tt>System.loadLibrary("name")</tt>. 
 
315
This can fail with an UnsatisfiedLinkError exception and can be due to a number of reasons.
 
316
<p>
 
317
You may get an exception similar to this:
 
318
<blockquote><pre>
 
319
$ java main
 
320
Exception in thread "main" java.lang.UnsatisfiedLinkError: no example in java.library.path
 
321
        at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1312)
 
322
        at java.lang.Runtime.loadLibrary0(Runtime.java:749)
 
323
        at java.lang.System.loadLibrary(System.java:820)
 
324
        at main.<clinit>(main.java:5)
 
325
</pre></blockquote>
 
326
 
 
327
The most common cause for this is an incorrect naming of the native library for the name passed to the <tt>loadLibrary</tt> function. 
 
328
The string passed to the <tt>loadLibrary</tt> function must not include the file extension name in the string, that is <i>.dll</i> or <i>.so</i>. 
 
329
The string must be <i>name</i> and not <i>libname</i> for all platforms. 
 
330
On Windows the native library must then be called <i>name.dll</i> and on most Unix systems it must be called <i>libname.so</i>. 
 
331
If you are debugging using <tt> java -debug</tt>, then the native library must be called <i>name_g.dll</i> on Windows and <i>libname_g.so</i> on Unix.
 
332
<p>
 
333
 
 
334
Another common reason for the native library not loading is because it is not in your path. 
 
335
On Windows make sure the <i>path</i> environment variable contains the path to the native library. 
 
336
On Unix make sure that your <i>LD_LIBRARY_PATH</i> contains the path to the native library. 
 
337
Adding paths to <i>LD_LIBRARY_PATH</i> can slow down other programs on your system so you may want to consider alternative approaches.
 
338
For example you could recompile your native library with extra path information using <tt>-rpath</tt> if you're using GNU, see the GNU linker documentation (<tt>ld</tt> man page).
 
339
You could use a command such as <tt>ldconfig</tt> (Linux) or
 
340
<tt>crle</tt> (Solaris) to add additional search paths to the default
 
341
system configuration (this requires root access and you will need to read the man pages).
 
342
 
 
343
<p>
 
344
 
 
345
The native library will also not load if there are any unresolved symbols in the compiled C/C++ code. 
 
346
The following exception is indicative of this:
 
347
 
 
348
<blockquote><pre>
 
349
$ java main
 
350
Exception in thread "main" java.lang.UnsatisfiedLinkError: libexample.so: undefined symbol: fact
 
351
        at java.lang.ClassLoader$NativeLibrary.load(Native Method)
 
352
        at java.lang.ClassLoader.loadLibrary0(ClassLoader.java, Compiled Code)
 
353
        at java.lang.ClassLoader.loadLibrary(ClassLoader.java, Compiled Code)
 
354
        at java.lang.Runtime.loadLibrary0(Runtime.java, Compiled Code)
 
355
        at java.lang.System.loadLibrary(System.java, Compiled Code)
 
356
        at main.<clinit>(main.java:5)
 
357
$
 
358
</pre></blockquote>
 
359
 
 
360
This error usually indicates that you forgot to include some object files or libraries in the linking of the native library file.  
 
361
Make sure you compile both the SWIG wrapper file and the code you are wrapping into the native library file.  
 
362
Also make sure you pass all of the required libraries to the linker.  
 
363
The <tt>java -verbose:jni</tt> commandline switch is also a great way to get more information on unresolved symbols.
 
364
One last piece of advice is to beware of the common faux pas of having more than one native library version in your path.
 
365
<p>
 
366
 
 
367
In summary, ensure that you are using the correct C/C++ compiler and linker combination and options for successful native library loading. 
 
368
If you are using the examples that ship with SWIG, then the Examples/Makefile must have these set up correctly for your system. 
 
369
The SWIG installation package makes a best attempt at getting these correct but does not get it right 100% of the time.
 
370
The <a href="http://swig.cs.uchicago.edu/cgi-bin/wiki.pl">SWIG Wiki</a> also has some settings for commonly used compiler and operating system combinations.
 
371
The following section also contains some C++ specific linking problems and solutions.
 
372
 
 
373
 
 
374
<a name="compilation_problems_cpp"></a>
 
375
<a name="n10"></a><H3>17.2.7 Compilation problems and compiling with C++</H3>
 
376
 
 
377
 
 
378
On most machines, shared library files should be linked using the C++
 
379
compiler.  For example:
 
380
 
 
381
<p>
 
382
<blockquote><pre>% swig -c++ -java example.i
 
383
% g++ -c -fpic example.cxx
 
384
% g++ -c -fpic example_wrap.cxx -I/usr/java/j2sdk1.4.1/include -I/usr/java/j2sdk1.4.1/include/linux
 
385
% g++ -shared example.o example_wrap.o -o libexample.so
 
386
</pre></blockquote>
 
387
 
 
388
In addition to this, you may need to include additional library
 
389
files to make it work.  For example, if you are using the Sun C++ compiler on
 
390
Solaris, you often need to add an extra library <tt>-lCrun</tt> like this:
 
391
 
 
392
<p>
 
393
<blockquote><pre>% swig -c++ -java example.i
 
394
% CC -c example.cxx
 
395
% CC -c example_wrap.cxx -I/usr/java/include -I/usr/java/include/solaris
 
396
% CC -G example.o example_wrap.o -L/opt/SUNWspro/lib -o libexample.so -lCrun
 
397
</pre></blockquote>
 
398
 
 
399
If you aren't entirely sure about the linking for C++, you
 
400
might look at an existing C++ program.  On many Unix machines, the
 
401
<tt>ldd</tt> command will list library dependencies.  This should give
 
402
you some clues about what you might have to include when you link your
 
403
shared library. For example:
 
404
 
 
405
<blockquote>
 
406
<pre>
 
407
$ ldd swig
 
408
        libstdc++-libc6.1-1.so.2 => /usr/lib/libstdc++-libc6.1-1.so.2 (0x40019000)
 
409
        libm.so.6 => /lib/libm.so.6 (0x4005b000)
 
410
        libc.so.6 => /lib/libc.so.6 (0x40077000)
 
411
        /lib/ld-linux.so.2 => /lib/ld-linux.so.2 (0x40000000)
 
412
$
 
413
</pre>
 
414
</blockquote>
 
415
 
 
416
Finally make sure the version of JDK header files matches the version of Java that you are running as incompatibilities could lead to compilation problems or unpredictable behaviour.
 
417
 
 
418
 
 
419
<a name="building_windows"></a>
 
420
<a name="n11"></a><H3>17.2.8 Building on Windows</H3>
 
421
 
 
422
 
 
423
Building on Windows is roughly similar to the process used with Unix.  
 
424
You will want to produce a DLL that can be loaded by the Java Virtual Machine.  
 
425
This section covers the process of using SWIG with Microsoft Visual C++ 6 although the procedure may be similar with other compilers.  
 
426
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.<p>
 
427
 
 
428
<a name="visual_studio"></a>
 
429
<a name="n12"></a><H4>17.2.8.1 Running SWIG from Visual Studio</H4>
 
430
 
 
431
 
 
432
If you are developing your application within Microsoft Visual studio, SWIG can be invoked as a custom build option. 
 
433
The Examples\java directory has a few <a href="Windows.html#examples">Windows Examples</a> containing Visual Studio project (.dsp) files.
 
434
The process to re-create the project files for a C project are roughly:<p>
144
435
<p>
145
436
<ul>
146
437
<li>Open up a new workspace and use the AppWizard to select a DLL project.
147
 
<li>Add both the SWIG interface file (the .i file), any supporting C files, and the name of the wrapper file that will be created by SWIG (ie. <tt>example_wrap.c</tt>).   Note: If using C++, choose a different suffix for the wrapper file <tt>example_wrap.cxx</tt>. Don't worry if the wrapper file doesn't exist yet--Developer Studio will keep a reference to it.
 
438
<li>Add both the SWIG interface file (the .i file), any supporting C files, and the name of the wrapper file that will be created by SWIG (ie. <tt>example_wrap.c</tt>).   
 
439
Don't worry if the wrapper file doesn't exist yet--Visual Studio will keep a reference to it.
148
440
<li>Select the SWIG interface file and go to the settings menu. Under settings, select the "Custom Build" option.
149
441
<li>Enter "SWIG" in the description field.
150
 
<li>Enter "<tt>swig -java -shadow -o $(ProjDir)\$(InputName)_wrap.c $(InputPath)</tt>" in the "Build command(s) field"
 
442
<li>Enter "<tt>swig -java -o $(ProjDir)\$(InputName)_wrap.c $(InputPath)</tt>" in the "Build command(s) field"
151
443
<li>Enter "<tt>$(ProjDir)\$(InputName)_wrap.c</tt>" in the "Output files(s) field".
152
444
<li>Next, select the settings for the entire project and go to C/C++ tab and select the Preprocessor category . Add the include directories to the JNI header files under "Additional include directories", eg "C:\jdk1.3\include,C:\jdk1.3\include\win32".
153
445
<li>Next, select the settings for the entire project and go to Link tab and select the General category. Set the name of the output file to match the name of your Java module (ie. example.dll).
156
448
<li>Build your project.
157
449
</ul>
158
450
<p>
159
 
Now, assuming all went well, SWIG will be automatically invoked when you build your project.  When doing a build, any changes made to the interface file will result in SWIG being automatically invoked to produce a new version of the wrapper file.  The Java classes that SWIG output should also be compiled into .class files. To run the native code in the DLL (example.dll), make sure that it is in your path then run your Java program which uses it, as described in the previous section. If the library fails to load have a look at <a href="#n10">Dynamic linking problems</a>.
 
451
Note: If using C++, choose a C++ suffix for the wrapper file, for example <tt>example_wrap.cxx</tt>.
 
452
Use <tt>_wrap.cxx</tt> instead of <tt>_wrap.c</tt> in the instructions above and add -c++ when invoking swig.
160
453
<p>
161
 
 
162
 
<a name="n107"></a><h3> Using NMAKE</h3>
163
 
Alternatively, SWIG extensions can be built by writing a Makefile for NMAKE.   Make sure the environment variables for MSVC++ are available and the MSVC++ tools are in your path.   Now, just write a short Makefile like this :<p>
 
454
Now, assuming all went well, SWIG will be automatically invoked when you build your project.  
 
455
When doing a build, any changes made to the interface file will result in SWIG being automatically invoked to produce a new version of the wrapper file.  
 
456
The Java classes that SWIG output should also be compiled into .class files. 
 
457
To run the native code in the DLL (example.dll), make sure that it is in your path then run your Java program which uses it, as described in the previous section. 
 
458
If the library fails to load have a look at <a href="#dynamic_linking_problems">Dynamic linking problems</a>.
 
459
 
 
460
<a name="nmake"></a>
 
461
<a name="n13"></a><H4>17.2.8.2 Using NMAKE</H4>
 
462
 
 
463
 
 
464
Alternatively, a Makefile for use by NMAKE can be written.   
 
465
Make sure the environment variables for MSVC++ are available and the MSVC++ tools are in your path.   
 
466
Now, just write a short Makefile like this :<p>
164
467
<p>
165
468
<blockquote><pre>
166
 
# Makefile for building a Java extension
 
469
# Makefile for using SWIG and Java for C code
167
470
 
168
471
SRCS          = example.c
169
472
IFILE         = example
199
502
JAVA_INCLUDE    = -ID:\jdk1.3\include -ID:\jdk1.3\include\win32
200
503
 
201
504
java::
202
 
        swig -java -shadow -o $(WRAPFILE) $(INTERFACE)
 
505
        swig -java -o $(WRAPFILE) $(INTERFACE)
203
506
        $(CC) $(CFLAGS) $(JAVA_INCLUDE) $(SRCS) $(WRAPFILE)
204
507
        set LIB=$(TOOLS)\lib
205
508
        $(LINK) $(LOPT) -out:example.dll $(LIBS) example.obj example_wrap.obj
206
509
        javac *.java
207
510
</pre></blockquote>
208
511
<p>
209
 
To build the extension, run NMAKE (you may need to run <tt>vcvars32</tt> first). This is a pretty simplistic Makefile, but hopefully its enough to get you started.   <p>
210
 
 
211
 
<a name="n3"></a><h2>The low-level Java/C interface</h2>
212
 
The SWIG Java module is based upon a basic low-level interface that provides access to C functions, variables, constants, and C++ classes. This low-level interface is not the recommended way to use SWIG with Java; shadow classes are the recommended way. This low-level interface is used by the shadow class interface so it is used behind the scenes.<p>
213
 
<p>
214
 
<a name="n108"></a><h3> Modules and the module class</h3>
215
 
The SWIG <tt>%module</tt> directive specifies the name of the Java module. If you specified `<tt>%module example</tt>', then everything found in a SWIG interface file will be contained within the Java module class which in this case will be called `<tt>example</tt>'.  In other words the module class contains all the C/C++ functions and accessor functions to variables that have been wrapped by SWIG. Make sure you don't use the same name as a Java keyword for your module name else the Java output will not compile.<p>
216
 
 
217
 
<a name="n109"></a><h3> Functions</h3>
218
 
C/C++ functions are mapped directly into a matching method in a Java class named after the module name. For example :<p>
219
 
<p>
220
 
 
221
 
<blockquote><pre>
222
 
%module example
223
 
extern int fact(int n);
224
 
</pre></blockquote>
225
 
Will produce the following JNI c function:
226
 
<blockquote><pre>
227
 
JNIEXPORT jint JNICALL Java_example_fact(JNIEnv *jenv, jclass jcls, jint jarg0) {
228
 
</pre></blockquote>
229
 
This will in turn call the desired <tt>fact</tt> function. The JNI naming mangling isn't pretty, but you can see from the above that the native function call is expecting a class 'example'. SWIG outputs the JNI Java code into the example class:
230
 
<blockquote><pre>
231
 
public class example  {
232
 
  public final static native int fact(int jarg0);
 
512
To build the DLL and compile the java code, run NMAKE (you may need to run <tt>vcvars32</tt> first). 
 
513
This is a pretty simplistic Makefile, but hopefully its enough to get you started.
 
514
Of course you may want to make changes for it to work for C++ by adding in the -c++ command line switch for swig and replacing .c with .cxx.
 
515
<p>
 
516
 
 
517
 
 
518
<a name="java_basic_tour"></a>
 
519
<a name="n14"></a><H2>17.3 A tour of basic C/C++ wrapping</H2>
 
520
 
 
521
 
 
522
By default, SWIG attempts to build a natural Java interface
 
523
to your C/C++ code.  Functions are wrapped as functions, classes are wrapped as classes, 
 
524
variables are wrapped with JavaBean type getters and setters and so forth.
 
525
This section briefly covers the essential aspects of this wrapping.
 
526
 
 
527
<a name="module_packages_classes"></a>
 
528
<a name="n15"></a><H3>17.3.1 Modules, packages and generated Java classes</H3>
 
529
 
 
530
 
 
531
The SWIG <tt>%module</tt> directive specifies the name of the Java
 
532
module. When you specify `<tt>%module example</tt>', the <i>module name</i>
 
533
determines the name of some of the generated files in the module.
 
534
The generated code consists of a <i>module class</i> file <tt>example.java</tt>, an
 
535
<i>intermediary JNI class</i> file, <tt>exampleJNI.java</tt> as well as numerous other Java <i>proxy class</i> files.
 
536
Each proxy class is named after the structs, unions and classes you are wrapping.
 
537
You may also get a <i>constants interface</i> file if you are wrapping any enumerations or constants, for example <tt>exampleConstants.java</tt>.
 
538
When choosing a module name, make sure you don't use the same name as one of the generated
 
539
proxy class files nor a Java keyword. Sometimes a C/C++ type cannot be wrapped by a proxy class, for 
 
540
example a pointer to a primitive type. In these situations a <i>type wrapper class</i> is generated.
 
541
Details of all these generated classes will unfold as you read this section.
 
542
<p>
 
543
 
 
544
The JNI (C/C++) code is generated into a file which also contains the module name, for example <tt>example_wrap.cxx</tt>
 
545
or </tt>example_wrap.c</tt>. These C or C++ files complete the contents of the module.
 
546
<p>
 
547
 
 
548
The generated Java classes can be placed into a Java package by using the <tt>-package</tt> commandline option.
 
549
This is often combined with the <tt>-outdir</tt> to specify a package directory for generating the Java files.
 
550
 
 
551
<blockquote><pre>
 
552
swig -java -package com.bloggs.swig -outdir com/bloggs/swig example.i
 
553
</pre></blockquote>
 
554
 
 
555
SWIG won't create the directory, so make sure it exists beforehand.
 
556
 
 
557
<a name="functions"></a>
 
558
<a name="n16"></a><H3>17.3.2 Functions</H3>
 
559
 
 
560
 
 
561
There is no such thing as a global Java function so global C functions are wrapped as static methods in 
 
562
the module class. For example,
 
563
 
 
564
<p>
 
565
<blockquote><pre>%module example
 
566
int fact(int n);
 
567
 
 
568
</pre></blockquote>
 
569
 
 
570
creates a static function that works exactly like you think it might:<p>
 
571
 
 
572
<blockquote><pre>
 
573
public class example {
 
574
  public static int fact(int n) {
 
575
    // makes call using JNI to the C function
 
576
  }
233
577
}
234
578
</pre></blockquote>
235
579
 
236
 
It can be used as follows from Java:<p>
 
580
 
 
581
<p>
 
582
The Java class <tt>example</tt> is the <i>module class</i>. The function can be used as follows from Java:<p>
237
583
 
238
584
<blockquote><pre>
239
585
System.out.println(example.fact(4));
240
586
</pre></blockquote>
241
587
 
242
 
<a name="n110"></a><h3> Variable Linking</h3>
243
 
SWIG provides access to C/C++ global variables through the class named after the module name, in other words all global variables are wrapped into the module class. Java does not allow the overriding of the dot operator so all variables are accessed through getters and setters. For example: <p>
 
588
 
 
589
<a name="global_variables"></a>
 
590
<a name="n17"></a><H3>17.3.3 Global variables</H3>
 
591
 
 
592
 
 
593
C/C++ global variables are fully supported by SWIG.  
 
594
Java does not allow the overriding of the dot operator so all variables are accessed through getters and setters. 
 
595
Again because there is no such thing as a
 
596
Java global variable, access to C/C++ global variables is done through static getter and setter functions in the module class.
 
597
 
244
598
<blockquote><pre>
245
 
/* SWIG interface file with global variables */
 
599
// SWIG interface file with global variables
246
600
%module example
247
601
...
248
602
extern int My_variable;
 
603
extern double density;
249
604
...
250
605
</pre></blockquote>
 
606
 
251
607
<p>
 
608
 
252
609
Now in Java :<p>
253
610
<p>
254
 
<blockquote><pre>
255
 
// Print out the value of a c global variable
256
 
System.out.println("My Variable = " + example.get_My_variable());
257
 
 
258
 
//Set the value of a C global variable
259
 
example.set_My_variable(100);
260
 
</pre></blockquote>
261
 
The value returned by the getter will always be up to date even if the value is changed in c. The setter will not be generated if the variable is a c 'const'.<p>
262
 
 
263
 
<a name="n111"></a><h3> Enums</h3>
264
 
SWIG will wrap enumerations. They appear as public final static Java variables. The Java enum names match the C/C++ enum names. For example, the following C enum:<p>
265
 
<blockquote><pre>
266
 
enum color { RED, BLUE, GREEN };
267
 
</pre></blockquote>
268
 
 
269
 
will be wrapped with the following Java:
270
 
<blockquote><pre>
271
 
public class example  {
272
 
... maybe some other functions ...
273
 
  public final static native int get_RED();
274
 
  public final static native int get_BLUE();
275
 
  public final static native int get_GREEN();
276
 
  // enums and constants
277
 
  public final static int RED = get_RED();
278
 
  public final static int BLUE = get_BLUE();
279
 
  public final static int GREEN = get_GREEN();
280
 
}
281
 
</pre></blockquote>
282
 
 
283
 
<a name="n112"></a><h3> Constants</h3>
284
 
C/C++ constants (from a #define) are wrapped by public final static Java variables. These constants are given the same name as the corresponding C constant. For example, the following C:<p>
285
 
<blockquote><pre>
286
 
#define    ICONST      42
287
 
#define    FCONST      2.1828
288
 
#define    CCONST      'x'
289
 
#define    SCONST      "Hello World"
290
 
</pre></blockquote>
291
 
will be wrapped with the following Java:
292
 
<blockquote><pre>
293
 
public final static int ICONST = 42;
294
 
public final static double FCONST = 2.1828;
295
 
public final static String CCONST = "x";
296
 
public final static String SCONST = "Hello World";
297
 
</pre></blockquote>
298
 
 
299
 
<a name="n113"></a><h3> Pointers</h3>
300
 
All c pointers are treated as Java longs in the low-level interface. For example:<p>
301
 
<blockquote><pre>
302
 
int* pointer_fn(short* a, int* b, long* c);
303
 
</pre></blockquote>
304
 
will produce the following Java function:
305
 
<blockquote><pre>
306
 
public final static native long pointer_fn(long jarg0, long jarg1, long jarg2);
307
 
</pre></blockquote>
308
 
Unlike other language modules, no SWIG pointer library exists yet for the Java module. Until this is written it does restrict the functions that can be usefully used from Java. In the above <tt>pointer_fn</tt>, any long representing a c pointer can be passed to other c functions, but any value that the pointer points to cannot be accessed from Java without writing and using some accessor functions, for example:<p>
309
 
<blockquote><pre>
310
 
/* c accessor function for reading return values that are int pointers */
311
 
int getIntValue(int *ptr) {return *ptr;};
312
 
 
313
 
int* pointer_fn();
314
 
</pre></blockquote>
315
 
The return value can then be read from Java, for example:
316
 
<blockquote><pre>
317
 
long integerPtr = example.pointer_fn();
318
 
System.out.println("return value=" + example.getIntValue(integerPtr));
319
 
</pre></blockquote>
320
 
 
321
 
Pointers that are returned in one of the parameter arguments are more difficult and other workarounds are necessary. One method is to write a c function which returns the desired value after calling the appropriate function. However, as the section on shadow classes demonstrates, the situation is a lot better when using shadow classes.
322
 
 
323
 
<p>
324
 
Another alternative is to use the typemaps.i library. This file has examples to demonstrate, but essentially if you use the typemaps in this library you can use real values from Java where a pointer is required in c. When the pointer is an output from the c function, a Java array is used. The value that the pointer is pointing to is placed into the array which can be read by the calling function.
325
 
 
326
 
<p>
327
 
<a name="n114"></a><h3> Structures </h3>
328
 
The low-level SWIG interface only provides a simple interface to C structures. For example :<p>
 
611
 
 
612
<blockquote><pre>
 
613
// Print out value of a C global variable
 
614
System.out.println("My_variable = " + example.getMy_variable());
 
615
// Set the value of a C global variable
 
616
example.setDensity(0.8442);
 
617
</pre></blockquote>
 
618
 
 
619
The value returned by the getter will always be up to date even if the value is changed in C. 
 
620
Note that the getters and setters produced follow the JavaBean property design pattern. 
 
621
That is the first letter of the variable name is capitalized and preceded with set or get.
 
622
If you have the misfortune of wrapping two variables that differ only in the capitalization of their first letters,
 
623
use %rename to change one of the variable names. For example:
 
624
 
 
625
<blockquote><pre>
 
626
%rename Clash RenamedClash;
 
627
float Clash;
 
628
int clash;
 
629
</pre></blockquote>
 
630
 
 
631
<p>
 
632
If a variable is declared as <tt>const</tt>, it is wrapped as a read-only variable.  
 
633
That is only a getter is produced.
 
634
 
 
635
<p>
 
636
To make ordinary variables read-only, you can use the <tt>%immutable</tt> directive. For example:
 
637
 
 
638
<blockquote>
 
639
<pre>
 
640
%immutable;
 
641
extern char *path;
 
642
%mutable;
 
643
</pre>
 
644
</blockquote>
 
645
 
 
646
The <tt>%immutable</tt> directive stays in effect until it is explicitly disabled using
 
647
<tt>%mutable</tt>.
 
648
 
 
649
<p>
 
650
If you just want to make a specific variable immutable, supply a declaration name.  For example:
 
651
 
 
652
<blockquote>
 
653
<pre>
 
654
%immutable path;
 
655
...
 
656
extern char *path;      // Read-only (due to %immutable)
 
657
</pre>
 
658
</blockquote>
 
659
 
 
660
 
 
661
<a name="constants"></a>
 
662
<a name="n18"></a><H3>17.3.4 Constants</H3>
 
663
 
 
664
 
 
665
C/C++ constants are wrapped as Java static final variables.
 
666
To create a constant, use <tt>#define</tt> or the
 
667
<tt>%constant</tt> directive.  For example:
 
668
 
 
669
<blockquote>
 
670
<pre>
 
671
#define PI 3.14159
 
672
#define VERSION "1.0"
 
673
%constant int FOO = 42;
 
674
%constant const char *path = "/usr/local";
 
675
</pre>
 
676
</blockquote>
 
677
 
 
678
By default the generated static final variables are initialised by making a JNI call to get their value.
 
679
The constants are generated into the constants interface and look like this:
 
680
 
 
681
<blockquote><pre>
 
682
public interface exampleConstants {
 
683
  // enums and constants
 
684
  public final static double PI = exampleJNI.get_PI();
 
685
  public final static String VERSION = exampleJNI.get_VERSION();
 
686
  public final static int FOO = exampleJNI.get_FOO();
 
687
  public final static String path = exampleJNI.get_path();
 
688
}
 
689
</pre></blockquote>
 
690
 
 
691
These are runtime constants. They are not compiler constants that can, for example, be used 
 
692
in a switch statement. This can be changed by using the <tt>%javaconst(flag)</tt> directive. It works like all
 
693
the other <a href="Customization.html#features">%feature directives</a>. The default is <tt>%javaconst(0)</tt>. 
 
694
It is possible to initialize all wrapped constants from pure Java code by placing a <tt>%javaconst(1)</tt> <b>before</b> SWIG parses the constants.
 
695
Putting it at the top of your interface file would ensure this.
 
696
Here is an example:
 
697
 
 
698
<blockquote><pre>
 
699
%javaconst(1);
 
700
%javaconst(0) BIG;
 
701
#define BIG 1000LL
 
702
#define EXPRESSION (0x100+5)
 
703
</pre></blockquote>
 
704
 
 
705
generates:
 
706
 
 
707
<blockquote><pre>
 
708
public interface exampleConstants {
 
709
  // enums and constants
 
710
  public final static long BIG = exampleJNI.get_BIG();
 
711
  public final static int EXPRESSION = (0x100+5);
 
712
}
 
713
</pre></blockquote>
 
714
 
 
715
Be careful using the <tt>%javaconst(1)</tt> directive as not all C code will compile as Java code. For example the 
 
716
<tt>1000LL</tt> value for the <tt>BIG</tt> constant above would not generate valid Java code. 
 
717
The example demonstrates how you can target particular constants (<tt>BIG</tt>) with <tt>%javaconst</tt>.
 
718
 
 
719
<p>
 
720
Note:  declarations declared as <tt>const</tt> are wrapped as read-only variables and
 
721
will be accessed using a getter as described in the previous section.  They
 
722
are not wrapped as constants.
 
723
 
 
724
<p>
 
725
<b>Compatibility Note:</b> In SWIG-1.3.19 and earlier releases, the constants were generated into the module class and the constants interface didn't exist.
 
726
Backwards compatibility is maintained as the module class implements the constants interface (even though some consider this type of interface implementation to be bad practice):
 
727
<blockquote><pre>
 
728
public class example implements exampleConstants {
 
729
}
 
730
</pre></blockquote>
 
731
 
 
732
You thus have the choice of accessing these constants from either the module class or the constants interface, for example,
 
733
<tt>example.EXPRESSION</tt> or <tt>exampleConstants.EXPRESSION</tt>.
 
734
 
 
735
 
 
736
<a name="enumerations"></a>
 
737
<a name="n19"></a><H3>17.3.5 Enumerations</H3>
 
738
 
 
739
 
 
740
Enumerations are wrapped as final static integers in Java and are also initialised using a JNI call. For example:
 
741
 
 
742
<blockquote>
 
743
<pre>
 
744
enum Beverage { ALE, LAGER=10, STOUT, PILSNER };
 
745
</pre>
 
746
</blockquote>
 
747
 
 
748
is wrapped into the constants interface, in a similar manner as constants (see previous section):
 
749
 
 
750
<blockquote><pre>
 
751
public interface exampleConstants {
 
752
  // enums and constants
 
753
  public final static int ALE = exampleJNI.get_ALE();
 
754
  public final static int LAGER = exampleJNI.get_LAGER();
 
755
  public final static int STOUT = exampleJNI.get_STOUT();
 
756
  public final static int PILSNER = exampleJNI.get_PILSNER();
 
757
}
 
758
</pre></blockquote>
 
759
 
 
760
The <tt>%javaconst(flag)</tt> directive introduced in the previous section on constants can also be used with enums,
 
761
thereby also allowing enum values to be used in Java switch statements. 
 
762
As is the case for constants, the default is <tt>%javaconst(0)</tt> as not all C values will compile as Java code.
 
763
However, it is recommended to add in a <tt>%javaconst(1)</tt> directive at the top of your 
 
764
interface file as it is only on very rare occasions that this will produce code that won't compile under Java.
 
765
Example usage:
 
766
 
 
767
<blockquote>
 
768
<pre>
 
769
%javaconst(1);
 
770
%javaconst(0) PILSNER;
 
771
enum Beverage { ALE, LAGER=10, STOUT, PILSNER };
 
772
</pre>
 
773
</blockquote>
 
774
 
 
775
generates:
 
776
 
 
777
<blockquote><pre>
 
778
public interface exampleConstants {
 
779
  // enums and constants
 
780
  public final static int ALE = 0;
 
781
  public final static int LAGER = 10;
 
782
  public final static int STOUT = LAGER+1;
 
783
  public final static int PILSNER = exampleJNI.get_PILSNER();
 
784
}
 
785
</pre></blockquote>
 
786
 
 
787
As in the case of constants, you can access them through either the module class or the constants interface, for example, <tt>example.ALE</tt> or <tt>exampleConstants.ALE</tt>.
 
788
 
 
789
<p>
 
790
For enums, make sure that the definition of the enumeration actually appears in a header
 
791
file or in the wrapper file somehow---if you just have an enum in a SWIG interface without
 
792
also telling the C compiler about it, the wrapper code won't compile.
 
793
 
 
794
<p>
 
795
 
 
796
<a name="pointers"></a>
 
797
<a name="n20"></a><H3>17.3.6 Pointers</H3>
 
798
 
 
799
 
 
800
C/C++ pointers are fully supported by SWIG.  Furthermore, SWIG has no problem working with
 
801
incomplete type information.  Here is a rather simple interface:
 
802
 
 
803
<blockquote>
 
804
<pre>
 
805
%module example
 
806
 
 
807
FILE *fopen(const char *filename, const char *mode);
 
808
int fputs(const char *, FILE *);
 
809
int fclose(FILE *);
 
810
</pre>
 
811
</blockquote>
 
812
 
 
813
When wrapped, you will be able to use the functions in a natural way from Java. For example:
 
814
 
 
815
<blockquote>
 
816
<pre>
 
817
SWIGTYPE_p_FILE f = example.fopen("junk","w");
 
818
example.fputs("Hello World\n", f);
 
819
example.fclose(f);
 
820
</pre>
 
821
</blockquote>
 
822
 
 
823
C pointers in the Java module are stored in a Java <tt>long</tt> and cross the JNI boundary held within this 64 bit number.
 
824
Many other SWIG language modules use an encoding of the pointer in a string. 
 
825
These scripting languages use the SWIG runtime type checker for dynamic type checking as they do not support static type checking by a compiler.
 
826
In order to implement static type checking of pointers within Java, they are wrapped by a simple Java class. 
 
827
In the example above the <tt>FILE *</tt> pointer is wrapped with a <i>type wrapper class </i> 
 
828
called <tt>SWIGTYPE_p_FILE</tt>.
 
829
 
 
830
<p>
 
831
Once obtained, a type wrapper object can be freely passed around to different C functions that
 
832
expect to receive an object of that type.  The only thing you can't do is 
 
833
dereference the pointer from Java. Of course, that isn't much of a concern in this example.
 
834
 
 
835
<p>
 
836
As much as you might be inclined to modify a pointer value directly
 
837
from Java, don't.  The value is not necessarily the
 
838
same as the logical memory address of the underlying object.  The value will
 
839
vary depending on the native byte-ordering of the platform (i.e.,
 
840
big-endian vs. little-endian).  
 
841
Most JVMs are 32 bit applications so any JNI code must also be compiled as 32 bit. 
 
842
The net result is pointers in JNI code are also 32 bits and 
 
843
are stored in the high order 4 bytes on big-endian machines and in the low order 4 bytes on little-endian machines. 
 
844
By design it is also not possible to manually cast
 
845
a pointer to a new type by using Java casts as it is particularly dangerous especially when
 
846
casting C++ objects.  If you need to cast a pointer or
 
847
change its value, consider writing some helper functions instead.  For
 
848
example:
 
849
 
 
850
<blockquote>
 
851
<pre>
 
852
%inline %{
 
853
/* C-style cast */
 
854
Bar *FooToBar(Foo *f) {
 
855
   return (Bar *) f;
 
856
}
 
857
 
 
858
/* C++-style cast */
 
859
Foo *BarToFoo(Bar *b) {
 
860
   return dynamic_cast&lt;Foo*&gt;(b);
 
861
}
 
862
 
 
863
Foo *IncrFoo(Foo *f, int i) {
 
864
    return f+i;
 
865
}
 
866
%}
 
867
</pre>
 
868
</blockquote>
 
869
 
 
870
Also, if working with C++, you should always try
 
871
to use the new C++ style casts.  For example, in the above code, the
 
872
C-style cast may return a bogus result whereas as the C++-style cast will return
 
873
a NULL pointer if the conversion can't be performed.
 
874
<p>
 
875
 
 
876
<a name="structures"></a>
 
877
<a name="n21"></a><H3>17.3.7 Structures</H3>
 
878
 
 
879
 
 
880
If you wrap a C structure, it is wrapped by a Java class with getters and setters for access to the
 
881
member variables. For example,
 
882
 
329
883
<p>
330
884
<blockquote><pre>struct Vector {
331
885
        double x,y,z;
332
886
};
333
887
 
334
888
</pre></blockquote>
335
 
This will be wrapped using native Java functions, where the first argument holds the pointer to an instance of the Vector struct. Example assuming the module name is 'example':
336
 
<blockquote><pre>
337
 
public class example  {
338
 
  public final static native void   set_Vector_x(long jarg0, double jarg1);
339
 
  public final static native double get_Vector_x(long jarg0);
340
 
  public final static native void   set_Vector_y(long jarg0, double jarg1);
341
 
  public final static native double get_Vector_y(long jarg0);
342
 
  public final static native void   set_Vector_z(long jarg0, double jarg1);
343
 
  public final static native double get_Vector_z(long jarg0);
344
 
}
345
 
</pre></blockquote>
346
 
These functions are then used in the resulting Java interface. For example:<p>
347
 
<p>
348
 
<blockquote><pre>
349
 
// v is a long holding the c pointer to a Vector that got created somehow
350
 
example.set_Vector_x(v, 7.8);
351
 
System.out.println("x=" + example.get_Vector_x(v));
352
 
</pre></blockquote>
353
 
When executed will display:<br>
354
 
<blockquote><pre>
355
 
x=7.8
356
 
</pre></blockquote>
357
 
 
358
 
Similar access is provided for unions and the data members of C++ classes.<p>
359
 
<a name="n115"></a><h3> C++ Classes</h3>
360
 
C++ classes are handled by building a set of low level accessor functions. Consider the following class :<p>
 
889
 
 
890
is used as follows:
 
891
 
 
892
<blockquote><pre>
 
893
Vector v = new Vector();
 
894
v.setX(3.5);
 
895
v.setY(7.2);
 
896
double x = v.getX();
 
897
double y = v.getY();
 
898
</pre></blockquote>
 
899
The variable setters and getters are also based on the JavaBean design pattern already covered under the Global variables section.
 
900
Similar access is provided for unions and the public data members of C++ classes.<p>
 
901
 
 
902
This object is actually an instance of a Java class that has been wrapped around a pointer to the C structure.  
 
903
This instance doesn't actually do anything--it just serves as a proxy.
 
904
The pointer to the C object is held in the Java proxy class in much the same way as pointers are held by type wrapper classes.
 
905
Further details about Java proxy classes are covered a little later.
 
906
 
 
907
<p>
 
908
<tt>const</tt> members of a structure are read-only. Data members
 
909
can also be forced to be read-only using the <tt>%immutable</tt> directive. For example:
 
910
 
 
911
<blockquote>
 
912
<pre>
 
913
struct Foo {
 
914
   ...
 
915
   %immutable;
 
916
   int x;        /* Read-only members */
 
917
   char *name;
 
918
   %mutable;
 
919
   ...
 
920
};
 
921
</pre>
 
922
</blockquote>
 
923
 
 
924
<p>
 
925
When <tt>char *</tt> members of a structure are wrapped, the contents are assumed to be
 
926
dynamically allocated using <tt>malloc</tt> or <tt>new</tt> (depending on whether or not
 
927
SWIG is run with the -c++ option).   When the structure member is set, the old contents will be 
 
928
released and a new value created.   If this is not the behavior you want, you will have to use
 
929
a typemap (described later).
 
930
 
 
931
<p>
 
932
If a structure contains arrays, access to those arrays is managed through pointers.  For
 
933
example, consider this:
 
934
 
 
935
<blockquote>
 
936
<pre>
 
937
struct Bar {
 
938
    int  x[16];
 
939
};
 
940
</pre>
 
941
</blockquote>
 
942
 
 
943
If accessed in Java, you will see behavior like this:
 
944
 
 
945
<blockquote>
 
946
<pre>
 
947
Bar b = new Bar();
 
948
SWIGTYPE_p_int x = b.getX();
 
949
</pre>
 
950
</blockquote>
 
951
 
 
952
This pointer can be passed around to functions that expect to receive
 
953
an <tt>int *</tt> (just like C).   You can also set the value of an array member using
 
954
another pointer.  For example:
 
955
 
 
956
<blockquote>
 
957
<pre>
 
958
Bar b = new Bar();
 
959
SWIGTYPE_p_int x = b.getX();
 
960
Bar c = new Bar();
 
961
c.setX(x);                    // Copy contents of b.x to c.x
 
962
</pre>
 
963
</blockquote>
 
964
 
 
965
For array assignment (setters not getters), SWIG copies the entire contents of the array starting with the data pointed
 
966
to by <tt>b.x</tt>.   In this example, 16 integers would be copied.  Like C, SWIG makes
 
967
no assumptions about bounds checking---if you pass a bad pointer, you may get a segmentation
 
968
fault or access violation.
 
969
Array access can be changed from this default to use Java arrays and this is covered later.
 
970
 
 
971
<p>
 
972
When a member of a structure is itself a structure, it is handled as a
 
973
pointer.  For example, suppose you have two structures like this:
 
974
 
 
975
<blockquote>
 
976
<pre>
 
977
struct Foo {
 
978
   int a;
 
979
};
 
980
 
 
981
struct Bar {
 
982
   Foo f;
 
983
};
 
984
</pre>
 
985
</blockquote>
 
986
 
 
987
Now, suppose that you access the <tt>f</tt> member of <tt>Bar</tt> like this:
 
988
 
 
989
<blockquote>
 
990
<pre>
 
991
Bar b = new Bar();
 
992
Foo x = b.getF();
 
993
</pre>
 
994
</blockquote>
 
995
 
 
996
In this case, <tt>x</tt> is a pointer that points to the <tt>Foo</tt> that is inside <tt>b</tt>.
 
997
This is the same value as generated by this C code:
 
998
 
 
999
<blockquote>
 
1000
<pre>
 
1001
Bar b;
 
1002
Foo *x = &b->f;       /* Points inside b */
 
1003
</pre>
 
1004
</blockquote>
 
1005
 
 
1006
Because the pointer points inside the structure, you can modify the contents and 
 
1007
everything works just like you would expect. For example:
 
1008
 
 
1009
<blockquote>
 
1010
<pre>
 
1011
Bar b = new Bar();
 
1012
b.getF().setA(3);   // Modify b.f.a
 
1013
Foo x = b.getF();                   
 
1014
x.setA(3);          // Modify x.a - this is the same as b.f.a
 
1015
</pre>
 
1016
</blockquote>
 
1017
 
 
1018
 
 
1019
<a name="classes"></a>
 
1020
<a name="n22"></a><H3>17.3.8 C++ classes</H3>
 
1021
 
 
1022
 
 
1023
C++ classes are wrapped by Java classes as well. For example, if you have this class,
 
1024
 
361
1025
<p>
362
1026
<blockquote><pre>class List {
363
1027
public:
368
1032
  void remove(char *item);
369
1033
  char *get(int n);
370
1034
  int  length;
371
 
  static void print(List *l);
372
1035
};
373
1036
</pre></blockquote>
374
 
<p>
375
 
When wrapped by SWIG, will produce the following JNI c code to access the class (assuming the module is set to 'example'):<p>
376
 
<p>
377
 
<blockquote><pre>
378
 
JNIEXPORT jlong JNICALL Java_example_new_1List(JNIEnv *jenv, jclass jcls);
379
 
JNIEXPORT void JNICALL Java_example_delete_1List(JNIEnv *jenv, jclass jcls, jlong jarg0);
380
 
JNIEXPORT jint JNICALL Java_example_List_1search(JNIEnv *jenv, jclass jcls, jlong jarg0, jstring jarg1);
381
 
JNIEXPORT void JNICALL Java_example_List_1insert(JNIEnv *jenv, jclass jcls, jlong jarg0, jstring jarg1);
382
 
JNIEXPORT void JNICALL Java_example_List_1remove(JNIEnv *jenv, jclass jcls, jlong jarg0, jstring jarg1);
383
 
JNIEXPORT jstring JNICALL Java_example_List_1get(JNIEnv *jenv, jclass jcls, jlong jarg0, jint jarg1);
384
 
JNIEXPORT void JNICALL Java_example_set_1List_1length(JNIEnv *jenv, jclass jcls, jlong jarg0, jint jarg1);
385
 
JNIEXPORT jint JNICALL Java_example_get_1List_1length(JNIEnv *jenv, jclass jcls, jlong jarg0);
386
 
JNIEXPORT void JNICALL Java_example_List_1print(JNIEnv *jenv, jclass jcls, jlong jarg0);
387
 
</pre></blockquote>
388
 
where jarg0 is the 'this' pointer in non-static functions. The JNI specification requires a c interface.
389
 
 
390
 
The following JNI Java functions are also produced for access from Java:
391
 
<blockquote><pre>
392
 
public class example  {
393
 
  public final static native long new_List();
394
 
  public final static native void delete_List(long jarg0);
395
 
  public final static native int List_search(long jarg0, String jarg1);
396
 
  public final static native void List_insert(long jarg0, String jarg1);
397
 
  public final static native void List_remove(long jarg0, String jarg1);
398
 
  public final static native String List_get(long jarg0, int jarg1);
399
 
  public final static native void List_length_set(long jarg0, int jarg1);
400
 
  public final static native int List_length_get(long jarg0);
401
 
  public final static native void List_print(long jarg0);
402
 
}
403
 
</pre></blockquote>
404
 
 
405
 
From Java, these functions can be used to access the C++ class:<p>
406
 
<blockquote><pre>
407
 
long l = example.new_List();
408
 
example.List_insert(l,"Ale");
409
 
example.List_insert(l,"Stout");
410
 
example.List_insert(l,"Lager");
411
 
example.List_print(l);
412
 
int len = example.get_List_length(l);
413
 
System.out.println(len);
414
 
</pre></blockquote>
415
 
When executed might display:
416
 
<blockquote><pre>
417
 
Lager
418
 
Stout
419
 
Ale
420
 
3
421
 
</pre></blockquote>
422
 
 
423
 
</pre></blockquote>
424
 
While somewhat primitive, the low-level SWIG interface provides direct and flexible access to C++ objects. As it turns out, a more elegant method of accessing structures and classes is available using shadow classes.<p>
425
 
 
426
 
<a name="n4"></a><h2>Java shadow classes</h2>
427
 
The low-level interface generated by SWIG provides access to C structures and C++ classes, but it doesn't look much like a class that might be created in Java. However, it is possible to indirectly use the low-level C interface to write a Java class that looks like the original C++ class. In this case, the Java class is said to "shadow" the C++ class.  That is, it behaves like the original class, but is really just a wrapper around a C++ class. The Java class is sometimes called a proxy class.<p>
428
 
<a name="n116"></a><h3> A simple example</h3>
429
 
For our earlier List class, a Java shadow class could be written by hand like this :<p>
430
 
<p>
431
 
<blockquote><pre>
432
 
public class List {
433
 
  protected long _cPtr;
434
 
  protected boolean _cMemOwn;
435
 
 
436
 
  public long getCPtr() {
437
 
    return _cPtr;
438
 
  }
439
 
 
440
 
  public List() {
441
 
    _cPtr = example.new_List();
442
 
    _cMemOwn = true;
443
 
  }
444
 
 
445
 
  protected void finalize() {
446
 
    _delete();
447
 
  }
448
 
 
449
 
  public void _delete() {
450
 
    if(_cPtr!=0 && _cMemOwn) {
451
 
      example.delete_List(_cPtr);
452
 
      _cPtr = 0;
453
 
    }
454
 
  }
455
 
 
456
 
  public int search(String item) {
457
 
    return example.List_search(_cPtr, item);
458
 
  }
459
 
 
460
 
  public void insert(String item) {
461
 
    example.List_insert(_cPtr, item);
462
 
  }
463
 
 
464
 
  public void remove(String item) {
465
 
    example.List_remove(_cPtr, item);
466
 
  }
467
 
 
468
 
  public String get(int n) {
469
 
    return example.List_get(_cPtr, n);
470
 
  }
471
 
 
472
 
  public void setLength(int value) {
473
 
    example.set_List_length(_cPtr, value);
474
 
  }
475
 
 
476
 
  public int getLength() {
477
 
    return example.get_List_length(_cPtr);
478
 
  }
479
 
 
480
 
  public static void print(List l) {
481
 
    example.List_print(l.getCPtr());
482
 
  }
483
 
 
484
 
}
485
 
</pre></blockquote>
486
 
Which is roughly what SWIG outputs.
487
 
When used in Java, we can use the class as follows:<p>
 
1037
 
 
1038
you can use it in Java like this:
488
1039
 
489
1040
<blockquote><pre>
490
1041
List l = new List();
491
1042
l.insert("Ale");
492
1043
l.insert("Stout");
493
1044
l.insert("Lager");
494
 
List.print(l);
495
 
int len = l.getLength();
496
 
System.out.println(len);
497
 
</pre></blockquote>
498
 
 
499
 
Obviously, this is a much nicer interface than before, it only required a small amount of Java coding, it is type-safe and fits in with the Java programming paradigm.<p>
500
 
 
501
 
<a name="n117"></a><h3> Why write shadow classes in Java?</h3>
502
 
While one could wrap C/C++ objects directly into Java as new Java types, this approach has a number of problems. First, as the C/C++ code gets complicated, the resulting wrapper code starts to become extremely ugly.<p>
503
 
<p>
504
 
By writing shadow classes in Java instead of C, the classes become real Java classes that can be easily used as base-classes in an inheritance hierarchy or for other applications. Writing the shadow classes in Java also greatly simplies coding complexity as writing them in Java is much easier than trying to accomplish the same thing in C. Finally, by writing shadow classes in Java, they are easy to modify and can be changed without ever recompiling any of the C code. The downside to using shadow classes over the simple interface is a slight performance degradation--a concern for some users.<p>
505
 
<p>
506
 
<a name="n118"></a><h3> Automated shadow class generation</h3>
507
 
SWIG automatically generates shadow classes when you use the <tt>-shadow</tt> option:<p>
508
 
<p>
509
 
<blockquote><pre>swig -java -shadow interface.i
510
 
</pre></blockquote>
511
 
 
512
 
This will create the following files:<p>
513
 
<p>
514
 
<blockquote><pre>
515
 
interface_wrap.c
516
 
interface.java
517
 
<i>
518
 
plus other .java files corresponding to each shadow class
519
 
</i>
520
 
</pre></blockquote>
521
 
 
522
 
The file <tt>interface_wrap.c</tt> contains the normal SWIG C JNI wrappers. The file <tt>interface.java</tt> contains the Java code corresponding to the Java native functions. The name of this file will be the same as specified by the <tt>%module</tt> directive in the SWIG interface file. These two files are produced whether or not the -shadow option is passed to SWIG. There will then be a <tt>.java</tt> file for each shadow class when -shadow is used. Note that if -c++ is passed to SWIG for wrapping C++ code, then a <tt>interface_wrap.cxx</tt> file replaces the <tt>interface_wrap.c</tt> file.
523
 
<p>
524
 
 
525
 
<a name="n119"></a><h3> Compiling modules with shadow classes</h3>
526
 
No changes need to be made to the compilation process when using shadow classes.<p>
527
 
 
528
 
<a name="n120"></a><h3> Where to go for more information</h3>
529
 
Shadow classes turn out to be so useful that they are used almost all of the time with SWIG. All of the examples presented here will assume that shadow classes have been enabled. The precise implementation of shadow classes is described at the end of this chapter.<p>
530
 
 
531
 
<a name="n5"></a><h2>Examples</h2>
532
 
 
533
 
The directory Examples/java has a number of examples. Looking at these is a good way to learn how the SWIG Java extension works. The Examples/index.html in the parent direcory contains the SWIG Examples Documentation and is a useful starting point. The following sections also describe plenty of examples.
534
 
 
535
 
<a name="n6"></a><h2>Exception handling </h2>
536
 
The SWIG <tt>%exception</tt> directive can be used to create a user-definable exception handler which can be used to convert errors in your C/C++ program into Java exceptions.  The chapter on exception handling contains more details, but suppose you have a C++ class like the following:<p>
537
 
<blockquote><pre>
538
 
class RangeError {};   // Used for an exception
539
 
 
540
 
class DoubleArray {
541
 
  private:
542
 
    int n;
543
 
    double *ptr;
544
 
  public:
545
 
    // Create a new array of fixed size
546
 
    DoubleArray(int size) {
547
 
      ptr = new double[size];
548
 
      n = size;
549
 
    }
550
 
    // Destroy an array
551
 
    ~DoubleArray() {
552
 
       delete ptr;
553
 
    }
554
 
    // Return the length of the array
555
 
    int   length() {
556
 
      return n;
557
 
    }
558
 
 
559
 
    // Get an item from the array and perform bounds checking.
560
 
    double getitem(int i) {
561
 
      if ((i &gt;= 0) &amp;&amp; (i &lt; n))
562
 
        return ptr[i];
563
 
      else
564
 
        throw RangeError();
565
 
    }
566
 
 
567
 
    // Set an item in the array and perform bounds checking.
568
 
    void setitem(int i, double val) {
569
 
      if ((i &gt;= 0) &amp;&amp; (i &lt; n))
570
 
        ptr[i] = val;
571
 
      else {
572
 
        throw RangeError();
 
1045
String item = l.get(2);
 
1046
int length = l.getLength();
 
1047
</pre></blockquote>
 
1048
 
 
1049
Class data members are accessed in the same manner as C structures.  
 
1050
 
 
1051
<p>
 
1052
Static class members are unsurprisingly wrapped as static members of the Java class:
 
1053
 
 
1054
<blockquote>
 
1055
<pre>
 
1056
class Spam {
 
1057
public:
 
1058
   static void foo();
 
1059
   static int bar;
 
1060
};
 
1061
</pre>
 
1062
</blockquote>
 
1063
 
 
1064
The static members work like any other Java static member:
 
1065
 
 
1066
<blockquote>
 
1067
<pre>
 
1068
Spam.foo();
 
1069
int bar = Spam.getBar();
 
1070
</pre>
 
1071
</blockquote>
 
1072
 
 
1073
 
 
1074
<a name="inheritance"></a>
 
1075
<a name="n23"></a><H3>17.3.9 C++ inheritance</H3>
 
1076
 
 
1077
 
 
1078
SWIG is fully aware of issues related to C++ inheritance.  Therefore, if you have
 
1079
classes like this
 
1080
 
 
1081
<blockquote>
 
1082
<pre>
 
1083
class Foo {
 
1084
...
 
1085
};
 
1086
 
 
1087
class Bar : public Foo {
 
1088
...
 
1089
};
 
1090
</pre>
 
1091
</blockquote>
 
1092
 
 
1093
those classes are wrapped into a hierarchy of Java classes that reflect the same inheritance
 
1094
structure:
 
1095
 
 
1096
<blockquote>
 
1097
<pre>
 
1098
Bar b = new Bar();
 
1099
Class c = b.getClass();
 
1100
System.out.println(c.getSuperclass().getName());
 
1101
</pre>
 
1102
</blockquote>
 
1103
 
 
1104
will of course display:
 
1105
 
 
1106
<blockquote><pre>
 
1107
Foo
 
1108
</pre></blockquote>
 
1109
 
 
1110
 
 
1111
Furthermore, if you have functions like this
 
1112
 
 
1113
<blockquote>
 
1114
<pre>
 
1115
void spam(Foo *f);
 
1116
</pre>
 
1117
</blockquote>
 
1118
 
 
1119
then the Java function <tt>spam()</tt> accepts instances of <tt>Foo</tt> or instances of any other proxy classes derived from <tt>Foo</tt>.
 
1120
 
 
1121
<p>
 
1122
Note that Java does not support multiple inheritance so any multiple inheritance in the C++ code is not going to work. 
 
1123
A warning is given when multiple inheritance is detected and only the first base class is used. 
 
1124
 
 
1125
<a name="pointers_refs_arrays"></a>
 
1126
<a name="n24"></a><H3>17.3.10 Pointers, references, arrays and pass by value</H3>
 
1127
 
 
1128
 
 
1129
In C++, there are many different ways a function might receive
 
1130
and manipulate objects.  For example:
 
1131
 
 
1132
<blockquote>
 
1133
<pre>
 
1134
void spam1(Foo *x);      // Pass by pointer
 
1135
void spam2(Foo &x);      // Pass by reference
 
1136
void spam3(Foo x);       // Pass by value
 
1137
void spam4(Foo x[]);     // Array of objects
 
1138
</pre>
 
1139
</blockquote>
 
1140
 
 
1141
In Java, there is no detailed distinction like this--specifically,
 
1142
there are only instances of classes.  There are no pointers nor references.
 
1143
Because of this, SWIG unifies all of these types
 
1144
together in the wrapper code.  For instance, if you actually had the
 
1145
above functions, it is perfectly legal to do this from Java:
 
1146
 
 
1147
<blockquote>
 
1148
<pre>
 
1149
Foo f = new Foo();  // Create a Foo
 
1150
example.spam1(f);   // Ok. Pointer
 
1151
example.spam2(f);   // Ok. Reference
 
1152
example.spam3(f);   // Ok. Value.
 
1153
example.spam4(f);   // Ok. Array (1 element)
 
1154
</pre>
 
1155
</blockquote>
 
1156
 
 
1157
Similar behavior occurs for return values.  For example, if you had
 
1158
functions like this,
 
1159
 
 
1160
<blockquote>
 
1161
<pre>
 
1162
Foo *spam5();
 
1163
Foo &spam6();
 
1164
Foo  spam7();
 
1165
</pre>
 
1166
</blockquote>
 
1167
 
 
1168
then all three functions will return a pointer to some <tt>Foo</tt> object.
 
1169
Since the third function (spam7) returns a value, newly allocated memory is used 
 
1170
to hold the result and a pointer is returned (Java will release this memory 
 
1171
when the returned object's finalizer is run by the garbage collector).
 
1172
 
 
1173
<a name="null_pointers"></a>
 
1174
<a name="n25"></a><H4>17.3.10.1 Null pointers</H4>
 
1175
 
 
1176
 
 
1177
Working with null pointers is easy. 
 
1178
A Java <tt>null</tt> can be used whenever a method expects a proxy class or typewrapper class.
 
1179
However, it is not possible to pass null to C/C++ functions that take parameters by value or by reference. 
 
1180
If you try you will get a NullPointerException.
 
1181
 
 
1182
<blockquote>
 
1183
<pre>
 
1184
example.spam1(null);   // Pointer - ok
 
1185
example.spam2(null);   // Reference - NullPointerException
 
1186
example.spam3(null);   // Value - NullPointerException
 
1187
example.spam4(null);   // Array - ok
 
1188
</pre>
 
1189
</blockquote>
 
1190
 
 
1191
For <tt>spam1</tt> and <tt>spam4</tt> above the Java <tt>null</tt> gets translated into a NULL pointer for passing to the C/C++ function. 
 
1192
The converse also occurs, that is, NULL pointers are translated into <tt>null</tt> Java objects when returned from a C/C++ function.
 
1193
 
 
1194
<a name="overloaded_functions"></a>
 
1195
<a name="n26"></a><H3>17.3.11 C++ overloaded functions</H3>
 
1196
 
 
1197
 
 
1198
C++ overloaded functions, methods, and constructors are mostly supported by SWIG.  For example,
 
1199
if you have two functions like this:
 
1200
 
 
1201
<blockquote>
 
1202
<pre>
 
1203
void foo(int);
 
1204
void foo(char *c);
 
1205
</pre>
 
1206
</blockquote>
 
1207
 
 
1208
You can use them in Java in a straightforward manner:
 
1209
 
 
1210
<blockquote>
 
1211
<pre>
 
1212
foo(3);           // foo(int)
 
1213
foo("Hello");     // foo(char *c)
 
1214
</pre>
 
1215
</blockquote>
 
1216
 
 
1217
Similarly, if you have a class like this,
 
1218
 
 
1219
<blockquote>
 
1220
<pre>
 
1221
class Foo {
 
1222
public:
 
1223
    Foo();
 
1224
    Foo(const Foo &);
 
1225
    ...
 
1226
};
 
1227
</pre>
 
1228
</blockquote>
 
1229
 
 
1230
you can write Java code like this:
 
1231
 
 
1232
<blockquote>
 
1233
<pre>
 
1234
Foo f = new Foo();        // Create a Foo
 
1235
Foo g = new Foo(f);       // Copy f
 
1236
</pre>
 
1237
</blockquote>
 
1238
 
 
1239
Overloading support is not quite as flexible as in C++. Sometimes there are methods that SWIG
 
1240
can't disambiguate as there can be more than one C++ type mapping onto a single Java type. For example:
 
1241
 
 
1242
<blockquote>
 
1243
<pre>
 
1244
void spam(int);
 
1245
void spam(unsigned short);
 
1246
</pre>
 
1247
</blockquote>
 
1248
 
 
1249
Here both int and unsigned short map onto a Java int. 
 
1250
Here is another example:
 
1251
 
 
1252
<blockquote>
 
1253
<pre>
 
1254
void foo(Bar *b);
 
1255
void foo(Bar &b);
 
1256
</pre>
 
1257
</blockquote>
 
1258
 
 
1259
If declarations such as these appear, you will get a warning message like this:
 
1260
 
 
1261
<blockquote>
 
1262
<pre>
 
1263
example.i:12: Warning(509): Overloaded spam(unsigned short) is shadowed by spam(int) at example.i:11.
 
1264
</pre>
 
1265
</blockquote>
 
1266
The generated Java code will not compile either.
 
1267
 
 
1268
To fix this, you either need to ignore or rename one of the methods.  For example:
 
1269
 
 
1270
<blockquote>
 
1271
<pre>
 
1272
%rename(spam_short) spam(short);
 
1273
...
 
1274
void spam(int);    
 
1275
void spam(short);   // Accessed as spam_short
 
1276
</pre>
 
1277
</blockquote>
 
1278
 
 
1279
or
 
1280
 
 
1281
<blockquote>
 
1282
<pre>
 
1283
%ignore spam(short);
 
1284
...
 
1285
void spam(int);    
 
1286
void spam(short);   // Ignored
 
1287
</pre>
 
1288
</blockquote>
 
1289
 
 
1290
<P>
 
1291
 
 
1292
<a name="namespaces"></a>
 
1293
<a name="n27"></a><H3>17.3.12 C++ namespaces</H3>
 
1294
 
 
1295
 
 
1296
SWIG is aware of C++ namespaces, but namespace names do not appear in
 
1297
the module nor do namespaces result in a module that is broken up into
 
1298
submodules or packages.  For example, if you have a file like this,
 
1299
 
 
1300
<blockquote>
 
1301
<pre>
 
1302
%module example
 
1303
 
 
1304
namespace foo {
 
1305
   int fact(int n);
 
1306
   struct Vector {
 
1307
       double x,y,z;
 
1308
   };
 
1309
};
 
1310
</pre>
 
1311
</blockquote>
 
1312
 
 
1313
it works in Java as follows:
 
1314
 
 
1315
<blockquote>
 
1316
<pre>
 
1317
int f = example.fact(3);
 
1318
Vector v = new Vector();
 
1319
v.setX(3.4);
 
1320
double y = v.getY();
 
1321
</pre>
 
1322
</blockquote>
 
1323
 
 
1324
If your program has more than one namespace, name conflicts (if any) can be resolved using <tt>%rename</tt>
 
1325
For example:
 
1326
 
 
1327
<blockquote>
 
1328
<pre>
 
1329
%rename(Bar_spam) Bar::spam;
 
1330
 
 
1331
namespace Foo {
 
1332
    int spam();
 
1333
}
 
1334
 
 
1335
namespace Bar {
 
1336
    int spam();
 
1337
}
 
1338
</pre>
 
1339
</blockquote>
 
1340
 
 
1341
If you have more than one namespace and your want to keep their
 
1342
symbols separate, consider wrapping them as separate SWIG modules.
 
1343
Each SWIG module can be placed into a separate package.
 
1344
 
 
1345
<a name="templates"></a>
 
1346
<a name="n28"></a><H3>17.3.13 C++ templates</H3>
 
1347
 
 
1348
 
 
1349
C++ templates don't present a huge problem for SWIG.  However, in order
 
1350
to create wrappers, you have to tell SWIG to create wrappers for a particular
 
1351
template instantiation.  To do this, you use the <tt>%template</tt> directive.
 
1352
For example:
 
1353
 
 
1354
<blockquote>
 
1355
<pre>
 
1356
%module example
 
1357
%{
 
1358
#include "pair.h"
 
1359
%}
 
1360
 
 
1361
template&lt;class T1, class T2&gt;
 
1362
struct pair {
 
1363
   typedef T1 first_type;
 
1364
   typedef T2 second_type;
 
1365
   T1 first;
 
1366
   T2 second;
 
1367
   pair();
 
1368
   pair(const T1&, const T2&);
 
1369
  ~pair();
 
1370
};
 
1371
 
 
1372
%template(pairii) pair&lt;int,int&gt;;
 
1373
</pre>
 
1374
</blockquote>
 
1375
 
 
1376
In Java:
 
1377
 
 
1378
<blockquote>
 
1379
<pre>
 
1380
pairii p = new pairii(3,4);
 
1381
int first = p.getFirst();
 
1382
int second = p.getSecond();
 
1383
</pre>
 
1384
</blockquote>
 
1385
 
 
1386
Obviously, there is more to template wrapping than shown in this example.
 
1387
More details can be found in the <a href="SWIGPlus.html">SWIG and C++</a> chapter.   
 
1388
 
 
1389
<a name="smart_pointers"></a>
 
1390
<a name="n29"></a><H3>17.3.14 C++ Smart Pointers</H3>
 
1391
 
 
1392
 
 
1393
In certain C++ programs, it is common to use classes that have been wrapped by
 
1394
so-called "smart pointers."   Generally, this involves the use of a template class
 
1395
that implements <tt>operator->()</tt> like this:
 
1396
 
 
1397
<blockquote>
 
1398
<pre>
 
1399
template&lt;class T&gt; class SmartPtr {
 
1400
   ...
 
1401
   T *operator->();
 
1402
   ...
 
1403
}
 
1404
</pre>
 
1405
</blockquote>
 
1406
 
 
1407
Then, if you have a class like this,
 
1408
 
 
1409
<blockquote>
 
1410
<pre>
 
1411
class Foo {
 
1412
public:
 
1413
     int x;
 
1414
     int bar();
 
1415
};
 
1416
</pre>
 
1417
</blockquote>
 
1418
 
 
1419
A smart pointer would be used in C++ as follows:
 
1420
 
 
1421
<blockquote>
 
1422
<pre>
 
1423
SmartPtr&lt;Foo&gt; p = CreateFoo();   // Created somehow (not shown)
 
1424
...
 
1425
p->x = 3;                        // Foo::x
 
1426
int y = p->bar();                // Foo::bar
 
1427
</pre>
 
1428
</blockquote>
 
1429
 
 
1430
To wrap this in Java, simply tell SWIG about the <tt>SmartPtr</tt> class and the low-level
 
1431
<tt>Foo</tt> object.  Make sure you instantiate <tt>SmartPtr</tt> using <tt>%template</tt> if necessary.
 
1432
For example:
 
1433
 
 
1434
<blockquote>
 
1435
<pre>
 
1436
%module example
 
1437
...
 
1438
%template(SmartPtrFoo) SmartPtr&lt;Foo&gt;;
 
1439
...
 
1440
</pre>
 
1441
</blockquote>
 
1442
 
 
1443
Now, in Java, everything should just "work":
 
1444
 
 
1445
<blockquote>
 
1446
<pre>
 
1447
SmartPtrFoo p = example.CreateFoo(); // Create a smart-pointer somehow
 
1448
p.setX(3);                           // Foo::x
 
1449
int y = p.bar();                     // Foo::bar
 
1450
</pre>
 
1451
</blockquote>
 
1452
 
 
1453
If you ever need to access the underlying pointer returned by <tt>operator->()</tt> itself,
 
1454
simply use the <tt>__deref__()</tt> method.  For example:
 
1455
 
 
1456
<blockquote>
 
1457
<pre>
 
1458
Foo f = p.__deref__();               // Returns underlying Foo *
 
1459
</pre>
 
1460
</blockquote>
 
1461
 
 
1462
<a name="further_details"></a>
 
1463
<a name="n30"></a><H2>17.4 Further details on the generated Java classes</H2>
 
1464
 
 
1465
 
 
1466
In the previous section, a high-level view of Java wrapping was
 
1467
presented.  A key component of this wrapping is that structures and
 
1468
classes are wrapped by Java proxy classes and type wrapper classes are used
 
1469
in situations where no proxies are generated.  This provides a very
 
1470
natural, type safe Java interface to the C/C++ code and fits in with the Java programing paradigm.
 
1471
However, a number of low-level details were omitted.  This section provides a brief overview
 
1472
of how the proxy classes work and then covers the type wrapper classes.
 
1473
First, the crucial intermediary JNI class is considered.
 
1474
 
 
1475
<a name="imclass"></a>
 
1476
<a name="n31"></a><H3>17.4.1 The intermediary JNI class</H3>
 
1477
 
 
1478
 
 
1479
In the <a href="SWIG.html">"SWIG basics"</a> and <a href="SWIGPlus.html">"SWIG and C++"</a> chapters,
 
1480
details of low-level structure and class wrapping are described.  To summarize those chapters, if you
 
1481
have a global function and class like this
 
1482
 
 
1483
<blockquote>
 
1484
<pre>
 
1485
class Foo {
 
1486
public:
 
1487
     int x;
 
1488
     int spam(int num, Foo* foo);
 
1489
};
 
1490
void egg(Foo* chips);
 
1491
</pre>
 
1492
</blockquote>
 
1493
 
 
1494
then SWIG transforms the class into a set of low-level procedural wrappers.
 
1495
These procedural wrappers essentially perform the equivalent of this C++ code:
 
1496
 
 
1497
<blockquote>
 
1498
<pre>
 
1499
Foo *new_Foo() {
 
1500
    return new Foo();
 
1501
}
 
1502
void delete_Foo(Foo *f) {
 
1503
    delete f;
 
1504
}
 
1505
int Foo_x_get(Foo *f) {
 
1506
    return f->x;
 
1507
}
 
1508
void Foo_x_set(Foo *f, int value) {
 
1509
    f->x = value;
 
1510
}
 
1511
int Foo_spam(Foo *f, int num, Foo* foo) {
 
1512
    return f->spam(num, foo);
 
1513
}
 
1514
</pre>
 
1515
</blockquote>
 
1516
 
 
1517
These procedural function names don't actually exist, but their functionality appears inside the generated
 
1518
JNI functions. The JNI functions have to follow a particular naming convention so the function names are actually:
 
1519
 
 
1520
<blockquote>
 
1521
<pre>
 
1522
JNIEXPORT jlong JNICALL Java_exampleJNI_new_1Foo(JNIEnv *jenv, jclass jcls);
 
1523
JNIEXPORT void JNICALL Java_exampleJNI_delete_1Foo(JNIEnv *jenv, jclass jcls, jlong jarg1);
 
1524
JNIEXPORT void JNICALL Java_exampleJNI_set_1Foo_1x(JNIEnv *jenv, jclass jcls, jlong jarg1, jint jarg2);
 
1525
JNIEXPORT jint JNICALL Java_exampleJNI_get_1Foo_1x(JNIEnv *jenv, jclass jcls, jlong jarg1);
 
1526
JNIEXPORT jint JNICALL Java_exampleJNI_Foo_1spam(JNIEnv *jenv, jclass jcls, jlong jarg1, jint jarg2, jlong jarg3);
 
1527
JNIEXPORT void JNICALL Java_exampleJNI_egg(JNIEnv *jenv, jclass jcls, jlong jarg1);
 
1528
</pre>
 
1529
</blockquote>
 
1530
 
 
1531
For every JNI C function there has to be a static native Java function. These appear in the intermediary JNI class:
 
1532
 
 
1533
<blockquote>
 
1534
<pre>
 
1535
class exampleJNI {
 
1536
  public final static native long new_Foo();
 
1537
  public final static native void delete_Foo(long jarg1);
 
1538
  public final static native void set_Foo_x(long jarg1, int jarg2);
 
1539
  public final static native int get_Foo_x(long jarg1);
 
1540
  public final static native int Foo_spam(long jarg1, int jarg2, long jarg3);
 
1541
  public final static native void egg(long jarg1);
 
1542
}
 
1543
</pre>
 
1544
</blockquote>
 
1545
 
 
1546
This class contains the complete Java - C/C++ interface so all function calls go via this class. 
 
1547
As this class acts as a go-between for all JNI calls to C/C++ code from the Java <a href="#java_proxy_classes">proxy classes</a>, <a href="#type_wrapper_classes">type wrapper classes</a> and <a href="#java_module_class">module class</a>, it is known as the intermediary JNI class.
 
1548
<p>
 
1549
 
 
1550
You may notice that SWIG uses a Java long wherever a pointer or class object needs traversing the Java-C/C++ boundary.
 
1551
This approach leads to minimal JNI code which makes for better performance as JNI code involves a lot of string manipulation.
 
1552
SWIG uses Java code wherever possible as it is compiled into byte code which requires fewer string operations.
 
1553
 
 
1554
<p>
 
1555
The functions in the intermediary JNI class cannot be accessed outside of its package. Access to them is gained through the module class for globals otherwise the appropriate proxy class.
 
1556
 
 
1557
<p>
 
1558
The name of the intermediary JNI class can be changed from its default, that is, the module name with JNI appended after it. 
 
1559
The module directive attribute <tt>jniclassname</tt> is used to achieve this:
 
1560
 
 
1561
<blockquote>
 
1562
<pre>
 
1563
%module (jniclassname="name") modulename
 
1564
</pre>
 
1565
</blockquote>
 
1566
 
 
1567
If <tt>name</tt> is the same as <tt>modulename</tt> then the module class name gets changed
 
1568
from <tt>modulename</tt> to <tt>modulenameModule</tt>.
 
1569
 
 
1570
<a name="imclass_pragmas"></a>
 
1571
<a name="n32"></a><H4>17.4.1.1 The intermediary JNI class pragmas</H4>
 
1572
 
 
1573
 
 
1574
The intermediary JNI class can be tailored through the use of pragmas, but is not commonly done. The pragmas for this class are:
 
1575
 
 
1576
<p>
 
1577
<table BORDER>
 
1578
<tr VALIGN=TOP>
 
1579
<td><b>Pragma</b></td>
 
1580
<td><b>Description</b></td>
 
1581
</tr>
 
1582
 
 
1583
<tr>
 
1584
    <td>jniclassbase            </td> <td>Base class for the intermediary JNI class</td>
 
1585
</tr>
 
1586
<tr>
 
1587
    <td>jniclassclassmodifiers  </td> <td>Class modifiers for the intermediary JNI class</td>
 
1588
</tr>
 
1589
<tr>
 
1590
    <td>jniclasscode            </td> <td>Java code is copied verbatim into the intermediary JNI class</td>
 
1591
</tr>
 
1592
<tr>
 
1593
    <td>jniclassimports         </td> <td>Java code, usually one or more import statements, placed before the intermediary JNI class definition</td>
 
1594
</tr>
 
1595
<tr>
 
1596
    <td>jniclassinterfaces      </td> <td>Comma separated interface classes for the intermediary JNI class</td>
 
1597
</tr>
 
1598
</table>
 
1599
 
 
1600
<p>
 
1601
The pragma code appears in the generated intermediary JNI class where you would expect:
 
1602
 
 
1603
<blockquote>
 
1604
<pre>
 
1605
[ jniclassimports pragma ]
 
1606
[ jniclassmodifiers pragma ] class jniclassname extends [ jniclassbase pragma ] implements [ jniclassinterfaces pragma ] {
 
1607
[ jniclasscode pragma ]
 
1608
... SWIG generated native methods ...
 
1609
}
 
1610
</pre>
 
1611
</blockquote>
 
1612
 
 
1613
The <tt>jniclasscode</tt> pragma is quite useful for adding in a static block for loading the shared library / dynamic link library and demonstrates how pragmas work:
 
1614
 
 
1615
<blockquote>
 
1616
<pre>
 
1617
%pragma(java) jniclasscode=%{
 
1618
  static {
 
1619
    try {
 
1620
        System.loadLibrary("example");
 
1621
    } catch (UnsatisfiedLinkError e) {
 
1622
      System.err.println("Native code library failed to load. \n" + e);
 
1623
      System.exit(1);
 
1624
    }
 
1625
  }
 
1626
%}
 
1627
</pre>
 
1628
</blockquote>
 
1629
 
 
1630
Pragmas will take either <tt>""</tt> or <tt>%{ %}</tt> as delimeters. 
 
1631
For example, let's change the intermediary JNI class access attribute to public. 
 
1632
 
 
1633
<blockquote>
 
1634
<pre>
 
1635
%pragma(java) jniclassclassmodifiers="public"
 
1636
</pre>
 
1637
</blockquote>
 
1638
 
 
1639
All the methods in the intermediary JNI class will then be callable outside of the package as the method modifiers are public by default.
 
1640
 
 
1641
<a name="java_module_class"></a>
 
1642
<a name="n33"></a><H3>17.4.2 The Java module class</H3>
 
1643
 
 
1644
 
 
1645
All global functions and variable getters/setters appear in the module class. For our example, there is just one function:
 
1646
 
 
1647
<blockquote>
 
1648
<pre>
 
1649
public class example {
 
1650
  public static void egg(Foo chips) {
 
1651
    exampleJNI.egg(Foo.getCPtr(chips));
 
1652
  }
 
1653
}
 
1654
</pre>
 
1655
</blockquote>
 
1656
 
 
1657
The module class is necessary as there is no such thing as a global in Java so all the C globals are put into this class. They are generated as static functions and so must be accessed as such by using the module name in the static function call:
 
1658
 
 
1659
<blockquote>
 
1660
<pre>
 
1661
example.egg(new Foo());
 
1662
</pre>
 
1663
</blockquote>
 
1664
 
 
1665
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 <tt>Foo</tt> can be passed to the <tt>egg</tt> function, whereas any <tt>long</tt> can be passed to the <tt>egg</tt> function in the intermediary JNI class.
 
1666
 
 
1667
<a name="module_class_pragmas"></a>
 
1668
<a name="n34"></a><H4>17.4.2.1 The Java module class pragmas</H4>
 
1669
 
 
1670
 
 
1671
The module class can be tailored through the use of pragmas, in the same manner as the intermediary JNI class. The pragmas are similarly named and are used in the same way. The complete list follows:
 
1672
 
 
1673
<p>
 
1674
<table BORDER>
 
1675
<tr VALIGN=TOP>
 
1676
<td><b>Pragma</b></td>
 
1677
<td><b>Description</b></td>
 
1678
</tr>
 
1679
<tr>
 
1680
    <td>modulebase            </td> <td>Base class for the module class</td>
 
1681
</tr>
 
1682
<tr>
 
1683
    <td>moduleclassmodifiers  </td> <td>Class modifiers for the module class</td>
 
1684
</tr>
 
1685
<tr>
 
1686
    <td>modulecode            </td> <td>Java code is copied verbatim into the module class</td>
 
1687
</tr>
 
1688
<tr>
 
1689
    <td>moduleimports         </td> <td>Java code, usually one or more import statements, placed before the module class definition</td>
 
1690
</tr>
 
1691
<tr>
 
1692
    <td>moduleinterfaces      </td> <td>Comma separated interface classes for the module class</td>
 
1693
</tr>
 
1694
 
 
1695
</table>
 
1696
 
 
1697
<p>
 
1698
 
 
1699
The pragma code appears in the generated module class like this:
 
1700
 
 
1701
<blockquote>
 
1702
<pre>
 
1703
[ moduleimports pragma ]
 
1704
[ modulemodifiers pragma ] class modulename extends [ modulebase pragma ] implements [ moduleinterfaces pragma ] {
 
1705
[ modulecode pragma ]
 
1706
... SWIG generated wrapper functions ...
 
1707
}
 
1708
</pre>
 
1709
</blockquote>
 
1710
 
 
1711
See <a href="#imclass_pragmas">The intermediary JNI class pragmas</a> section for further details on using pragmas.
 
1712
 
 
1713
 
 
1714
<a name="java_proxy_classes"></a>
 
1715
<a name="n35"></a><H3>17.4.3 Java proxy classes</H3>
 
1716
 
 
1717
 
 
1718
A Java proxy class is generated for each structure, union or C++ class that is wrapped.
 
1719
The default proxy class for our previous example looks like this:
 
1720
 
 
1721
<blockquote>
 
1722
<pre>
 
1723
public class Foo {
 
1724
  private long swigCPtr;
 
1725
  protected boolean swigCMemOwn;
 
1726
 
 
1727
  protected Foo(long cPtr, boolean cMemoryOwn) {
 
1728
    swigCMemOwn = cMemoryOwn;
 
1729
    swigCPtr = cPtr;
 
1730
  }
 
1731
 
 
1732
  protected void finalize() {
 
1733
    delete();
 
1734
  }
 
1735
 
 
1736
  public void delete() {
 
1737
    if(swigCPtr != 0 && swigCMemOwn) {
 
1738
      exampleJNI.delete_Foo(swigCPtr);
 
1739
      swigCMemOwn = false;
 
1740
    }
 
1741
    swigCPtr = 0;
 
1742
  }
 
1743
 
 
1744
  protected static long getCPtr(Foo obj) {
 
1745
    return obj.swigCPtr;
 
1746
  }
 
1747
 
 
1748
  public void setX(int x) {
 
1749
    exampleJNI.set_Foo_x(swigCPtr, x);
 
1750
  }
 
1751
 
 
1752
  public int getX() {
 
1753
    return exampleJNI.get_Foo_x(swigCPtr);
 
1754
  }
 
1755
 
 
1756
  public int spam(int num, Foo foo) {
 
1757
    return exampleJNI.Foo_spam(swigCPtr, num, Foo.getCPtr(foo));
 
1758
  }
 
1759
 
 
1760
  public Foo() {
 
1761
    this(exampleJNI.new_Foo(), true);
 
1762
  }
 
1763
}
 
1764
</pre>
 
1765
</blockquote>
 
1766
 
 
1767
 
 
1768
This class merely holds a pointer to the underlying C++ object (<tt>swigCPtr</tt>).
 
1769
It also contains all the methods in the C++ class it is proxying plus getters and setters for public
 
1770
member variables. These functions call the native methods in the intermediary JNI class. 
 
1771
The advantage of having this extra layer is the type safety that the proxy class functions offer. 
 
1772
It adds static type checking which leads to fewer surprises at runtime. 
 
1773
For example, you can see that if you attempt to use the <tt> spam() </tt> 
 
1774
function it will only compile when the parameters passed are an <tt>int</tt> and a <tt>Foo</tt>. 
 
1775
From a user's point of view, it makes the class work as if it were a Java class:
 
1776
 
 
1777
<blockquote>
 
1778
<pre>
 
1779
Foo f = new Foo();
 
1780
f.setX(3);
 
1781
int y = f.spam(5, new Foo());
 
1782
</pre>
 
1783
</blockquote>
 
1784
 
 
1785
<a name="memory_management"></a>
 
1786
<a name="n36"></a><H4>17.4.3.1 Memory management</H4>
 
1787
 
 
1788
 
 
1789
Each proxy class has an ownership flag <tt>swigCMemOwn</tt>.   The value of this
 
1790
flag determines who is responsible for deleting the underlying C++ object.   If set to <tt>true</tt>,
 
1791
the proxy class's finalizer will destroy the C++ object when the proxy class is 
 
1792
garbage collected.   If set to false, then the destruction of the proxy class has no effect on the C++ object.
 
1793
 
 
1794
<P>
 
1795
When an object is created by a constructor or returned by value, Java automatically takes
 
1796
ownership of the result. 
 
1797
On the other hand, when pointers or references are returned to Java, there is often no way to know where
 
1798
they came from.  Therefore, the ownership is set to false.  For example:
 
1799
 
 
1800
 
 
1801
<blockquote>
 
1802
<pre>
 
1803
class Foo {
 
1804
public:
 
1805
    Foo();
 
1806
    Foo bar1();
 
1807
    Foo &bar2();
 
1808
    Foo *bar2();
 
1809
};
 
1810
</pre>
 
1811
</blockquote>
 
1812
 
 
1813
In Java:
 
1814
 
 
1815
<blockquote>
 
1816
<pre>
 
1817
Foo f = new Foo();   //  f.swigCMemOwn = true
 
1818
Foo f1 = f.bar1();   // f1.swigCMemOwn = true
 
1819
Foo f2 = f.bar2();   // f2.swigCMemOwn = false
 
1820
Foo f3 = f.bar3();   // f3.swigCMemOwn = false
 
1821
</pre>
 
1822
</blockquote>
 
1823
 
 
1824
This behavior for pointers and references is especially important for classes that act as containers.  
 
1825
For example, if a method returns a pointer to an object
 
1826
that is contained inside another object, you definitely don't want
 
1827
Java to assume ownership and destroy it!
 
1828
 
 
1829
<p>
 
1830
For the most part, memory management issues remain hidden.  However,
 
1831
there are situations where you might have to manually
 
1832
change the ownership of an object.  For instance, consider code like this:
 
1833
 
 
1834
<blockquote>
 
1835
<pre>
 
1836
class Obj {};
 
1837
class Node {
 
1838
   Obj *value;
 
1839
public:
 
1840
   void set_value(Obj *v) { value = v; }
 
1841
};
 
1842
</pre>
 
1843
</blockquote>
 
1844
 
 
1845
Now, consider the following Java code:
 
1846
 
 
1847
<blockquote>
 
1848
<pre>
 
1849
Node n = new Node();    // Create a node
 
1850
{
 
1851
  Obj o = new Obj();    // Create an object
 
1852
  n.set_value(o);       // Set value
 
1853
}                       // o goes out of scope
 
1854
</pre>
 
1855
</blockquote>
 
1856
 
 
1857
In this case, the Node <tt>n</tt> is holding a reference to
 
1858
<tt>o</tt> internally.  However, SWIG has no way to know that this
 
1859
has occurred.  The Java proxy class still thinks that it has ownership of 
 
1860
<tt>o</tt>.  As <tt>o</tt> has gone out of scope, it could be garbage collected in which case the C++ destructor
 
1861
will be invoked and <tt>n</tt> will then be holding a stale-pointer to <tt>o</tt>.  If
 
1862
you're lucky, you will only get a segmentation fault.
 
1863
 
 
1864
<p>
 
1865
To work around this, the ownership flag of <tt>o</tt> needs changing to <tt>false</tt>. 
 
1866
The ownership flag is a private member variable of the proxy class so this is not possible without some customization of the proxy class. 
 
1867
This is achieved using a typemap to add pure Java code to the proxy class and is detailed later in the section on typemaps.
 
1868
 
 
1869
<p>
 
1870
Sometimes a function will create memory and return a pointer to a newly allocated object. 
 
1871
SWIG has no way of knowing this so by default the proxy class does not manage the returned object.
 
1872
However, you can tell the proxy class to manage the memory if you specify the <tt>%newobject</tt> directive. Consider:
 
1873
 
 
1874
<blockquote>
 
1875
<pre>
 
1876
class Obj {...};
 
1877
class Factory {
 
1878
public:
 
1879
    static Obj *createObj() { return new Obj(); }
 
1880
};
 
1881
</pre>
 
1882
</blockquote>
 
1883
 
 
1884
If we call the factory function, then we have to manually delete the memory:
 
1885
 
 
1886
<blockquote>
 
1887
<pre>
 
1888
Obj obj = Factory.createObj();   // obj.swigCMemOwn = false
 
1889
...
 
1890
obj.delete();
 
1891
</pre>
 
1892
</blockquote>
 
1893
 
 
1894
Now add in the %newobject directive:
 
1895
 
 
1896
<blockquote>
 
1897
<pre>
 
1898
%newobject Factory::createObj();
 
1899
 
 
1900
class Obj {...};
 
1901
class Factory {
 
1902
public:
 
1903
    static Obj *createObj() { return new Obj(); }
 
1904
};
 
1905
</pre>
 
1906
</blockquote>
 
1907
 
 
1908
A call to <tt>delete()</tt> is no longer necessary as the garbage collector will make the C++ destructor call because <tt>swigCMemOwn</tt> is now true.
 
1909
 
 
1910
<blockquote>
 
1911
<pre>
 
1912
Obj obj = Factory.createObj();   // obj.swigCMemOwn = true;
 
1913
...
 
1914
</pre>
 
1915
</blockquote>
 
1916
 
 
1917
 
 
1918
<a name="inheritance_mirroring"></a>
 
1919
<a name="n37"></a><H4>17.4.3.2 Inheritance</H4>
 
1920
 
 
1921
 
 
1922
Java proxy classes will mirror C++ inheritance chains. For example, given the base class <tt>Base</tt> and its derived class </tt>Derived</tt>:
 
1923
 
 
1924
<blockquote><pre>
 
1925
class Base {
 
1926
public:
 
1927
  virtual double foo();
 
1928
};
 
1929
 
 
1930
class Derived : public Base {
 
1931
public:
 
1932
  virtual double foo();
 
1933
};
 
1934
</pre></blockquote>
 
1935
 
 
1936
The base class is generated much like any other proxy class seen so far:
 
1937
 
 
1938
<blockquote><pre>
 
1939
public class Base {
 
1940
  private long swigCPtr;
 
1941
  protected boolean swigCMemOwn;
 
1942
 
 
1943
  protected Base(long cPtr, boolean cMemoryOwn) {
 
1944
    swigCMemOwn = cMemoryOwn;
 
1945
    swigCPtr = cPtr;
 
1946
  }
 
1947
 
 
1948
  protected void finalize() {
 
1949
    delete();
 
1950
  }
 
1951
 
 
1952
  public void delete() {
 
1953
    if(swigCPtr != 0 && swigCMemOwn) {
 
1954
      exampleJNI.delete_Base(swigCPtr);
 
1955
      swigCMemOwn = false;
 
1956
    }
 
1957
    swigCPtr = 0;
 
1958
  }
 
1959
 
 
1960
  protected static long getCPtr(Base obj) {
 
1961
    return obj.swigCPtr;
 
1962
  }
 
1963
 
 
1964
  public double foo() {
 
1965
    return exampleJNI.Base_foo(swigCPtr);
 
1966
  }
 
1967
 
 
1968
  public Base() {
 
1969
    this(exampleJNI.new_Base(), true);
 
1970
  }
 
1971
}
 
1972
</pre></blockquote>
 
1973
 
 
1974
The <tt>Derived</tt> class extends <tt>Base</tt> mirroring the C++ class inheritance hierarchy. 
 
1975
 
 
1976
<blockquote><pre>
 
1977
public class Derived extends Base {
 
1978
  private long swigCPtr;
 
1979
 
 
1980
  protected Derived(long cPtr, boolean cMemoryOwn) {
 
1981
    super(exampleJNI.SWIGDerivedToBase(cPtr), cMemoryOwn);
 
1982
    swigCPtr = cPtr;
 
1983
  }
 
1984
 
 
1985
  protected void finalize() {
 
1986
    delete();
 
1987
  }
 
1988
 
 
1989
  public void delete() {
 
1990
    if(swigCPtr != 0 && swigCMemOwn) {
 
1991
      exampleJNI.delete_Derived(swigCPtr);
 
1992
      swigCMemOwn = false;
 
1993
    }
 
1994
    swigCPtr = 0;
 
1995
    super.delete();
 
1996
  }
 
1997
 
 
1998
  protected static long getCPtr(Derived obj) {
 
1999
    return obj.swigCPtr;
 
2000
  }
 
2001
 
 
2002
  public double foo() {
 
2003
    return exampleJNI.Derived_foo(swigCPtr);
 
2004
  }
 
2005
 
 
2006
  public Derived() {
 
2007
    this(exampleJNI.new_Derived(), true);
 
2008
  }
 
2009
}
 
2010
</pre></blockquote>
 
2011
 
 
2012
Note the memory ownership is controlled by the base class. 
 
2013
However each class in the inheritance hierarchy has its own pointer value which is obtained during construction. 
 
2014
The <tt>SWIGDerivedToBase()</tt> call converts the pointer from a <tt>Derived *</tt> to a <tt>Base *</tt> as C++ compilers are free to implement 
 
2015
pointers in the inheritance hierarchy with different values. 
 
2016
 
 
2017
<p>
 
2018
 
 
2019
It is of course possible to extend <tt>Base</tt> using your own Java classes. 
 
2020
If <tt>Derived</tt> is provided by the C++ code, you could for example add in a pure Java class <tt>Extended</tt> derived from <tt>Base</tt>. 
 
2021
There is a caveat and that is any C++ code will not know about your pure Java class <tt>Extended</tt> so this type of derivation is restricted.
 
2022
However, true cross language polymorphism can be achieved using the <a href="#java_directors">directors</a> feature.
 
2023
<p>
 
2024
 
 
2025
 
 
2026
<a name="proxy_classes_gc"></a>
 
2027
<a name="n38"></a><H4>17.4.3.3 Proxy classes and garbage collection</H4>
 
2028
 
 
2029
 
 
2030
By default each proxy class has a <tt>delete()</tt> and a <tt>finalize()</tt> method. 
 
2031
The <tt>finalize()</tt> method calls <tt>delete()</tt> which frees any malloc'd memory for wrapped C structs or calls the C++ class destructors. 
 
2032
The idea is for <tt>delete()</tt> to be called when you have finished with the C/C++ object. 
 
2033
Ideally you need not call <tt>delete()</tt>, but rather leave it to the garbage collector to call it from the finalizer. 
 
2034
The unfortunate thing is that Sun, in their wisdom, do not guarantee that the finalizers will be called. 
 
2035
When a program exits, the garbage collector does not always call the finalizers. 
 
2036
Depending on what the finalizers do and which operating system you use, this may or may not be a problem. 
 
2037
<p>
 
2038
 
 
2039
If the <tt>delete()</tt> call into JNI code is just for memory handling, there is not a problem when run on most operating systems, for example Windows and Unix. 
 
2040
Say your JNI code creates memory on the heap which your finalizers should clean up, the finalizers may or may not be called before the program exits. 
 
2041
In Windows and Unix all memory that a process uses is returned to the system on exit, so this isn't a problem. 
 
2042
This is not the case in some operating systems like vxWorks. 
 
2043
If however, your finalizer calls into JNI code invoking the C++ destructor which in turn releases a TCP/IP socket for example, there is no guarantee that it will be released. 
 
2044
Note that with long running programs the garbage collector will eventually run, thereby calling any unreferenced object's finalizers.
 
2045
<p>
 
2046
 
 
2047
Some not so ideal solutions are:
 
2048
<ol>
 
2049
<li start=1>
 
2050
Call the <tt>System.runFinalizersOnExit(true)</tt> or <tt>Runtime.getRuntime().runFinalizersOnExit(true)</tt> to ensure the finalizers are called before the program exits. The catch is that this is a deprecated function call as the documenation says: 
 
2051
<blockquote><i>
 
2052
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.
 
2053
</i></blockquote> 
 
2054
In many cases you will be lucky and find that it works, but it is not to be advocated. 
 
2055
Have a look at <a href=http://java.sun.com>Sun's Java web site</a> and search for <tt>runFinalizersOnExit</tt>.
 
2056
</li>
 
2057
<p>
 
2058
<li>
 
2059
From jdk1.3 onwards a new function, <tt>addShutdownHook()</tt>, was introduced which is guaranteed to be called when your program exits. 
 
2060
You can encourage the garbage collector to call the finalizers, for example, add this static block to the class that has the <tt>main()</tt> function: 
 
2061
<blockquote><pre>
 
2062
  static {
 
2063
    Runtime.getRuntime().addShutdownHook( 
 
2064
      new Thread() {
 
2065
        public void run() { System.gc(); System.runFinalization(); }
573
2066
      }
574
 
    }
575
 
  };
576
 
</pre></blockquote>
577
 
<p>
578
 
The functions associated with this class can throw a C++ range exception for an out-of-bounds array access.   We can catch the C++ exception and rethrow it as a Java exception by specifying the following in an interface file :<p>
579
 
<p>
580
 
<blockquote><pre>
581
 
%exception {
 
2067
    );
 
2068
  }
 
2069
</pre></blockquote>
 
2070
Although this usually works, the documentation doesn't guarantee that <tt>runFinalization()</tt> will actually call the finalizers. 
 
2071
As the the shutdown hook is guaranteed you could also make a JNI call to clean up any resources that are being tracked by the C/C++ code.
 
2072
</li>
 
2073
<p>
 
2074
<li>
 
2075
Call the <tt>delete()</tt> function manually which will immediately invoke the C++ destructor. 
 
2076
As a suggestion it may be a good idea to set the object to null so that should the object be inadvertantly used again a Java null pointer exception is thrown, the alternative would crash the JVM by using a null C pointer. 
 
2077
For example given a SWIG generated class A:
 
2078
<blockquote><pre>
 
2079
A myA = new A();
 
2080
// use myA ...
 
2081
myA.delete();
 
2082
// any use of myA here would crash the JVM 
 
2083
myA=null;
 
2084
// any use of myA here would cause a Java null pointer exception to be thrown
 
2085
</pre></blockquote>
 
2086
The SWIG generated code ensures that the memory is not deleted twice, in the event the finalizers get called in addition to the manual <tt>delete()</tt> call.
 
2087
</li>
 
2088
 
 
2089
<p>
 
2090
<li>
 
2091
Write your own object manager in Java. 
 
2092
You could derive all SWIG classes from a single base class which could track which objects have had their finalizers run, then call the rest of them on program termination.
 
2093
The section on <a href="#java_typemaps">Java typemaps</a> details how to specify a pure Java base class.
 
2094
</li>
 
2095
</ol>
 
2096
 
 
2097
<a name="type_wrapper_classes"></a>
 
2098
<a name="n39"></a><H3>17.4.4 Type wrapper classes</H3>
 
2099
 
 
2100
 
 
2101
The generated type wrapper class, for say an <tt>int *</tt>, looks like this:
 
2102
 
 
2103
<blockquote><pre>
 
2104
public class SWIGTYPE_p_int {
 
2105
  private long swigCPtr;
 
2106
 
 
2107
  protected SWIGTYPE_p_int(long cPtr, boolean bFutureUse) {
 
2108
    swigCPtr = cPtr;
 
2109
  }
 
2110
 
 
2111
  protected SWIGTYPE_p_int() {
 
2112
    swigCPtr = 0;
 
2113
  }
 
2114
 
 
2115
  protected static long getCPtr(SWIGTYPE_p_int obj) {
 
2116
    return obj.swigCPtr;
 
2117
  }
 
2118
}
 
2119
</pre></blockquote>
 
2120
 
 
2121
The methods do not have public access, so by default it is impossible to do anything with objects of this class other than 
 
2122
pass them around. The methods in the class are part of the inner workings of SWIG. 
 
2123
If you need to mess around with pointers you will have to use some typemaps specific to the Java module to achieve this.
 
2124
The section on <a href="#java_typemaps">Java typemaps</a> details how to modify the generated code.
 
2125
 
 
2126
<p>
 
2127
Note that if you use a pointer or reference to a proxy class in a function then no type wrapper class is generated because the proxy class can be used
 
2128
as the function parameter. If however,  you need anything more complicated like a pointer to a pointer to a proxy class then a typewrapper class
 
2129
is generated for your use. 
 
2130
<p>
 
2131
 
 
2132
Note that SWIG generates a type wrapper class and not a proxy class when it has not parsed the definition of a type that gets used. 
 
2133
For example, say SWIG has not parsed the definition of <tt>class Snazzy</tt> because it is in a header file that you may have forgotten to use the <tt>%include</tt> directive on.
 
2134
Should SWIG parse <tt>Snazzy *</tt> being used in a function parameter, it will then generates a type wrapper class around a <tt>Snazzy</tt> pointer.
 
2135
Also recall from earlier that SWIG will use a pointer when a class is passed by value or by reference:
 
2136
 
 
2137
<blockquote>
 
2138
<pre>
 
2139
void spam(Snazzy *x, Snazzy &y, Snazzy z);
 
2140
</pre>
 
2141
</blockquote>
 
2142
 
 
2143
Should SWIG not know anything about <tt>Snazzy</tt> then a <tt>SWIGTYPE_p_Snazzy</tt> must be used for all 3 parameters in the <tt>spam</tt> function.
 
2144
The Java function generated is:
 
2145
 
 
2146
<blockquote>
 
2147
<pre>
 
2148
public static void spam(SWIGTYPE_p_Snazzy x, SWIGTYPE_p_Snazzy y, SWIGTYPE_p_Snazzy z) { ... }
 
2149
</pre>
 
2150
</blockquote>
 
2151
 
 
2152
<p>
 
2153
Note that typedefs are tracked by SWIG and the typedef name is used to construct the type wrapper class name. For example, consider the case where <tt>Snazzy</tt> is a typedef to an <tt>int</tt> which SWIG does parse:
 
2154
 
 
2155
 
 
2156
<blockquote>
 
2157
<pre>
 
2158
typedef int Snazzy;
 
2159
void spam(Snazzy *x, Snazzy &y, Snazzy z);
 
2160
</pre>
 
2161
</blockquote>
 
2162
 
 
2163
Because the typedefs have been tracked the Java function generated is:
 
2164
<blockquote>
 
2165
<pre>
 
2166
public static void spam(SWIGTYPE_p_int x, SWIGTYPE_p_int y, int z) { ... }
 
2167
</pre>
 
2168
</blockquote>
 
2169
 
 
2170
<p>
 
2171
 
 
2172
<a name="java_directors"></a>
 
2173
<a name="n40"></a><H2>17.5 Cross language polymorphism using directors (experimental)</H2>
 
2174
 
 
2175
 
 
2176
Proxy classes provide a natural, object-oriented way to wrap C++ classes.
 
2177
As described earlier, each proxy instance has an associated C++ instance, and method calls from Java to the proxy are passed to the C++ instance transparently via C wrapper functions.
 
2178
<p>
 
2179
 
 
2180
This arrangement is asymmetric in the sense that no corresponding mechanism exists to pass method calls down the inheritance chain from C++ to Java. 
 
2181
In particular, if a C++ class has been extended in Java (by deriving from the proxy class), these classes will not be visible from C++ code. 
 
2182
Virtual method calls from C++ are thus not able to access the lowest implementation in the inheritance chain.
 
2183
<p>
 
2184
 
 
2185
SWIG can address this problem and make the relationship between C++ classes and proxy classes more symmetric. 
 
2186
To achieve this goal, new classes called directors are introduced at the bottom of the C++ inheritance chain. 
 
2187
The job of the directors is to route method calls correctly, either to C++ implementations higher in the inheritance chain or to Java implementations lower in the inheritance chain. 
 
2188
The upshot is that C++ classes can be extended in Java and from C++ these extensions look exactly like native C++ classes. 
 
2189
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.
 
2190
 
 
2191
<a name="java_enabling_directors"></a>
 
2192
<a name="n41"></a><H3>17.5.1 Enabling directors</H3>
 
2193
 
 
2194
 
 
2195
The director feature is disabled by default.
 
2196
To use directors you must make two changes to the interface file.
 
2197
First, add the "directors" option to the %module directive, like this:
 
2198
 
 
2199
<blockquote>
 
2200
<pre>
 
2201
%module(directors="1") modulename
 
2202
</pre>
 
2203
</blockquote>
 
2204
 
 
2205
Without this option no director code will be generated.
 
2206
Second, you must use the %feature("director") directive to tell SWIG which classes and methods should get directors.
 
2207
The %feature directive can be applied globally, to specific classes, and to specific methods, like this:
 
2208
 
 
2209
<blockquote>
 
2210
<pre> 
 
2211
// generate directors for all classes that have virtual methods
 
2212
%feature("director");         
 
2213
 
 
2214
// genarate directors for all virtual methods in class Foo
 
2215
%feature("director") Foo;      
 
2216
 
 
2217
// generate a director for just Foo::bar()
 
2218
%feature("director") Foo::bar; 
 
2219
</pre>
 
2220
</blockquote>
 
2221
 
 
2222
You can use the %feature("nodirector") directive to turn off directors for specific classes or methods.
 
2223
So for example,
 
2224
 
 
2225
<blockquote>
 
2226
<pre>
 
2227
%feature("director") Foo;
 
2228
%feature("nodirector") Foo::bar;
 
2229
</pre>
 
2230
</blockquote>
 
2231
 
 
2232
will generate directors for all virtual methods of class Foo except bar().  
 
2233
<p>
 
2234
 
 
2235
Directors can also be generated implicitly through inheritance. 
 
2236
In the following, class Bar will get a director class that handles the methods one() and two() (but not three()):
 
2237
 
 
2238
<blockquote>
 
2239
<pre>
 
2240
%feature("director") Foo;
 
2241
class Foo {
 
2242
public:
 
2243
    virtual void one();
 
2244
    virtual void two();
 
2245
};
 
2246
 
 
2247
class Bar: public Foo {
 
2248
public:
 
2249
    virtual void three();
 
2250
};
 
2251
</pre>
 
2252
</blockquote>
 
2253
 
 
2254
<a name="java_directors_classes"></a>
 
2255
<a name="n42"></a><H3>17.5.2 Director classes</H3>
 
2256
 
 
2257
 
 
2258
For each class that has directors enabled, SWIG generates a new class that derives from both the class in question and a special <tt>Swig::Director</tt> class. 
 
2259
These new classes, referred to as director classes, can be loosely thought of as the C++ equivalent of the Java proxy classes.
 
2260
The director classes store a pointer to their underlying Java proxy classes.
 
2261
<p>
 
2262
 
 
2263
For simplicity let's ignore the <tt>Swig::Director</tt> class and refer to the original C++ class as the director's base class.
 
2264
By default, a director class extends all virtual methods in the inheritance chain of its base class (see the preceding section for how to modify this behavior).
 
2265
Thus all virtual method calls, whether they originate in C++ or in Java via proxy classes, eventually end up in at the implementation in the director class.
 
2266
The job of the director methods is to route these method calls to the appropriate place in the inheritance chain.
 
2267
By "appropriate place" we mean the method that would have been called if the C++ base class and its Java derived classes were seamlessly integrated.
 
2268
That seamless integration is exactly what the director classes provide, transparently skipping over all the messy JNI glue code that binds the two languages together.
 
2269
<p>
 
2270
 
 
2271
In reality, the "appropriate place" is one of only two possibilities: C++ or Java.
 
2272
Once this decision is made, the rest is fairly easy.
 
2273
If the correct implementation is in C++, then the lowest implementation of the method in the C++ inheritance chain is called explicitly.
 
2274
If the correct implementation is in Java, the Java API is used to call the method of the underlying Java object 
 
2275
(after which the usual virtual method resolution in Java automatically finds the right implementation).
 
2276
<p>
 
2277
 
 
2278
 
 
2279
<a name="java_directors_overhead"></a>
 
2280
<a name="n43"></a><H3>17.5.3 Overhead and code bloat</H3>
 
2281
 
 
2282
 
 
2283
Enabling directors for a class will generate a new director method for every virtual method in the class' inheritance chain.
 
2284
This alone can generate a lot of code bloat for large hierarchies.
 
2285
Method arguments that require complex conversions to and from Java types can result in large director methods.
 
2286
For this reason it is recommended that directors are selectively enabled only for specific classes that are likely to be extended in Java and used in C++.
 
2287
<p>
 
2288
 
 
2289
Although directors make it natural to mix native C++ objects with Java objects (as director objects),
 
2290
one should be aware of the obvious fact that method calls to Java objects from C++ will be much slower than calls to C++ objects.
 
2291
Additionally, compared to classes that do not use directors, the call routing in the director methods adds a small overhead.
 
2292
This situation can be optimized by selectively enabling director methods (using the %feature directive) for only those methods that are likely to be extended in Java.
 
2293
 
 
2294
 
 
2295
<a name="java_directors_example"></a>
 
2296
<a name="n44"></a><H3>17.5.4 Simple directors example</H3>
 
2297
 
 
2298
 
 
2299
<p>
 
2300
Consider the following SWIG interface file:
 
2301
</p>
 
2302
 
 
2303
<blockquote>
 
2304
<pre>
 
2305
%module(directors="1") example;
 
2306
 
 
2307
%feature("director") DirectorBase;
 
2308
 
 
2309
class DirectorBase {
 
2310
public:
 
2311
  virtual ~DirectorBase() {}
 
2312
  virtual void upcall_method() {}
 
2313
};
 
2314
 
 
2315
void callup(DirectorBase *director) {
 
2316
  director->upcall_method();
 
2317
}
 
2318
</pre>
 
2319
</blockquote>
 
2320
 
 
2321
The following <code>directorDerived</code> Java class is derived from the Java proxy class <code>DirectorBase</code> and overrides <code>upcall_method()</code>.
 
2322
When C++ code invokes <code>upcall_method()</code>, the SWIG-generated C++ code redirects the call via JNI to the Java <code>directorDerived</code> subclass.
 
2323
Naturally, the SWIG generated C++ code and the generated Java intermediate class marshall and convert arguments between C++ and Java when needed.
 
2324
</p>
 
2325
 
 
2326
<blockquote>
 
2327
<pre>
 
2328
public class directorDerived extends DirectorBase {
 
2329
  public directorDerived() {
 
2330
  }
 
2331
 
 
2332
  public void upcall_method() {
 
2333
    System.out.println("directorDerived::upcall_method() invoked.");
 
2334
  }
 
2335
}
 
2336
</pre>
 
2337
</blockquote>
 
2338
 
 
2339
Running the following Java code
 
2340
 
 
2341
<blockquote>
 
2342
<pre>
 
2343
directorDerived director = new directorDerived();
 
2344
example.callup(director);
 
2345
</pre>
 
2346
</blockquote>
 
2347
 
 
2348
will result in the following being output:
 
2349
 
 
2350
<blockquote>
 
2351
<pre>
 
2352
directorDerived::upcall_method() invoked.
 
2353
</pre>
 
2354
</blockquote>
 
2355
 
 
2356
<a name="common_customization"></a>
 
2357
<a name="n45"></a><H2>17.6 Common customization features</H2>
 
2358
 
 
2359
 
 
2360
An earlier section presented the absolute basics of C/C++ wrapping. If you do nothing
 
2361
but feed SWIG a header file, you will get an interface that mimics the behavior
 
2362
described.  However, sometimes this isn't enough to produce a nice module.  Certain
 
2363
types of functionality might be missing or the interface to certain functions might
 
2364
be awkward.  This section describes some common SWIG features that are used
 
2365
to improve the interface to existing C/C++ code.
 
2366
 
 
2367
<a name="helper_functions"></a>
 
2368
<a name="n46"></a><H3>17.6.1 C/C++ helper functions</H3>
 
2369
 
 
2370
 
 
2371
Sometimes when you create a module, it is missing certain bits of functionality. For
 
2372
example, if you had a function like this
 
2373
 
 
2374
<blockquote>
 
2375
<pre>
 
2376
typedef struct Image {...};
 
2377
void set_transform(Image *im, double m[4][4]);
 
2378
</pre>
 
2379
</blockquote>
 
2380
 
 
2381
it would be accessible from Java, but there may be no easy way to call it.
 
2382
The problem here is that a type wrapper class is generated for the two dimensional array parameter so
 
2383
there is no easy way to construct and manipulate a suitable
 
2384
<tt>double [4][4]</tt> value.   To fix this, you can write some extra C helper
 
2385
functions.  Just use the <tt>%inline</tt> directive. For example:
 
2386
 
 
2387
<blockquote>
 
2388
<pre>
 
2389
%inline %{
 
2390
/* Note: double[4][4] is equivalent to a pointer to an array double (*)[4] */
 
2391
double (*new_mat44())[4] {
 
2392
   return (double (*)[4]) malloc(16*sizeof(double));
 
2393
}
 
2394
void free_mat44(double (*x)[4]) {
 
2395
   free(x);
 
2396
}
 
2397
void mat44_set(double x[4][4], int i, int j, double v) {
 
2398
   x[i][j] = v;
 
2399
}
 
2400
double mat44_get(double x[4][4], int i, int j) {
 
2401
   return x[i][j];
 
2402
}
 
2403
%}
 
2404
</pre>
 
2405
</blockquote>
 
2406
 
 
2407
From Java, you could then write code like this:
 
2408
 
 
2409
<blockquote>
 
2410
<pre>
 
2411
Image im = new Image();
 
2412
SWIGTYPE_p_a_4__double a = example.new_mat44();
 
2413
example.mat44_set(a,0,0,1.0);
 
2414
example.mat44_set(a,1,1,1.0);
 
2415
example.mat44_set(a,2,2,1.0);
 
2416
...
 
2417
example.set_transform(im,a);
 
2418
example.free_mat44(a);
 
2419
</pre>
 
2420
</blockquote>
 
2421
 
 
2422
Admittedly, this is not the most elegant looking approach.  However, it works and it wasn't too
 
2423
hard to implement.  It is possible to improve on this using Java code, typemaps, and other
 
2424
customization features as covered in later sections, but sometimes helper functions are a quick and easy solution to difficult cases.  
 
2425
 
 
2426
<a name="class_extension"></a>
 
2427
<a name="n47"></a><H3>17.6.2 Class extension with %extend</H3>
 
2428
 
 
2429
 
 
2430
One of the more interesting features of SWIG is that it can extend
 
2431
structures and classes with new methods or constructors.
 
2432
Here is a simple example:
 
2433
 
 
2434
<blockquote>
 
2435
<pre>
 
2436
%module example
 
2437
%{
 
2438
#include "someheader.h"
 
2439
%}
 
2440
 
 
2441
struct Vector {
 
2442
   double x,y,z;
 
2443
};
 
2444
 
 
2445
%extend Vector {
 
2446
   char *toString() {
 
2447
       static char tmp[1024];
 
2448
       sprintf(tmp,"Vector(%g,%g,%g)", self->x,self->y,self->z);
 
2449
       return tmp;
 
2450
   }
 
2451
   Vector(double x, double y, double z) {
 
2452
       Vector *v = (Vector *) malloc(sizeof(Vector));
 
2453
       v->x = x;
 
2454
       v->y = y;
 
2455
       v->z = z;
 
2456
       return v;
 
2457
   }
 
2458
};
 
2459
</pre>
 
2460
</blockquote>
 
2461
 
 
2462
Now, in Java
 
2463
 
 
2464
<blockquote>
 
2465
<pre>
 
2466
Vector v = new Vector(2,3,4);
 
2467
System.out.println(v);
 
2468
</pre>
 
2469
</blockquote>
 
2470
will display
 
2471
 
 
2472
<blockquote>
 
2473
<pre>
 
2474
Vector(2,3,4)
 
2475
</pre>
 
2476
</blockquote>
 
2477
 
 
2478
<tt>%extend</tt> works with both C and C++ code.  It does not modify the underlying object
 
2479
in any way---the extensions only show up in the Java interface.
 
2480
 
 
2481
<a name="exception_handling"></a>
 
2482
<a name="n48"></a><H3>17.6.3 Exception handling with %exception</H3>
 
2483
 
 
2484
 
 
2485
If a C or C++ function throws an error, you may want to convert that error into a Java
 
2486
exception. To do this, you can use the <tt>%exception</tt> directive.  The <tt>%exception</tt> directive
 
2487
simply lets you rewrite part of the generated wrapper code to include an error check.
 
2488
 
 
2489
<p>
 
2490
In C, a function often indicates an error by returning a status code (a negative number
 
2491
or a NULL pointer perhaps).  Here is a simple example of how you might handle that:
 
2492
 
 
2493
<blockquote>
 
2494
<pre>
 
2495
%exception malloc {
 
2496
  $action
 
2497
  if (!result) {
 
2498
    jclass clazz = (*jenv)->FindClass(jenv, "java/lang/OutOfMemoryError");
 
2499
    (*jenv)->ThrowNew(jenv, clazz, "Not enough memory");
 
2500
    return $null;
 
2501
  }
 
2502
}
 
2503
void *malloc(size_t nbytes);
 
2504
</pre>
 
2505
</blockquote>
 
2506
 
 
2507
In Java,
 
2508
 
 
2509
<blockquote>
 
2510
<pre>
 
2511
SWIGTYPE_p_void a = example.malloc(2000000000);
 
2512
</pre>
 
2513
</blockquote>
 
2514
 
 
2515
will produce a familiar looking Java exception:
 
2516
 
 
2517
<blockquote>
 
2518
<pre>
 
2519
Exception in thread "main" java.lang.OutOfMemoryError: Not enough memory
 
2520
        at exampleJNI.malloc(Native Method)
 
2521
        at example.malloc(example.java:16)
 
2522
        at main.main(main.java:112)
 
2523
</pre>
 
2524
</blockquote>
 
2525
 
 
2526
If a library provides some kind of general error handling framework, you can also use
 
2527
that.  For example:
 
2528
 
 
2529
<blockquote>
 
2530
<pre>
 
2531
%exception malloc {
 
2532
  $action
 
2533
  if (err_occurred()) {
 
2534
    jclass clazz = (*jenv)->FindClass(jenv, "java/lang/OutOfMemoryError");
 
2535
    (*jenv)->ThrowNew(jenv, clazz, "Not enough memory");
 
2536
    return $null;
 
2537
  }
 
2538
}
 
2539
void *malloc(size_t nbytes);
 
2540
</pre>
 
2541
</blockquote>
 
2542
 
 
2543
No declaration name is given to <tt>%exception</tt>, it is applied to all wrapper functions.
 
2544
The <tt> $action </tt> is a SWIG special variable and is replaced by the C/C++ function call being wrapped.
 
2545
The <tt> return $null; </tt> handles all native method return types, namely those that have a void return and those that do not. 
 
2546
This is useful for typemaps that will be used in native method returning all return types. 
 
2547
See the section on
 
2548
<a href="#special_variables">Java special variables</a> for further explanation.
 
2549
 
 
2550
<p>
 
2551
C++ exceptions are also easy to handle.  
 
2552
We can catch the C++ exception and rethrow it as a Java exception like this:<p>
 
2553
 
 
2554
<blockquote>
 
2555
<pre>
 
2556
%exception getitem {
582
2557
  try {
583
 
    $action
584
 
  }
585
 
  catch (RangeError) {
586
 
    jclass clazz = jenv-&gt;FindClass("java/lang/Exception");
587
 
    jenv-&gt;ThrowNew(clazz, "Range error");
 
2558
     $action
 
2559
  } catch (std::out_of_range &e) {
 
2560
    jclass clazz = jenv->FindClass("java/lang/Exception");
 
2561
    jenv->ThrowNew(clazz, "Range error");
588
2562
    return $null;
589
 
  }
590
 
}
591
 
</pre></blockquote>
592
 
 
593
 
What the above does is define swig exception handlers for two types of functions; namely those that are have a void return and those that do not. Both are needed to cover all types of JNI functions. The code excerpts above are inserted into all the JNI functions. The $action call is replaced by the C/C++ code being executed by the wrapper, for example the <tt>setitem</tt> call. Another special variable, $null, is useful for typemaps that will be used in JNI functions returning all return types. See the section on
594
 
<a href="#n124">Typemap variables</a> for further explanation.
595
 
<p>
596
 
 
597
 
 
598
 
The above uses the C++ JNI calling syntax as opposed to the C calling syntax and so will not compile as C.
599
 
It is however possible to write JNI calls in <a href="#n126">typemaps for both C and C++ compilation</a>. 
600
 
The <tt>ThrowNew()</tt> JNI function must take a class derived from java.lang.Exception. The %exception typemap above could be tailored to individual needs.
601
 
<p>
602
 
When the C++ class throws a RangeError exception, our wrapper functions will catch it, turn it into a Java exception, and allow a graceful death as opposed to having some sort of mysterious JVM crash. Since SWIG's exception handling is user-definable, we are not limited to C++ exception handling. Please see the chapter on exception handling for more details and using the <tt>exception.i</tt> library for writing language-independent exception handlers.<p>
603
 
See the chapter on "<a href="Exceptions.html">Exception Handling</a>" for further examples on exceptions and how %exception can be targeted for use in a particular function.
604
 
<p>
605
 
If we use the following code:
606
 
 
607
 
<blockquote><pre>
608
 
final int SIZE=5;
609
 
DoubleArray arr = new DoubleArray(SIZE);
610
 
for (int i=0; i&lt;SIZE; i++)
611
 
  arr.setitem(i, (double)i);
612
 
for (int i=0; i&lt;SIZE+1; i++) //Note the array over bounds
613
 
  System.out.println(i + " " + arr.getitem(i));
614
 
</pre></blockquote>
615
 
 
616
 
Something similar to the following will be output when it is run:
617
 
<blockquote><pre>
618
 
0 0.0
619
 
1 1.0
620
 
2 2.0
621
 
3 3.0
622
 
4 4.0
623
 
Exception in thread "main" java.lang.Exception: Range error
624
 
        at example.DoubleArray_getitem(Native Method)
625
 
        at example.DoubleArray_getitem(Compiled Code)
626
 
        at DoubleArray.getitem(Compiled Code)
627
 
        at main.main(Compiled Code)
628
 
</pre></blockquote>
629
 
<p>
630
 
 
631
 
<a name="n7"></a><h2>Remapping C datatypes with typemaps</h2>
632
 
This section describes how SWIG's treatment of various C/C++ datatypes can be remapped using the SWIG <tt>%typemap</tt> directive.   While not required, this section assumes some familiarity with the JNI. The reader is advised to be familiar with the chapter on SWIG typemaps. Also it is best to consult JNI documentation either online at <a href=http://java.sun.com>Sun's Java web site</a> or a good book on the JNI. The following two books are recommended:<p>
 
2563
   }
 
2564
}
 
2565
 
 
2566
class Base {
 
2567
public:
 
2568
     Foo *getitem(int index);      // Exception handler added
 
2569
     ...
 
2570
};
 
2571
</pre>
 
2572
</blockquote>
 
2573
 
 
2574
The examples above first use the C JNI calling syntax then the C++ JNI calling syntax. The C++ calling syntax will not compile as C and also visa versa.
 
2575
It is however possible to write JNI calls which will compile under both C and C++ and is covered in the <a href="#typemaps_for_c_and_c++">Typemaps for both C and C++ compilation</a> section. 
 
2576
 
 
2577
<p>
 
2578
The language-independent <tt>exception.i</tt> library file can also be used
 
2579
to raise exceptions.  See the <a href="Library.html">SWIG Library</a> chapter.
 
2580
 
 
2581
<a name="method_access"></a>
 
2582
<a name="n49"></a><H3>17.6.4 Method access with %javamethodmodifiers</H3>
 
2583
 
 
2584
 
 
2585
A Java feature called <tt>%javamethodmodifiers</tt> can be used to change the method modifiers from the default <tt>public</tt>. It applies to both module class methods and proxy class methods. For example:
 
2586
 
 
2587
<blockquote>
 
2588
<pre>
 
2589
%javamethodmodifiers protect_me() "protected";
 
2590
void protect_me();
 
2591
</pre>
 
2592
</blockquote>
 
2593
 
 
2594
Will produce the method in the module class with protected access.
 
2595
 
 
2596
<blockquote>
 
2597
<pre>
 
2598
protected static void protect_me() {
 
2599
  exampleJNI.protect_me();
 
2600
}
 
2601
</pre>
 
2602
</blockquote>
 
2603
 
 
2604
<a name="tips_techniques"></a>
 
2605
<a name="n50"></a><H2>17.7 Tips and techniques</H2>
 
2606
 
 
2607
 
 
2608
Although SWIG is largely automatic, there are certain types of wrapping problems that
 
2609
require additional user input.    Examples include dealing with output parameters,
 
2610
strings and arrays.   This chapter discusses the common techniques for
 
2611
solving these problems.
 
2612
 
 
2613
<a name="input_output_parameters"></a>
 
2614
<a name="n51"></a><H3>17.7.1 Input and output parameters using primitive pointers and references</H3>
 
2615
 
 
2616
 
 
2617
A common problem in some C programs is handling parameters passed as simple pointers or references.  For
 
2618
example:
 
2619
 
 
2620
<blockquote>
 
2621
<pre>
 
2622
void add(int x, int y, int *result) {
 
2623
   *result = x + y;
 
2624
}
 
2625
</pre>
 
2626
</blockquote>
 
2627
 
 
2628
or perhaps
 
2629
 
 
2630
<blockquote>
 
2631
<pre>
 
2632
int sub(int *x, int *y) {
 
2633
   return *x-*y;
 
2634
}
 
2635
</pre>
 
2636
</blockquote>
 
2637
 
 
2638
The <tt>typemaps.i</tt> library file will help in these situations.  For example:
 
2639
 
 
2640
<blockquote>
 
2641
<pre>
 
2642
%module example
 
2643
%include "typemaps.i"
 
2644
 
 
2645
void add(int, int, int *OUTPUT);
 
2646
int  sub(int *INPUT, int *INPUT);
 
2647
</pre>
 
2648
</blockquote>
 
2649
 
 
2650
In Java, this allows you to pass simple values.  For example:
 
2651
 
 
2652
<blockquote>
 
2653
<pre>
 
2654
int result = example.sub(7,4);
 
2655
System.out.println("7 - 4 = " + result);
 
2656
int[] sum = {0};
 
2657
example.add(3,4,sum);
 
2658
System.out.println("3 + 4 = " + sum[0]);
 
2659
</pre>
 
2660
</blockquote>
 
2661
 
 
2662
Which will display:
 
2663
<blockquote> <pre>
 
2664
7 - 4 = 3
 
2665
3 + 4 = 7
 
2666
</pre></blockquote>
 
2667
 
 
2668
Notice how the <tt>INPUT</tt> parameters allow integer values to be passed instead of pointers
 
2669
and how the <tt>OUTPUT</tt> parameter will return the result in the first element of the integer array.
 
2670
 
 
2671
<p>
 
2672
If you don't want to use the names <tt>INPUT</tt> or <tt>OUTPUT</tt>, use the <tt>%apply</tt>
 
2673
directive.  For example:
 
2674
 
 
2675
<blockquote>
 
2676
<pre>
 
2677
%module example
 
2678
%include "typemaps.i"
 
2679
 
 
2680
%apply int *OUTPUT { int *result };
 
2681
%apply int *INPUT  { int *x, int *y};
 
2682
 
 
2683
void add(int x, int y, int *result);
 
2684
int  sub(int *x, int *y);
 
2685
</pre>
 
2686
</blockquote>
 
2687
 
 
2688
<p>
 
2689
If a function mutates one of its parameters like this,
 
2690
 
 
2691
<blockquote>
 
2692
<pre>
 
2693
void negate(int *x) {
 
2694
   *x = -(*x);
 
2695
}
 
2696
</pre>
 
2697
</blockquote>
 
2698
 
 
2699
you can use <tt>INOUT</tt> like this:
 
2700
 
 
2701
<blockquote>
 
2702
<pre>
 
2703
%include "typemaps.i"
 
2704
...
 
2705
void negate(int *INOUT);
 
2706
</pre>
 
2707
</blockquote>
 
2708
 
 
2709
In Java, the input parameter is the first element in a 1 element array and is replaced by the output of the function. For example:
 
2710
 
 
2711
<blockquote>
 
2712
<pre>
 
2713
int[] neg = {3};
 
2714
example.negate(neg);
 
2715
System.out.println("Negative of 3 = " + neg[0]);
 
2716
</pre>
 
2717
</blockquote>
 
2718
 
 
2719
And no prizes for guessing the output:
 
2720
<blockquote><pre>
 
2721
Negative of 3 = -3
 
2722
</pre></blockquote>
 
2723
 
 
2724
These typemaps can also be applied to C++ references. 
 
2725
The above examples would work the same if they had been defined using references instead of pointers.
 
2726
For example, the Java code to use the <tt>negate</tt> function would be the same if it were defined either as it is above: 
 
2727
 
 
2728
<blockquote>
 
2729
<pre>
 
2730
void negate(int *INOUT);
 
2731
</pre>
 
2732
</blockquote>
 
2733
or using a reference:
 
2734
<blockquote>
 
2735
<pre>
 
2736
void negate(int &INOUT);
 
2737
</pre>
 
2738
</blockquote>
 
2739
 
 
2740
<p>
 
2741
Note: Since most Java primitive types are immutable and are passed by value, it is not possible to
 
2742
perform in-place modification of a type passed as a parameter.
 
2743
 
 
2744
<p>
 
2745
Be aware that the primary purpose of the <tt>typemaps.i</tt> file is to support primitive datatypes.
 
2746
Writing a function like this
 
2747
 
 
2748
<blockquote>
 
2749
<pre>
 
2750
void foo(Bar *OUTPUT);
 
2751
</pre>
 
2752
</blockquote>
 
2753
 
 
2754
will not have the intended effect since <tt>typemaps.i</tt> does not define an OUTPUT rule for <tt>Bar</tt>.
 
2755
 
 
2756
<a name="simple_pointers"></a>
 
2757
<a name="n52"></a><H3>17.7.2 Simple pointers</H3>
 
2758
 
 
2759
 
 
2760
If you must work with simple pointers such as <tt>int *</tt> or <tt>double *</tt> another approach to using 
 
2761
<tt>typemaps.i</tt> is to use the <tt>cpointer.i</tt> pointer library file.    For example:
 
2762
 
 
2763
<blockquote>
 
2764
<pre>
 
2765
%module example
 
2766
%include "cpointer.i"
 
2767
 
 
2768
extern void add(int x, int y, int *result);
 
2769
%pointer_functions(int, intp);
 
2770
</pre>
 
2771
</blockquote>
 
2772
 
 
2773
The <tt>%pointer_functions(type,name)</tt> macro generates five helper functions that can be used to create,
 
2774
destroy, copy, assign, and dereference a pointer.  In this case, the functions are as follows:
 
2775
 
 
2776
<blockquote>
 
2777
<pre>
 
2778
int  *new_intp();
 
2779
int  *copy_intp(int *x);
 
2780
void  delete_intp(int *x);
 
2781
void  intp_assign(int *x, int value);
 
2782
int   intp_value(int *x);
 
2783
</pre>
 
2784
</blockquote>
 
2785
 
 
2786
In Java, you would use the functions like this:
 
2787
 
 
2788
<blockquote>
 
2789
<pre>
 
2790
SWIGTYPE_p_int intPtr = example.new_intp();
 
2791
example.add(3,4,intPtr);
 
2792
int result = example.intp_value(intPtr);
 
2793
System.out.println("3 + 4 = " + result);
 
2794
</pre>
 
2795
</blockquote>
 
2796
 
 
2797
If you replace <tt>%pointer_functions(int,intp)</tt> by <tt>%pointer_class(int,intp)</tt>, the interface is more class-like.
 
2798
 
 
2799
<blockquote>
 
2800
<pre>
 
2801
intp intPtr = new intp();
 
2802
example.add(3,4,intPtr.cast());
 
2803
int result = intPtr.value();
 
2804
System.out.println("3 + 4 = " + result);
 
2805
</pre>
 
2806
</blockquote>
 
2807
 
 
2808
See the <a href="Library.html">SWIG Library</a> chapter for further details.
 
2809
 
 
2810
<a name="c_arrays"></a>
 
2811
<a name="n53"></a><H3>17.7.3 Wrapping C arrays with Java arrays</H3>
 
2812
 
 
2813
 
 
2814
SWIG can wrap arrays in a more natural Java manner than the default by using the <tt>arrays_java.i</tt> library file. 
 
2815
Let's consider an example:
 
2816
 
 
2817
<blockquote>
 
2818
<pre>
 
2819
%include "arrays_java.i";
 
2820
int array[4];
 
2821
void populate(int x[]) {
 
2822
    int i;
 
2823
    for (i=0; i<4; i++)
 
2824
        x[i] = 100 + i;
 
2825
}
 
2826
</pre>
 
2827
</blockquote>
 
2828
 
 
2829
These one dimensional arrays can then be used as if they were Java arrays:
 
2830
 
 
2831
<blockquote>
 
2832
<pre>
 
2833
int[] array = new int[4];
 
2834
example.populate(array);
 
2835
 
 
2836
System.out.print("array: ");
 
2837
for (int i=0; i&lt;array.length; i++)
 
2838
    System.out.print(array[i] + " ");
 
2839
 
 
2840
example.setArray(array);
 
2841
 
 
2842
int[] global_array = example.getArray();
 
2843
 
 
2844
System.out.print("\nglobal_array: ");
 
2845
for (int i=0; i&lt;array.length; i++)
 
2846
    System.out.print(global_array[i] + " ");
 
2847
</pre>
 
2848
</blockquote>
 
2849
 
 
2850
Java arrays are always passed by reference, so any changes a function makes to the array will be seen by the calling function. 
 
2851
Here is the output after running this code:
 
2852
 
 
2853
<blockquote>
 
2854
<pre>
 
2855
array: 100 101 102 103
 
2856
global_array: 100 101 102 103
 
2857
</pre>
 
2858
</blockquote>
 
2859
 
 
2860
Note that for assigning array variables the length of the C variable is used, so it is possible to use a Java array that is bigger than the C code will cope with.
 
2861
Only the number of elements in the C array will be used.
 
2862
However, if the Java array is not large enough then you are likely to get a segmentation fault or access violation, just like you would in C.
 
2863
When arrays are used in functions like <tt>populate</tt>, the size of the C array passed to the function is determined by the size of the Java array.
 
2864
<p>
 
2865
Please be aware that the typemaps in this library are not efficient as all the elements are copied from the Java array to a C array whenever the array is passed to and from JNI code.
 
2866
There is an alternative approach using the SWIG array library and this is covered in the next.
 
2867
 
 
2868
<a name="unbounded_c_arrays"></a>
 
2869
<a name="n54"></a><H3>17.7.4 Unbounded C Arrays</H3>
 
2870
 
 
2871
 
 
2872
Sometimes a C function expects an array to be passed as a pointer.  For example,
 
2873
 
 
2874
<blockquote>
 
2875
<pre>
 
2876
int sumitems(int *first, int nitems) {
 
2877
    int i, sum = 0;
 
2878
    for (i = 0; i &lt; nitems; i++) {
 
2879
        sum += first[i];
 
2880
    }
 
2881
    return sum;
 
2882
}
 
2883
</pre>
 
2884
</blockquote>
 
2885
 
 
2886
One of the ways to wrap this is to apply the Java array typemaps that come in the <tt>arrays_java.i</tt> library file:
 
2887
 
 
2888
<blockquote>
 
2889
<pre>
 
2890
%include "arrays_java.i"
 
2891
%apply int[ANY] {int *};
 
2892
</pre>
 
2893
</blockquote>
 
2894
 
 
2895
The <tt>ANY</tt> size will ensure the typemap is applied to arrays of all sizes.
 
2896
You could narrow the typemap matching rules by specifying a particular array size.
 
2897
Now you can use a pure Java array and pass it to the C code:
 
2898
 
 
2899
<blockquote>
 
2900
<pre>
 
2901
int[] array = new int[10000000];          // Array of 10-million integers
 
2902
for (int i=0; i&lt;array.length; i++) {      // Set some values
 
2903
  array[i] = i;
 
2904
}
 
2905
int sum = example.sumitems(array,10000);
 
2906
System.out.println("Sum = " + sum);
 
2907
</pre>
 
2908
</blockquote>
 
2909
 
 
2910
and the sum would be displayed:
 
2911
 
 
2912
<blockquote>
 
2913
<pre>
 
2914
Sum = 49995000
 
2915
</pre>
 
2916
</blockquote>
 
2917
 
 
2918
This approach is probably the most natural way to use arrays.
 
2919
However, it suffers from performance problems when using large arrays as a lot of copying
 
2920
of the elements occurs in transferring the array from the Java world to the C++ world.
 
2921
An alternative approach to using Java arrays for C arrays is to use an alternative SWIG library file <tt>carrays.i</tt>.
 
2922
This approach can be more efficient for large arrays as the array is accessed one element at a time.
 
2923
For example:
 
2924
 
 
2925
<blockquote>
 
2926
<pre>
 
2927
%include "carrays.i"
 
2928
%array_functions(int, intArray);
 
2929
</pre>
 
2930
</blockquote>
 
2931
 
 
2932
The <tt>%array_functions(type,name)</tt> macro generates four helper functions that can be used to create and
 
2933
destroy arrays and operate on elements.  In this case, the functions are as follows:
 
2934
 
 
2935
<blockquote>
 
2936
<pre>
 
2937
int *new_intArray(int nelements);
 
2938
void delete_intArray(int *x);
 
2939
int intArray_getitem(int *x, int index);
 
2940
void intArray_setitem(int *x, int index, int value);
 
2941
</pre>
 
2942
</blockquote>
 
2943
 
 
2944
In Java, you would use the functions like this:
 
2945
 
 
2946
<blockquote>
 
2947
<pre>
 
2948
SWIGTYPE_p_int array = example.new_intArray(10000000);  // Array of 10-million integers
 
2949
for (int i=0; i<10000; i++) {                           // Set some values
 
2950
    example.intArray_setitem(array,i,i);
 
2951
}
 
2952
int sum = example.sumitems(array,10000);
 
2953
System.out.println("Sum = " + sum);
 
2954
</pre>
 
2955
</blockquote>
 
2956
 
 
2957
If you replace <tt>%array_functions(int,intp)</tt> by <tt>%array_class(int,intp)</tt>, the interface is more class-like
 
2958
and a couple more helper functions are available for casting between the array and the type wrapper class.
 
2959
 
 
2960
<blockquote>
 
2961
<pre>
 
2962
%include "carrays.i"
 
2963
%array_class(int, intArray);
 
2964
</pre>
 
2965
</blockquote>
 
2966
 
 
2967
The <tt>%array_class(type, name)</tt> macro creates wrappers for an unbounded array object that
 
2968
can be passed around as a simple pointer like <tt>int *</tt> or <tt>double *</tt>.
 
2969
For instance, you will be able to do this in Java:
 
2970
 
 
2971
<blockquote>
 
2972
<pre>
 
2973
intArray array = new intArray(10000000);  // Array of 10-million integers
 
2974
for (int i=0; i<10000; i++) {             // Set some values
 
2975
    array.setitem(i,i);
 
2976
}
 
2977
int sum = example.sumitems(array.cast(),10000);
 
2978
System.out.println("Sum = " + sum);
 
2979
</pre>
 
2980
</blockquote>
 
2981
 
 
2982
The array "object" created by <tt>%array_class()</tt> does not
 
2983
encapsulate pointers inside a special array object.  In fact, there is
 
2984
no bounds checking or safety of any kind (just like in C).  Because of
 
2985
this, the arrays created by this library are extremely low-level
 
2986
indeed.  You can't iterate over them nor can you even query their
 
2987
length.  In fact, any valid memory address can be accessed if you want
 
2988
(negative indices, indices beyond the end of the array, etc.).
 
2989
Needless to say, this approach is not going to suit all applications.
 
2990
On the other hand, this low-level approach is extremely efficient and
 
2991
well suited for applications in which you need to create buffers,
 
2992
package binary data, etc.
 
2993
 
 
2994
<a name="java_typemaps"></a>
 
2995
<a name="n55"></a><H2>17.8 Java typemaps</H2>
 
2996
 
 
2997
 
 
2998
This section describes how you can modify SWIG's default wrapping behavior
 
2999
for various C/C++ datatypes using the <tt>%typemap</tt> directive.   
 
3000
You are advised to be familiar with the the material in the "<a href="Typemaps.html">Typemaps</a>" chapter.
 
3001
While not absolutely essential knowledge, this section assumes some familiarity with the Java Native Interface (JNI). 
 
3002
JNI documentation can be consulted either online at <a href=http://java.sun.com>Sun's Java web site</a> or from a good JNI book. 
 
3003
The following two books are recommended:<p>
633
3004
<ul>
634
3005
<li> Title: 'Essential JNI: Java Native Interface.' Author: Rob Gordon. Publisher: Prentice Hall. ISBN: 0-13-679895-0.  </li>
635
3006
<li> Title: 'The Java Native Interface: Programmer's Guide and Specification.' Author: Sheng Liang. Publisher: Addison-Wesley. ISBN: 0-201-32577-2.  </li>
636
3007
</ul>
637
 
<a name="n121"></a><h3>Default type mapping</h3>
 
3008
 
 
3009
<p>
 
3010
Before proceeding, it should be stressed that typemaps are not a required 
 
3011
part of using SWIG---the default wrapping behavior is enough in most cases.
 
3012
Typemaps are only used if you want to change some aspect of the generated code.
 
3013
 
 
3014
<a name="default_primitive_type_mappings"></a>
 
3015
<a name="n56"></a><H3>17.8.1 Default primitive type mappings</H3>
 
3016
 
 
3017
 
638
3018
The following table lists the default type mapping from Java to C/C++.<p>
639
3019
<table BORDER>
640
3020
<tr>
644
3024
</tr>
645
3025
 
646
3026
<tr>
 
3027
<td>bool<br> const bool & </td>
 
3028
<td>boolean</td>
 
3029
<td>jboolean</td>
 
3030
</tr>
 
3031
 
 
3032
<tr>
 
3033
<td>char<br>const char &</td>
647
3034
<td>char</td>
 
3035
<td>jchar</td>
 
3036
</tr>
 
3037
 
 
3038
<tr>
 
3039
<td>signed char<br>const signed char &</td>
648
3040
<td>byte</td>
649
3041
<td>jbyte</td>
650
3042
</tr>
651
3043
 
652
3044
<tr>
653
 
<td>unsigned char</td>
654
 
<td>short</td>
655
 
<td>jshort</td>
656
 
</tr>
657
 
 
658
 
<tr>
659
 
<td>short</td>
660
 
<td>short</td>
661
 
<td>jshort</td>
662
 
</tr>
663
 
 
664
 
<tr>
665
 
<td>unsigned short</td>
666
 
<td>int</td>
667
 
<td>jint</td>
668
 
</tr>
669
 
 
670
 
<tr>
671
 
<td>int</td>
672
 
<td>int</td>
673
 
<td>jint</td>
674
 
</tr>
675
 
 
676
 
<tr>
677
 
<td>unsigned int</td>
678
 
<td>long</td>
679
 
<td>jlong</td>
680
 
</tr>
681
 
 
682
 
<tr>
683
 
<td>long</td>
684
 
<td>int</td>
685
 
<td>jint</td>
686
 
</tr>
687
 
 
688
 
<tr>
689
 
<td>unsigned long</td>
690
 
<td>long</td>
691
 
<td>jlong</td>
692
 
</tr>
693
 
 
694
 
<tr>
695
 
<td>long long</td>
696
 
<td>long</td>
697
 
<td>jlong</td>
698
 
</tr>
699
 
 
700
 
<tr>
701
 
<td>unsigned long long</td>
 
3045
<td>unsigned char<br>const unsigned char &</td>
 
3046
<td>short</td>
 
3047
<td>jshort</td>
 
3048
</tr>
 
3049
 
 
3050
<tr>
 
3051
<td>short<br>const short &</td>
 
3052
<td>short</td>
 
3053
<td>jshort</td>
 
3054
</tr>
 
3055
 
 
3056
<tr>
 
3057
<td>unsigned short<br> const unsigned short &</td>
 
3058
<td>int</td>
 
3059
<td>jint</td>
 
3060
</tr>
 
3061
 
 
3062
<tr>
 
3063
<td>int<br> const int &</td>
 
3064
<td>int</td>
 
3065
<td>jint</td>
 
3066
</tr>
 
3067
 
 
3068
<tr>
 
3069
<td>unsigned int<br> const unsigned int &</td>
 
3070
<td>long</td>
 
3071
<td>jlong</td>
 
3072
</tr>
 
3073
 
 
3074
<tr>
 
3075
<td>long<br>const long &</td>
 
3076
<td>int</td>
 
3077
<td>jint</td>
 
3078
</tr>
 
3079
 
 
3080
<tr>
 
3081
<td>unsigned long<br>const unsigned long &</td>
 
3082
<td>long</td>
 
3083
<td>jlong</td>
 
3084
</tr>
 
3085
 
 
3086
<tr>
 
3087
<td>long long<br> const long long &</td>
 
3088
<td>long</td>
 
3089
<td>jlong</td>
 
3090
</tr>
 
3091
 
 
3092
<tr>
 
3093
<td>unsigned long long<br>const unsigned long long &</td>
702
3094
<td>java.math.BigInteger</td>
703
3095
<td>jobject</td>
704
3096
</tr>
705
3097
 
706
3098
<tr>
707
 
<td>float</td>
 
3099
<td>float<br>const float &</td>
708
3100
<td>float</td>
709
3101
<td>jfloat</td>
710
3102
</tr>
711
3103
 
712
3104
<tr>
713
 
<td>double</td>
 
3105
<td>double<br> const double &</td>
714
3106
<td>double</td>
715
3107
<td>jdouble</td>
716
3108
</tr>
717
3109
 
718
3110
<tr>
719
 
<td>bool</td>
720
 
<td>boolean</td>
721
 
<td>jboolean</td>
722
 
</tr>
723
 
 
724
 
<tr>
725
 
<td>void</td>
726
 
<td>void</td>
727
 
<td>void</td>
 
3111
<td>char *<br>char []</td>
 
3112
<td>String</td>
 
3113
<td>jstring</td>
728
3114
</tr>
729
3115
 
730
3116
</table>
731
3117
<br>
732
 
Arrays are implemented using the same mappings, for example a c array, char[SIZE], is mapped to a Java array, byte[SIZE].
733
 
<br><br>
734
 
When SWIG is being used without shadow classes, longs are used for all pointers. All complex types (C/C++ structs and classes) are accessible using a Java long which holds a pointer to the underlying C/C++ object. Arrays of complex types are mapped as arrays of pointers to the type, that is a Java long[].
735
 
<br><br>
736
 
The output is different when SWIG is being used to generate shadow classes. Primitive types and pointers to these types remain the same; so a Java long is used for pointers to primitive types. However, for complex types, the shadow classes use a Java class which wraps the struct/class instead of a Java long. This applies to both argument parameters and return types that are complex types or pointers to complex types. Arrays of complex types turn into arrays of Java classes rather than arrays of longs.
737
 
<br><br>
738
 
For example, given the following C++ function call:
739
 
<blockquote> <pre>
740
 
void AClass::func(int a, int* b, SomeClass c, SomeClass* d, SomeClass& e, SomeClass f[10]);
741
 
</blockquote> </pre>
742
 
The non shadow access from Java is shown below, where the first parameter, ptr, is a long containing the pointer to an object of type AClass:
743
 
<blockquote> <pre>
744
 
public final static native void AClass_func(long ptr, int a, long b, long c, long d, long e, long[] f);
745
 
</blockquote> </pre>
746
 
The Java shadow class, AClass, will contain the following function:
747
 
<blockquote> <pre>
748
 
public void func(int a, long b, SomeClass c, SomeClass d, SomeClass e, SomeClass f[]) {...}
749
 
</blockquote> </pre>
750
 
<p>
751
 
 
752
 
The mappings for C int and C long are appropriate for 32 bit applications which
753
 
are used in the current 32 bit JVMs. There is no perfect mapping between Java and C as Java doesn't support all the unsigned C data types. However, the mappings allow the full range of C values from Java. 
754
 
<p>
755
 
For future 64 bit JVMs you may 
756
 
have to change the C long, but probably not C int mappings. Mappings will be system dependent, for example long will need remapping on Unix LP64 systems (long, pointer 64 bits, int 32 bits), but not on 
757
 
Microsoft 64 bit Windows which will be using a P64 IL32 (pointer 64 bits and int, long 32 bits) model. This may be automated in a future version of SWIG. Note that the Java write once run anywhere philosophy holds true for all pure Java code when moving to a 64 bit JVM. Unfortunately it won't of course hold true for JNI code.
758
 
 
759
 
 
760
 
<a name="n122"></a><h3> What is a typemap?</h3>
761
 
A typemap is mechanism by which SWIG's processing of a particular C datatype can be overridden.   A simple typemap might look like this :<p>
762
 
<p>
763
 
<blockquote><pre>
764
 
%module example
 
3118
Note that SWIG wraps the C <tt>char</tt> type as a character. Pointers and arrays of this type are wrapped as strings. 
 
3119
The <tt>signed char</tt> type can be used if you want to treat <tt>char</tt> as a signed number rather than a character.
 
3120
Also note that all const references to primitive types are treated as if they are passed by value.
 
3121
<p>
 
3122
 
 
3123
Given the following C function:
 
3124
<blockquote> <pre>
 
3125
void func(unsigned short a, char *b, const long &c, unsigned long long d);
 
3126
</blockquote> </pre>
 
3127
The module class method would be:
 
3128
<blockquote> <pre>
 
3129
public static void func(int a, String b, int c, java.math.BigInteger d) {...}
 
3130
</blockquote> </pre>
 
3131
The intermediary JNI class would use the same types:
 
3132
<blockquote> <pre>
 
3133
public final static native void func(int jarg1, String jarg2, int jarg3, java.math.BigInteger jarg4);
 
3134
</blockquote> </pre>
 
3135
and the JNI function would look like this:
 
3136
<blockquote> <pre>
 
3137
JNIEXPORT void JNICALL Java_exampleJNI_func(JNIEnv *jenv, jclass jcls, jint jarg1, jstring jarg2, jint jarg3, jobject jarg4) {...}
 
3138
</blockquote> </pre>
 
3139
<p>
 
3140
 
 
3141
The mappings for C <tt>int</tt> and C <tt>long</tt> are appropriate for 32 bit applications which are used in the 32 bit JVMs. 
 
3142
There is no perfect mapping between Java and C as Java doesn't support all the unsigned C data types. 
 
3143
However, the mappings allow the full range of values for each C type from Java. 
 
3144
<p>
 
3145
 
 
3146
<a name="jvm64"></a>
 
3147
<a name="n57"></a><H3>17.8.2 Sixty four bit JVMs</H3>
 
3148
 
 
3149
 
 
3150
If you are using a 64 bit JVM you may have to override the C long, but probably not C int default mappings. 
 
3151
Mappings will be system dependent, for example long will need remapping on Unix LP64 systems (long, pointer 64 bits, int 32 bits), but not on 
 
3152
Microsoft 64 bit Windows which will be using a P64 IL32 (pointer 64 bits and int, long 32 bits) model. 
 
3153
This may be automated in a future version of SWIG. 
 
3154
Note that the Java write once run anywhere philosophy holds true for all pure Java code when moving to a 64 bit JVM. 
 
3155
Unfortunately it won't of course hold true for JNI code.
 
3156
 
 
3157
 
 
3158
<a name="what_is_typemap"></a>
 
3159
<a name="n58"></a><H3>17.8.3 What is a typemap?</H3>
 
3160
 
 
3161
 
 
3162
A typemap is nothing more than a code generation rule that is attached to 
 
3163
a specific C datatype.   For example, to convert integers from Java to C,
 
3164
you might define a typemap like this:
 
3165
 
 
3166
<p>
 
3167
<blockquote><pre>%module example
765
3168
 
766
3169
%typemap(in) int {
767
3170
  $1 = $input;
768
3171
  printf("Received an integer : %d\n",  $1);
769
3172
}
770
 
 
771
 
extern int fact(int n);
 
3173
extern int fact(int nonnegative);
772
3174
</pre></blockquote>
773
 
<p>
774
 
Typemaps require a method name, datatype, and conversion code.  The "in" method in this example refers to an input argument of a function. The datatype `int' tells SWIG that we are remapping integers.  The supplied code is used to convert from a <tt>jint</tt> to the corresponding C datatype, <tt>int</tt>.  Within the supporting C code, the variable <tt>$input</tt> contains the Java data (the JNI jint in this case) and <tt>$1</tt> contains the destination of a conversion.  <p>
775
 
<p>
 
3175
 
 
3176
<p>
 
3177
Typemaps are always associated with some specific aspect of code generation.
 
3178
In this case, the "in" method refers to the conversion of input arguments
 
3179
to C/C++.  The datatype <tt>int</tt> is the datatype to which the typemap
 
3180
will be applied.  The supplied C code is used to convert values.  In this
 
3181
code a number of special variables prefaced by a <tt>$</tt> are used.  The
 
3182
<tt>$1</tt> variable is a placeholder for a local variable of type <tt>int</tt>.
 
3183
The <tt>$input</tt> variable contains the Java data, the JNI <tt>jint</tt> in this case.
 
3184
 
 
3185
<p>
 
3186
 
776
3187
When this example is compiled into a Java module, it can be used as follows:<p>
777
3188
<p>
778
3189
<blockquote><pre>
784
3195
720
785
3196
</pre></blockquote>
786
3197
 
787
 
<p>
788
 
A full discussion of typemaps can be found in the <a href="Typemaps.html">SWIG users reference section on typemaps</a>.  We will primarily be concerned with Java typemaps here.<p>
789
 
<a name="n123"></a><h3> Java typemaps</h3>
790
 
The typemaps available to the Java module include the common typemaps listed in the main typemaps section as well as the following Java specific typemaps:
 
3198
In this example, the typemap is applied to all occurrences of the <tt>int</tt> datatype.
 
3199
You can refine this by supplying an optional parameter name.  For example:
 
3200
 
 
3201
<blockquote><pre>
 
3202
%module example
 
3203
 
 
3204
%typemap(in) int nonnegative {
 
3205
  $1 = $input;
 
3206
  printf("Received an integer : %d\n",  $1);
 
3207
}
 
3208
 
 
3209
extern int fact(int nonnegative);
 
3210
</pre></blockquote>
 
3211
 
 
3212
In this case, the typemap code is only attached to arguments that exactly match <tt>int nonnegative</tt>.
 
3213
 
 
3214
<p>
 
3215
The application of a typemap to specific datatypes and argument names involves
 
3216
more than simple text-matching--typemaps are fully integrated into the
 
3217
SWIG C++ type-system.   When you define a typemap for <tt>int</tt>, that typemap
 
3218
applies to <tt>int</tt> and qualified variations such as <tt>const int</tt>.  In addition,
 
3219
the typemap system follows <tt>typedef</tt> declarations.  For example:
 
3220
 
 
3221
<blockquote>
 
3222
<pre>
 
3223
%typemap(in) int nonnegative {
 
3224
  $1 = $input;
 
3225
  printf("Received an integer : %d\n",  $1);
 
3226
}
 
3227
typedef int Integer;
 
3228
extern int fact(Integer nonnegative);    // Above typemap is applied
 
3229
</pre>
 
3230
</blockquote>
 
3231
 
 
3232
However, the matching of <tt>typedef</tt> only occurs in one direction.  If you
 
3233
defined a typemap for <tt>Integer</tt>, it is not applied to arguments of
 
3234
type <tt>int</tt>.
 
3235
 
 
3236
<p>
 
3237
Typemaps can also be defined for groups of consecutive arguments.  For example:
 
3238
 
 
3239
<blockquote>
 
3240
<pre>
 
3241
%typemap(in) (char *str, int len) {
 
3242
...
 
3243
};
 
3244
 
 
3245
int count(char c, char *str, int len);
 
3246
</pre>
 
3247
</blockquote>
 
3248
 
 
3249
When a multi-argument typemap is defined, the arguments are always handled as a single
 
3250
Java parameter.  This allows the function to be used like this (notice how the length
 
3251
parameter is omitted):
 
3252
 
 
3253
<blockquote>
 
3254
<pre>
 
3255
int c = example.count('e',"Hello World");
 
3256
</pre>
 
3257
</blockquote>
 
3258
 
 
3259
<a name="typemaps_c_to_java_types"></a>
 
3260
<a name="n59"></a><H3>17.8.4 Typemaps for mapping C/C++ types to Java types</H3>
 
3261
 
 
3262
 
 
3263
The typemaps available to the Java module include the common typemaps listed in the main typemaps section. 
 
3264
There are a number of additional typemaps which are necessary for using SWIG with Java.
 
3265
The most important of these implement the mapping of C/C++ types to Java types:
791
3266
 
792
3267
<br>&nbsp;
793
3268
<table BORDER>
798
3273
</tr>
799
3274
 
800
3275
<tr>
801
 
<td>typemap(jni)</td>
802
 
<td>JNI types. These provide the default mapping of types from C to JNI.</td>
803
 
</tr>
804
 
 
805
 
<tr>
806
 
<td>typemap(jtype)</td>
807
 
<td>Java types. These provide the default mapping of types from C to Java when used in the Java module class.</td>
808
 
</tr>
809
 
 
810
 
<tr>
811
 
<td>typemap(jstype)</td>
812
 
<td>Java shadow class types. These provide the default mapping of types from C to Java when used in Java shadow classes.</td>
813
 
</tr>
 
3276
<td>jni</td>
 
3277
<td>JNI C types. These provide the default mapping of types from C/C++ to JNI for use in the JNI (C/C++) code.</td>
 
3278
</tr>
 
3279
 
 
3280
<tr>
 
3281
<td>jtype</td>
 
3282
<td>Java intermediary types. These provide the default mapping of types from C/C++ to Java for use in the native functions in the intermediary JNI class. The type must be the equivalent Java type for the JNI C type specified in the "jni" typemap.</td>
 
3283
</tr>
 
3284
 
 
3285
<tr>
 
3286
<td>jstype</td>
 
3287
<td>Java types. These provide the default mapping of types from C/C++ to Java for use in the Java module class, proxy classes and type wrapper classes.</td>
 
3288
</tr>
 
3289
 
 
3290
<tr>
 
3291
<td>javain</td>
 
3292
<td>Conversion from jstype to jtype. 
 
3293
    These are Java code typemaps which transform the type used in the Java module class, proxy classes and type wrapper classes (as specified in the "jstype" typemap)
 
3294
    to the type used in the Java intermediary JNI class (as specified in the "jtype" typemap).
 
3295
    In other words the typemap provides the conversion to the native method call parameter types.</td>
 
3296
</tr>
 
3297
 
 
3298
<tr>
 
3299
<td>javaout</td>
 
3300
<td>Conversion from jtype to jstype.
 
3301
    These are Java code typemaps which transform the type used in the Java intermediary JNI class (as specified in the "jtype" typemap) to 
 
3302
    the Java type used in the Java module class, proxy classes and type wrapper classes (as specified in the "jstype" typemap).
 
3303
    In other words the typemap provides the conversion from the native method call return type. </td>
 
3304
</tr>
 
3305
 
 
3306
<tr>
 
3307
<td>javadirectorin</td>
 
3308
<td>Conversion from jtype to jstype for director methods.
 
3309
    These are Java code typemaps which transform the type used in the Java intermediary JNI class (as specified in the "jtype" typemap) to 
 
3310
    the Java type used in the Java module class, proxy classes and type wrapper classes (as specified in the "jstype" typemap).
 
3311
    This typemap provides the conversion for the parameters in the director methods when calling up from C++ to Java.
 
3312
    See <a href="#java_directors_typemaps">Director typemaps</a>.  </td>
 
3313
</tr>
 
3314
 
 
3315
<tr>
 
3316
<td>javadirectorout</td>
 
3317
<td>Conversion from jstype to jtype for director methods.
 
3318
    These are Java code typemaps which transform the type used in the Java module class, proxy classes and type wrapper classes (as specified in the "jstype" typemap)
 
3319
    to the type used in the Java intermediary JNI class (as specified in the "jtype" typemap).
 
3320
    This typemap provides the conversion for the return type in the director methods when returning from the C++ to Java upcall.
 
3321
    See <a href="#java_directors_typemaps">Director typemaps</a>.  </td>
 
3322
</tr>
 
3323
 
 
3324
<tr>
 
3325
<td>directorin</td>
 
3326
<td>Conversion from C++ type to jni type for director methods.
 
3327
  These are C++ typemaps which converts the parameters used in the C++ director method to the appropriate JNI intermediary type.
 
3328
  The conversion is done in JNI code prior to calling the Java function from the JNI code.
 
3329
  See <a href="#java_directors_typemaps">Director typemaps</a>. </td>
 
3330
</tr>
 
3331
 
814
3332
</table>
815
3333
 
816
 
<p>The default code generated by SWIG for the Java module comes from the typemaps in the java.swg library file. There are other typemaps in the Java library which could be used. These are listed below:
 
3334
<p>
 
3335
If you are writing your own typemaps to handle a particular type, you will normally have to write a collection of them. 
 
3336
The default typemaps are in <tt>java.swg</tt> and so might be a good place for finding typemaps to base any new ones on.</li>
 
3337
 
 
3338
<p>
 
3339
The "jni", "jtype" and "jstype" typemaps are usually defined together to handle the Java to C/C++ type mapping.
 
3340
An "in" typemap should be accompanied by a "javain" typemap and likewise an "out" typemap by a "javaout" typemap.
 
3341
If an "in" typemap is written, a "freearg" and "argout" typemap may also need to be written
 
3342
as some types have a default "freearg" and/or "argout" typemap which may need overriding. 
 
3343
The "freearg" typemap sometimes releases memory allocated by the "in" typemap. 
 
3344
The "argout" typemap sometimes sets values in function parameters which are passed by reference in Java. 
 
3345
 
 
3346
<p>The default code generated by SWIG for the Java module comes from the typemaps in the <tt>java.swg</tt> library file which implements the 
 
3347
<a href="#default_primitive_type_mappings">Default primitive type mappings</a>
 
3348
covered earlier.
 
3349
There are other type mapping typemaps in the Java library. 
 
3350
These are listed below:
817
3351
<br>&nbsp;
818
3352
<table BORDER>
819
3353
<tr VALIGN=TOP>
825
3359
<td><b>Function</b></td>
826
3360
</tr>
827
3361
 
828
 
<tr VALIGN=TOP>
829
 
<td>char *</td>
830
 
<td>BYTE</td>
831
 
<td>various.i</td>
832
 
<td>input
833
 
<br>output</td>
834
 
<td>byte[]</td>
835
 
 
836
 
<td VALIGN=TOP>Java byte array is converted to char array which
837
 
is released afterwards</td>
838
 
</tr>
839
 
 
840
 
<tr>
841
 
<td>char **</td>
842
 
<td>STRING_IN</td>
843
 
<td>various.i</td>
844
 
<td>input</td>
845
 
<td>String[]</td>
846
 
<td>\0 terminated array of \0 terminated strings
847
 
<br>the array is malloc-ed and released afterwards</td>
848
 
</tr>
849
 
 
850
 
<tr>
851
 
<td></td>
852
 
<td>STRING_OUT</td>
853
 
<td>various.i</td>
854
 
<td>output</td>
855
 
<td>String[]</td>
856
 
<td>&amp;char*
857
 
<br>the argument is the address of an '\0' terminated string</td>
858
 
</tr>
859
 
 
860
 
<tr>
861
 
<td></td>
862
 
<td>STRING_RET</td>
863
 
<td>various.i</td>
864
 
<td>return</td>
865
 
<td>String[]</td>
866
 
<td>\0 terminated array of \0 terminated strings
867
 
<br>the array is not free-ed.</td>
868
 
</tr>
869
 
 
870
 
<tr>
871
 
<td>primitive type pointers</td>
 
3362
<tr>
 
3363
<td>primitive pointers and references</td>
872
3364
<td>INPUT</td>
873
3365
<td>typemaps.i</td>
874
3366
<td>input</td>
875
3367
<td>Java basic types</td>
876
 
<td>Allows values to be used for c functions taking pointers for data input.
 
3368
<td>Allows values to be used for C functions taking pointers for data input.
877
3369
 
878
3370
<tr>
879
 
<td>primitive type pointers</td>
 
3371
<td>primitive pointers and references</td>
880
3372
<td>OUTPUT</td>
881
3373
<td>typemaps.i</td>
882
3374
<td>output</td>
883
3375
<td>Java basic type arrays</td>
884
 
<td>Allows values held within an array to be used for c functions taking pointers for data output.
 
3376
<td>Allows values held within an array to be used for C functions taking pointers for data output.
885
3377
 
886
3378
<tr>
887
 
<td>primitive type pointers</td>
 
3379
<td>primitive pointers and references</td>
888
3380
<td>INOUT</td>
889
3381
<td>typemaps.i</td>
890
3382
<td>input<br>output</td>
891
3383
<td>Java basic type arrays</td>
892
 
<td>Allows values held within an array to be used for c functions taking pointers for data input and output.
 
3384
<td>Allows values held within an array to be used for C functions taking pointers for data input and output.
893
3385
 
894
3386
<tr>
895
3387
<td>string <br>wstring</td>
896
3388
<td>[unnamed]</td>
897
 
<td>stl_string.i</td>
898
 
<td>input<br> ouput</td>
 
3389
<td>std_string.i</td>
 
3390
<td>input<br> output</td>
899
3391
<td>String</td>
900
 
<td>Use for STL std::string mapping to Java String.</td>
901
 
</tr>
 
3392
<td>Use for std::string mapping to Java String.</td>
 
3393
</tr>
 
3394
 
 
3395
<tr>
 
3396
<td>arrays of primitive types</td>
 
3397
<td>[unnamed]</td>
 
3398
<td>arrays_java.i</td>
 
3399
<td>input<br> output</td>
 
3400
<td>arrays of primitive Java types</td>
 
3401
<td>Use for mapping C arrays to Java arrays.</td>
 
3402
</tr>
 
3403
 
 
3404
<tr>
 
3405
<td>arrays of classes/structs/unions</td>
 
3406
<td>JAVA_ARRAYSOFCLASSES macro</td>
 
3407
<td>arrays_java.i</td>
 
3408
<td>input<br> output</td>
 
3409
<td>arrays of proxy classes</td>
 
3410
<td>Use for mapping C arrays to Java arrays.</td>
 
3411
</tr>
 
3412
 
 
3413
<tr>
 
3414
<td>arrays of enums</td>
 
3415
<td>ARRAYSOFENUMS</td>
 
3416
<td>arrays_java.i</td>
 
3417
<td>input<br> output</td>
 
3418
<td>int[]</td>
 
3419
<td>Use for mapping C arrays to Java arrays.</td>
 
3420
</tr>
 
3421
 
 
3422
<tr VALIGN=TOP>
 
3423
<td>char *</td>
 
3424
<td>BYTE</td>
 
3425
<td>various.i</td>
 
3426
<td>input</td>
 
3427
<td>byte[]</td>
 
3428
 
 
3429
<td VALIGN=TOP>Java byte array is converted to char array</td>
 
3430
</tr>
 
3431
 
 
3432
<tr>
 
3433
<td>char **</td>
 
3434
<td>STRING_ARRAY</td>
 
3435
<td>various.i</td>
 
3436
<td>input<br> output</td>
 
3437
<td>String[]</td>
 
3438
<td>Use for mapping NULL terminated arrays of C strings to Java String arrays</td>
 
3439
</tr>
 
3440
 
902
3441
</table>
903
3442
 
904
 
<p>
905
 
If a %typemap(in) is written, a %typemap(freearg) and %typemap(argout) may also need to be written. This is because some types have a default 'freearg' and/or 'argout' typemap which may need overriding. The 'freearg' typemap sometimes releases memory allocated by the 'in' typemap. The 'argout' typemap sometimes sets values in function parameters which are passed by reference in Java.</li>
906
 
 
907
 
<a name="n124"></a><h3> Typemap variables</h3>
 
3443
<a name="special_variables"></a>
 
3444
<a name="n60"></a><H3>17.8.5 Java special variables</H3>
 
3445
 
 
3446
 
908
3447
The standard SWIG special variables are available for use within typemaps as described in the <a href=Typemaps.html>Typemaps documentation</a>, for example <tt>$1</tt>, <tt>$input</tt>,<tt>$result</tt> etc.
909
3448
 
910
3449
<p>
911
3450
The Java module uses a few additional special variables:
912
3451
<p>
 
3452
 
913
3453
<b><tt>$javaclassname</tt></b><br>
914
 
Only in jstype typemaps. $javaclassname is similar to $1_basetype, except when applied to unions/structs/classes. Here the type name is used if it has been wrapped by SWIG otherwise a Java long is used. Used primarily to get the Java classname of a wrapped union/struct/class. For example, $javaclassname is replaced by 'Foo' when the type is 'struct Foo'.<p>
 
3454
<tt>$javaclassname</tt> is similar to <tt>$1_type</tt>. It expands to the class name for use in Java. 
 
3455
When wrapping a union, struct or class, it expands to the Java proxy class name.
 
3456
Otherwise it expands to the type wrapper class name.
 
3457
For example, <tt>$javaclassname</tt> is replaced by <tt>Foo</tt> when the wrapping a <tt>struct Foo</tt> or <tt>struct Foo *</tt> and 
 
3458
<tt>SWIGTYPE_p_unsigned_short</tt> is used for <tt>unsigned short *</tt>.
 
3459
<p>
915
3460
 
916
3461
<b><tt>$null </tt></b><br>
917
3462
Used in input typemaps to return early from JNI functions that have either void or a non-void return type. Example:
928
3473
If the typemap gets put into a function with void as return, $null will expand to nothing:
929
3474
 
930
3475
<blockquote><pre>
931
 
void jni_fn(...) {
 
3476
JNIEXPORT void JNICALL Java_jnifn(...) {
932
3477
    if (error) {
933
3478
      SWIG_exception(SWIG_IndexError, "Array element error");
934
3479
      return ;
940
3485
otherwise $null expands to NULL 
941
3486
 
942
3487
<blockquote><pre>
943
 
jobject jni_fn(...) {
 
3488
JNIEXPORT jobject JNICALL Java_jnifn(...) {
944
3489
    if (error) {
945
3490
      SWIG_exception(SWIG_IndexError, "Array element error");
946
3491
      return NULL;
949
3494
}
950
3495
</pre></blockquote>
951
3496
 
952
 
 
953
 
<a name="n126"></a><h3> Typemaps for C and C++</h3>
954
 
JNI calls must be written differently depending on whether the code is being compiled as C or C++. For example C compilation requires syntax like
 
3497
<b><tt>$javainput, $jnicall and $owner</tt></b><br>
 
3498
The $javainput special variable is used in "javain" typemaps and $jnicall and $owner are used in "javaout" typemaps.
 
3499
$jnicall is analogous to $action in %exception. It is replaced by the call to the native method in the intermediary JNI class.
 
3500
$owner is replaced by either <tt>true</tt> if %newobject has been used, otherwise <tt>false</tt>.
 
3501
$javainput is analogous to the $input special variable. It is replaced by the parameter name.
 
3502
<p>
 
3503
 
 
3504
Here is an example:
 
3505
 
 
3506
<blockquote><pre>
 
3507
%typemap(javain) Class "Class.getCPtr($javainput)"
 
3508
%typemap(javain) unsigned short "$javainput"
 
3509
%typemap(javaout) Class * {
 
3510
    return new Class($jnicall, $owner);
 
3511
  }
 
3512
 
 
3513
%inline %{
 
3514
    class Class {...};
 
3515
    Class * bar(Class cls, unsigned short ush) { return new Class(); };
 
3516
%}
 
3517
</pre></blockquote>
 
3518
 
 
3519
The generated proxy code is then:
 
3520
 
 
3521
<blockquote><pre>
 
3522
public static Class bar(Class cls, int ush) {
 
3523
  return new Class(exampleJNI.bar(Class.getCPtr(cls), ush), false);
 
3524
}
 
3525
</pre></blockquote>
 
3526
 
 
3527
Here $javainput has been replaced by <tt>cls</tt> and <tt>ush</tt>. $jnicall has been replaced by 
 
3528
the native method call, <tt>exampleJNI.bar(...)</tt> and $owner has been replaced by <tt>false</tt>.
 
3529
If %newobject is used by adding the following at the beginning of our example:
 
3530
 
 
3531
<blockquote><pre>
 
3532
%newobject bar(Class cls, unsigned short ush);
 
3533
</pre></blockquote>
 
3534
 
 
3535
The generated code constructs the return type using <tt>true</tt> indicating the proxy class <tt>Class</tt> is responsible for destroying the C++ memory allocated for it in <tt>bar</tt>:
 
3536
 
 
3537
<blockquote><pre>
 
3538
public static Class bar(Class cls, int ush) {
 
3539
  return new Class(exampleJNI.bar(Class.getCPtr(cls), ush), true);
 
3540
}
 
3541
</pre></blockquote>
 
3542
 
 
3543
<b><tt>$jniinput, $javacall and $packagepath</tt></b><br>
 
3544
These special variables used in the directors typemaps. See <a href="#java_directors_typemaps">Director specific typemaps</a> for details.
 
3545
 
 
3546
<a name="typemaps_for_c_and_c++"></a>
 
3547
<a name="n61"></a><H3>17.8.6 Typemaps for both C and C++ compilation</H3>
 
3548
 
 
3549
 
 
3550
JNI calls must be written differently depending on whether the code is being compiled as C or C++. 
 
3551
For example C compilation requires the pointer to a function pointer struct member syntax like
 
3552
 
955
3553
<blockquote><pre>
956
3554
const jclass clazz = (*jenv)->FindClass(jenv, "java/lang/String");
957
3555
</pre></blockquote>
958
 
whereas C++ code compilation of the same function call has to be written like this
 
3556
 
 
3557
whereas C++ code compilation of the same function call is a member function call using a class pointer like
 
3558
 
959
3559
<blockquote><pre>
960
3560
const jclass clazz = jenv->FindClass("java/lang/String");
961
3561
</pre></blockquote>
962
 
To enable typemaps to be compiled as either C or C++ use the JCALLx macros defined in Lib/java/javahead.swg where x is the number of arguments in the C++ version of the JNI call. The above JNI call would be written in a typemap like this
 
3562
 
 
3563
To enable typemaps to be used for either C or C++ compilation, a set of JCALLx macros have been defined in Lib/java/javahead.swg, 
 
3564
where x is the number of arguments in the C++ version of the JNI call. 
 
3565
The above JNI calls would be written in a typemap like this
 
3566
 
963
3567
<blockquote><pre>
964
3568
const jclass clazz = JCALL1(FindClass, jenv, "java/lang/String");
965
3569
</pre></blockquote>
966
 
<p>
967
 
 
968
 
<a name="n125"></a><h3> Name based type conversion</h3>
969
 
Typemaps are based both on the datatype and an optional name attached to a datatype.   For example :<p>
970
 
<p>
971
 
<blockquote><pre>%module foo
972
 
 
973
 
// This typemap will be applied to all char ** function arguments
974
 
%typemap(in) char ** { ... }
975
 
 
976
 
// This typemap is applied only to char ** arguments named `argv'
977
 
%typemap(in) char **argv { ... }
978
 
 
979
 
</pre></blockquote>
980
 
In this example, two typemaps are applied to the <tt>char **</tt> datatype.  However, the second typemap will only be applied to arguments named `<tt>argv</tt>'.  A named typemap will always override an unnamed typemap.<p>
981
 
<p>
982
 
Due to the name-based nature of typemaps, it is important to note that typemaps are independent of typedef declarations.  For example :<p>
983
 
<p>
984
 
<blockquote><pre>%typemap(in) double {
985
 
        ... get a double ...
986
 
}
987
 
void foo(double);            // Uses the above typemap
988
 
typedef double Real;
989
 
void bar(Real);              // Does not use the above typemap (double != Real)
990
 
 
991
 
</pre></blockquote>
992
 
To get around this problem, the <tt>%apply</tt> directive can be used as follows :<p>
993
 
<blockquote><pre>
994
 
%typemap(in) double {
995
 
        ... get a double ...
996
 
}
997
 
void foo(double);
998
 
 
999
 
typedef double Real;         // Uses typemap
1000
 
%apply double { Real };      // Applies all "double" typemaps to Real.
1001
 
void bar(Real);              // Now uses the same typemap.
1002
 
</pre></blockquote>
1003
 
 
1004
 
<a name="n126"></a><h3> Converting Java String arrays to char ** </h3>
1005
 
A common problem in many C programs is the processing of command line arguments, which are usually passed in an array of NULL terminated strings.   The following SWIG interface file allows a Java String array to be used as a <tt>char **</tt> object.<p>
 
3570
 
 
3571
Note that the SWIG preprocessor expands these into the appropriate C or C++ JNI calling convention. 
 
3572
The C calling convention is emitted by default and the C++ calling convention is emitted when using the -c++ SWIG commandline option. 
 
3573
If you do not intend your code to be targeting both C and C++ then your typemaps can use the appropriate JNI calling convention and need not use the JCALLx macros.
 
3574
<p>
 
3575
 
 
3576
 
 
3577
<a name="java_code_typemaps"></a>
 
3578
<a name="n62"></a><H3>17.8.7 Java code typemaps</H3>
 
3579
 
 
3580
 
 
3581
Most of SWIG's typemaps are used for the generation of C/C++ code. 
 
3582
The typemaps in this section are used solely for the generation of Java code. 
 
3583
Elements of proxy classes and type wrapper classes come from the following typemaps (the defaults).
 
3584
 
 
3585
<p>
 
3586
 
 
3587
<tt>%typemap(javabase)</tt>
 
3588
<blockquote>
 
3589
base (extends) for Java class: empty default
 
3590
</blockquote>
 
3591
 
 
3592
<tt>%typemap(javaclassmodifiers)</tt>
 
3593
<blockquote>
 
3594
class modifiers for the Java class: default is "public"
 
3595
</blockquote>
 
3596
 
 
3597
<tt>%typemap(javacode)</tt>
 
3598
<blockquote>
 
3599
Java code is copied verbatim to the Java class: empty default
 
3600
</blockquote>
 
3601
 
 
3602
<tt>%typemap(javadestruct, methodname="delete")</tt> <br>
 
3603
<blockquote>
 
3604
destructor wrapper - the <tt>delete()</tt> method (proxy classes only),
 
3605
used for all classes except those which have a base class
 
3606
: default calls C++ destructor (or frees C memory) and resets <tt>swigCPtr</tt> and <tt>swigCMemOwn</tt> flags
 
3607
<br>
 
3608
<br>
 
3609
Note that the <tt>delete()</tt> method name is configurable and is specified by the <tt>methodname</tt> attribute.
 
3610
</blockquote>
 
3611
 
 
3612
<tt>%typemap(javadestruct_derived, methodname="delete")</tt>
 
3613
<blockquote>
 
3614
destructor wrapper - the <tt>delete()</tt> method (proxy classes only),
 
3615
same as "javadestruct" but only used for derived classes
 
3616
: default calls C++ destructor (or frees C memory) and resets <tt>swigCPtr</tt> and <tt>swigCMemOwn</tt> flags
 
3617
<br>
 
3618
<br>
 
3619
Note that the <tt>delete()</tt> method name is configurable and is specified by the <tt>methodname</tt> attribute.
 
3620
</blockquote>
 
3621
 
 
3622
<tt>%typemap(javaimports)</tt>
 
3623
<blockquote>
 
3624
import statements for Java class: empty default
 
3625
</blockquote>
 
3626
 
 
3627
<tt>%typemap(javainterfaces)</tt>
 
3628
<blockquote>
 
3629
interfaces (extends) for Java class: empty default
 
3630
</blockquote>
 
3631
 
 
3632
<tt>%typemap(javafinalize)</tt>
 
3633
<blockquote>
 
3634
the <tt>finalize()</tt> method (proxy classes only): default calls the <tt>delete()</tt> method
 
3635
</blockquote>
 
3636
 
 
3637
<tt>%typemap(javagetcptr)</tt>
 
3638
<blockquote>
 
3639
the <tt>getCPtr()</tt> method: default returns the <tt>swigCPtr</tt> member variable
 
3640
</blockquote>
 
3641
 
 
3642
<tt>%typemap(javaptrconstructormodifiers)</tt>
 
3643
<blockquote>
 
3644
method modifier for the constructors taking a C pointer and the memory ownership flag: default is "protected"
 
3645
</blockquote>
 
3646
 
 
3647
In summary the contents of the typemaps make up a proxy class like this:
 
3648
 
 
3649
<blockquote>
 
3650
<pre>
 
3651
[ javaimports typemap ]
 
3652
[ javamodifiers typemap ] class proxyclassname extends [ javabase typemap ] implements [ javainterfaces typemap ] {
 
3653
[ javafinalize typemap ]
 
3654
[ javaptrconstructormodifiers typemap ] proxyclassname(long cPtr, boolean cMemoryOwn) {...}
 
3655
... Other SWIG generated constructors ...
 
3656
public void <i>delete</i>() [ javadestruct OR javadestruct_derived typemap ]
 
3657
[ javagetcptr typemap ]
 
3658
[ javacode typemap ]
 
3659
... proxy functions ...
 
3660
}
 
3661
</pre>
 
3662
</blockquote>
 
3663
 
 
3664
Note the <tt><i>delete</i>()</tt> methodname is configurable, see "javadestruct" and "javadestruct_derived" typemaps above.
 
3665
<p>
 
3666
 
 
3667
The type wrapper class is similar in construction:
 
3668
 
 
3669
<blockquote>
 
3670
<pre>
 
3671
[ javaimports typemap ]
 
3672
[ javamodifiers typemap ] class typewrappername extends [ javabase typemap ] implements [ javainterfaces typemap ] {
 
3673
[ javaptrconstructormodifiers typemap ] proxyclassname(long cPtr, boolean bFutureUse) {...}
 
3674
... Other SWIG generated constructors ...
 
3675
[ javagetcptr typemap ]
 
3676
[ javacode typemap ]
 
3677
}
 
3678
</pre>
 
3679
</blockquote>
 
3680
 
 
3681
The defaults can be overridden to tailor these classes and are often used to hide or expose the C/C++ pointer. Here is an example which will change the <tt>getCPtr()</tt> method from the default protected access to public access. 
 
3682
 
 
3683
<blockquote>
 
3684
<pre>
 
3685
%typemap(javagetcptr) SWIGTYPE %{
 
3686
  public static long getCPtr($javaclassname obj) {
 
3687
    return (obj == null) ? 0 : obj.swigCPtr;
 
3688
  }
 
3689
%}
 
3690
</pre>
 
3691
</blockquote>
 
3692
 
 
3693
Note that <tt>SWIGTYPE</tt> will target all proxy classes, but not all type wrapper classes. 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:
 
3694
 
 
3695
<blockquote>
 
3696
<pre>
 
3697
%typemap(javagetcptr) SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE [], SWIGTYPE (CLASS::*) %{
 
3698
  public static long getCPtr($javaclassname obj) {
 
3699
    return obj.swigCPtr;
 
3700
  }
 
3701
%}
 
3702
</pre>
 
3703
</blockquote>
 
3704
 
 
3705
<p>
 
3706
 
 
3707
<a name="java_directors_typemaps"></a>
 
3708
<a name="n63"></a><H3>17.8.8 Director specific typemaps</H3>
 
3709
 
 
3710
 
 
3711
The Java directors feature requires the "javadirectorin", "javadirectorout" and the "directorin" typemaps in order to work properly.
 
3712
The "javapackage" typemap is an optional typemap used to identify the Java package path for individual SWIG generated proxy classes.
 
3713
<p>
 
3714
 
 
3715
<tt>%typemap(directorin)</tt>
 
3716
<blockquote>
 
3717
 
 
3718
 
 
3719
The "directorin" typemap is used for converting arguments in the C++ director class to the appropriate JNI type before the upcall to Java.
 
3720
This typemap also specifies the JNI field descriptor for the type in the "descriptor" attribute.
 
3721
For example, integers are converted as follows:
 
3722
 
 
3723
<blockquote>
 
3724
<pre>
 
3725
%typemap(directorin,descriptor="I") int "$input = (jint) $1;"
 
3726
</pre>
 
3727
</blockquote>
 
3728
 
 
3729
<code>$input</code> is the SWIG name of the JNI temporary variable passed to Java in the upcall.
 
3730
The <code>descriptor="I"</code> will put an <code>I</code> into the JNI field descriptor that identifies the Java method that will be called from C++.
 
3731
For more about JNI field descriptors and their importance, refer to the <a href="#java_typemaps">JNI documentation mentioned earlier</a>.
 
3732
A typemap for C character strings is:
 
3733
 
 
3734
<blockquote>
 
3735
<pre>
 
3736
%typemap(directorin,descriptor="Ljava/lang/String;") char *
 
3737
  %{ $input = jenv-&gt;NewStringUTF($1); %}
 
3738
</pre>
 
3739
</blockquote>
 
3740
 
 
3741
 
 
3742
User-defined types have the default "descriptor" attribute "<code>L$packagepath/$javaclassname;</code>" where <code>$packagepath</code> 
 
3743
is the package name passed from the SWIG command line and <code>$javaclassname</code> is the Java proxy class' name.
 
3744
If the <tt>-package</tt> commandline option is not used to specify the package, then '$packagepath/' will be removed from the resulting output JNI field descriptor.
 
3745
<b>Do not forget the terminating ';' for JNI field descriptors starting with 'L'.</b>
 
3746
If the ';' is left out, Java will generate a "method not found" runtime error.
 
3747
 
 
3748
</blockquote>
 
3749
 
 
3750
 
 
3751
<tt>%typemap(javadirectorin)</tt>
 
3752
<blockquote>
 
3753
 
 
3754
Conversion from jtype to jstype for director methods.
 
3755
These are Java code typemaps which transform the type used in the Java intermediary JNI class (as specified in the "jtype" typemap) to 
 
3756
the Java type used in the Java module class, proxy classes and type wrapper classes (as specified in the "jstype" typemap).
 
3757
This typemap provides the conversion for the parameters in the director methods when calling up from C++ to Java.
 
3758
 
 
3759
For primitive types, this typemap is usually specified as:
 
3760
<blockquote>
 
3761
<pre>
 
3762
%typemap(javadirectorin) int "$jniinput"
 
3763
</pre>
 
3764
</blockquote>
 
3765
 
 
3766
The <code>$jniinput</code> special variable is analogous to <code>$javainput</code> special variable.
 
3767
It is replaced by the input parameter name.
 
3768
 
 
3769
</blockquote>
 
3770
 
 
3771
 
 
3772
<tt>%typemap(javadirectorout)</tt>
 
3773
<blockquote>
 
3774
Conversion from jstype to jtype for director methods.
 
3775
These are Java code typemaps which transform the type used in the Java module class, proxy classes and type wrapper classes (as specified in the "jstype" typemap)
 
3776
to the type used in the Java intermediary JNI class (as specified in the "jtype" typemap).
 
3777
This typemap provides the conversion for the return type in the director methods when returning from the C++ to Java upcall.
 
3778
 
 
3779
For primitive types, this typemap is usually specified as:
 
3780
<blockquote>
 
3781
<pre>
 
3782
%typemap(javadirectorout) int "$javacall"
 
3783
</pre>
 
3784
</blockquote>
 
3785
 
 
3786
The <code>$javacall</code> special variable is analogous to the <code>$jnicall</code> special variable.
 
3787
It is replaced by the call to the target Java method.
 
3788
The target method is the method in the Java proxy class which overrides the virtual C++ method in the C++ base class.
 
3789
 
 
3790
</blockquote>
 
3791
 
 
3792
<tt>%typemap(javapackage)</tt>
 
3793
<blockquote>
 
3794
 
 
3795
 
 
3796
The "javapackage" typemap is optional; it serves to identify a class's Java package.
 
3797
This typemap should be used in conjunction with classes that are defined outside of the current SWIG interface file.
 
3798
For example:
 
3799
 
 
3800
<blockquote>
 
3801
<pre>
 
3802
// class Foo is handled in a different interface file:
 
3803
%import "Foo.i"
 
3804
 
 
3805
%feature("director") Example;
 
3806
 
 
3807
%inline {
 
3808
  class Bar { };
 
3809
 
 
3810
  class Example {
 
3811
  public:
 
3812
    virtual ~Example();
 
3813
    void     ping(Foo *arg1, Bar *arg2);
 
3814
  };
 
3815
}
 
3816
</pre>
 
3817
</blockquote>
 
3818
 
 
3819
Assume that the Foo class is part of the Java package <i>wombat.foo</i> but the above interface file is part of the Java package <i>wombat.example</i>.
 
3820
Without the "javapackage" typemap, SWIG will assume that the Foo class belongs to <i>wombat.example</i> class.
 
3821
The corrected interface file looks like:
 
3822
 
 
3823
<blockquote>
 
3824
<pre>
 
3825
// class Foo is handled in a different interface file:
 
3826
%import "Foo.i"
 
3827
%typemap("javapackage") Foo "wombat.foo";
 
3828
%feature("director") Example;
 
3829
 
 
3830
%inline {
 
3831
  class Bar { };
 
3832
 
 
3833
  class Example {
 
3834
  public:
 
3835
    virtual ~Example();
 
3836
    void     ping(Foo *arg1, Bar *arg2);
 
3837
  };
 
3838
}
 
3839
</pre>
 
3840
</blockquote>
 
3841
 
 
3842
<p>
 
3843
Practically speaking, you should create a separate SWIG interface file, which is %import-ed into each SWIG interface file, when you have multiple Java packages:
 
3844
 
 
3845
<blockquote>
 
3846
<pre>
 
3847
%typemap("javapackage") SWIGTYPE, SWIGTYPE *, SWIGTYPE &amp; "package.for.most.classes";
 
3848
 
 
3849
%typemap("javapackage") Package_2_class_one "package.for.other.classes";
 
3850
%typemap("javapackage") Package_3_class_two "package.for.another.set";
 
3851
/* etc */
 
3852
</pre>
 
3853
</blockquote>
 
3854
 
 
3855
The basic strategy here is to provide a default package typemap for the majority of the classes, only providing "javapackage" typemaps for the exceptions.
 
3856
</p>
 
3857
 
 
3858
</blockquote>
 
3859
 
 
3860
<a name="typemap_examples"></a>
 
3861
<a name="n64"></a><H2>17.9 Typemap Examples</H2>
 
3862
 
 
3863
 
 
3864
This section includes a few examples of typemaps.  For more examples, you
 
3865
might look at the files "<tt>java.swg</tt>" and "<tt>typemaps.i</tt>" in
 
3866
the SWIG library.
 
3867
 
 
3868
 
 
3869
<a name="converting_java_string_arrays"></a>
 
3870
<a name="n65"></a><H3>17.9.1 Converting Java String arrays to char ** </H3>
 
3871
 
 
3872
 
 
3873
A common problem in many C programs is the processing of command line arguments, which are usually passed in an array of NULL terminated strings.   
 
3874
The following SWIG interface file allows a Java String array to be used as a <tt>char **</tt> object.<p>
1006
3875
<p>
1007
3876
<blockquote><pre>
1008
3877
%module example
1009
3878
 
1010
3879
/* This tells SWIG to treat char ** as a special case when used as a parameter in a function call */
1011
 
%typemap(in) char** (jint size) {
 
3880
%typemap(in) char ** (jint size) {
1012
3881
    int i = 0;
1013
3882
    size = (*jenv)-&gt;GetArrayLength(jenv, $input);
1014
3883
    $1 = (char **) malloc((size+1)*sizeof(char *));
1015
3884
    /* make a copy of each string */
1016
3885
    for (i = 0; i&lt;size; i++) {
1017
3886
        jstring j_string = (jstring)(*jenv)-&gt;GetObjectArrayElement(jenv, $input, i);
1018
 
        const char* c_string = (*jenv)-&gt;GetStringUTFChars(jenv, j_string, 0);
1019
 
        $1[i] = malloc(strlen((c_string)+1)*sizeof(const char*));
 
3887
        const char * c_string = (*jenv)-&gt;GetStringUTFChars(jenv, j_string, 0);
 
3888
        $1[i] = malloc(strlen((c_string)+1)*sizeof(const char *));
1020
3889
        strcpy($1[i], c_string);
1021
3890
        (*jenv)-&gt;ReleaseStringUTFChars(jenv, j_string, c_string);
1022
3891
        (*jenv)-&gt;DeleteLocalRef(jenv, j_string);
1025
3894
}
1026
3895
 
1027
3896
/* This cleans up the memory we malloc'd before the function call */
1028
 
%typemap(freearg) char** {
 
3897
%typemap(freearg) char ** {
1029
3898
    int i;
1030
 
    for (i=0; i&lt;size-1; i++)
 
3899
    for (i=0; i&lt;size$argnum-1; i++)
1031
3900
      free($1[i]);
1032
3901
    free($1);
1033
3902
}
1034
3903
 
1035
3904
/* This allows a C function to return a char ** as a Java String array */
1036
 
%typemap(out) char** {
 
3905
%typemap(out) char ** {
1037
3906
    int i;
1038
3907
    int len=0;
1039
3908
    jstring temp_string;
1050
3919
    }
1051
3920
}
1052
3921
 
1053
 
/* This tells SWIG what the matching JNI type for the Java type is */
1054
 
%typemap(jni) char** "jobjectArray"
 
3922
/* These 3 typemaps tell SWIG what JNI and Java types to use */
 
3923
%typemap(jni) char ** "jobjectArray"
 
3924
%typemap(jtype) char ** "String[]"
 
3925
%typemap(jstype) char ** "String[]"
1055
3926
 
1056
 
/* This tells SWIG what Java type to use */
1057
 
%typemap(jtype) char** "String[]"
1058
 
%typemap(jstype) char** "String[]"
 
3927
/* These 2 typemaps handle the conversion of the jtype to jstype typemap type and visa versa */
 
3928
%typemap(javain) char ** "$javainput"
 
3929
%typemap(javaout) char ** {
 
3930
    return $jnicall;
 
3931
  }
1059
3932
 
1060
3933
/* Now a few test functions */
1061
3934
%inline %{
1077
3950
%}
1078
3951
</pre></blockquote>
1079
3952
 
1080
 
Note that the 'C' JNI calling convention is used. Checking for any thrown exceptions after JNI function calls has been omitted. When this module is compiled, our wrapped C functions can now be used by the following Java program:<p>
 
3953
Note that the 'C' JNI calling convention is used. 
 
3954
Checking for any thrown exceptions after JNI function calls has been omitted. 
 
3955
When this module is compiled, our wrapped C functions can be used by the following Java program:<p>
1081
3956
<p>
1082
3957
<blockquote><pre>
1083
3958
// File main.java
1084
 
import example;
1085
3959
 
1086
3960
public class main {
1087
3961
 
1117
3991
4:Michelle
1118
3992
</pre></blockquote>
1119
3993
 
1120
 
Our type-mapping makes the Java interface to these functions more natural and easy to use.     <p>
1121
 
 
1122
 
<a name="n127"></a><h3> Using typemaps to return arguments</h3>
1123
 
A common problem in some C programs is that values may be returned in arguments rather than in the return value of a function. The typemaps.i file defines INPUT, OUTPUT and INOUT typemaps which can be used to solve some instances of this problem. This library file uses an array as a means of moving data to and from Java when wrapping a c function that takes pointers as parameters. <p>
1124
 
 
1125
 
Now we are going to outline an alternative approach to using arrays for C pointers. The INOUT typemap uses a double[] array for receiving and returning the double* parameters. In this approach we are able to use a Java class myDouble instead of double[] arrays where the c pointer double* is required. 
 
3994
In the example, a few different typemaps are used.  The "in" typemap is
 
3995
used to receive an input argument and convert it to a C array.  Since dynamic
 
3996
memory allocation is used to allocate memory for the array, the
 
3997
"freearg" typemap is used to later release this memory after the execution of
 
3998
the C function. The "out" typemap is used for function return values.
 
3999
Lastly the "jni", "jtype" and "jstype" typemaps are also required to specify
 
4000
what Java types to use.
 
4001
 
 
4002
<a name="expanding_java_object"></a>
 
4003
<a name="n66"></a><H3>17.9.2 Expanding a Java object to multiple arguments</H3>
 
4004
 
 
4005
 
 
4006
Suppose that you had a collection of C functions with arguments
 
4007
such as the following:
 
4008
 
 
4009
<blockquote>
 
4010
<pre>
 
4011
int foo(int argc, char **argv);
 
4012
</pre>
 
4013
</blockquote>
 
4014
 
 
4015
In the previous example, a typemap was written to pass a Java String array as the <tt>char **argv</tt>.  This
 
4016
allows the function to be used from Java as follows:
 
4017
 
 
4018
<blockquote>
 
4019
<pre>
 
4020
example.foo(4, new String[]{"red", "green", "blue", "white"});
 
4021
</pre>
 
4022
</blockquote>
 
4023
 
 
4024
Although this works, it's a little awkward to specify the argument count.  To fix this, a multi-argument
 
4025
typemap can be defined.  This is not very difficult--you only have to make slight modifications to the
 
4026
previous example's typemaps:
 
4027
 
 
4028
<blockquote>
 
4029
<pre>
 
4030
%typemap(in) (int argc, char **argv) {
 
4031
    int i = 0;
 
4032
    $1 = (*jenv)->GetArrayLength(jenv, $input);
 
4033
    $2 = (char **) malloc(($1+1)*sizeof(char *));
 
4034
    /* make a copy of each string */
 
4035
    for (i = 0; i<$1; i++) {
 
4036
        jstring j_string = (jstring)(*jenv)->GetObjectArrayElement(jenv, $input, i);
 
4037
        const char * c_string = (*jenv)->GetStringUTFChars(jenv, j_string, 0);
 
4038
        $2[i] = malloc(strlen((c_string)+1)*sizeof(const char *));
 
4039
        strcpy($2[i], c_string);
 
4040
        (*jenv)->ReleaseStringUTFChars(jenv, j_string, c_string);
 
4041
        (*jenv)->DeleteLocalRef(jenv, j_string);
 
4042
    }
 
4043
    $2[i] = 0;
 
4044
}
 
4045
 
 
4046
%typemap(freearg) (int argc, char **argv) {
 
4047
    int i;
 
4048
    for (i=0; i<$1-1; i++)
 
4049
      free($2[i]);
 
4050
    free($2);
 
4051
}
 
4052
 
 
4053
%typemap(jni) (int argc, char **argv) "jobjectArray"
 
4054
%typemap(jtype) (int argc, char **argv) "String[]"
 
4055
%typemap(jstype) (int argc, char **argv) "String[]"
 
4056
 
 
4057
%typemap(javain) (int argc, char **argv) "$javainput"
 
4058
</pre>
 
4059
</blockquote>
 
4060
 
 
4061
When writing a multiple-argument typemap, each of the types is referenced by a variable such 
 
4062
as <tt>$1</tt> or <tt>$2</tt>.   The typemap code simply fills in the appropriate values from
 
4063
the supplied Java parameter.
 
4064
 
 
4065
<p>
 
4066
With the above typemap in place, you will find it no longer necessary
 
4067
to supply the argument count.  This is automatically set by the typemap code.  For example:
 
4068
 
 
4069
<blockquote>
 
4070
<pre>
 
4071
example.foo(new String[]{"red", "green", "blue", "white"});
 
4072
</pre>
 
4073
</blockquote>
 
4074
 
 
4075
 
 
4076
<a name="using_typemaps_return_arguments"></a>
 
4077
<a name="n67"></a><H3>17.9.3 Using typemaps to return arguments</H3>
 
4078
 
 
4079
 
 
4080
A common problem in some C programs is that values may be returned in function parameters rather than in the return value of a function. 
 
4081
The <tt>typemaps.i</tt> file defines INPUT, OUTPUT and INOUT typemaps which can be used to solve some instances of this problem. 
 
4082
This library file uses an array as a means of moving data to and from Java when wrapping a C function that takes non const pointers or non const references as parameters. <p>
 
4083
 
 
4084
Now we are going to outline an alternative approach to using arrays for C pointers. 
 
4085
The INOUT typemap uses a <tt>double[]</tt> array for receiving and returning the <tt>double*</tt> parameters. 
 
4086
In this approach we are able to use a Java class <tt>myDouble</tt> instead of <tt>double[]</tt> arrays where the C pointer <tt>double*</tt> is required. 
 
4087
Here is our example function:
 
4088
 
1126
4089
<blockquote><pre>
1127
4090
/* Returns a status value and two values in out1 and out2 */
1128
4091
int spam(double a, double b, double *out1, double *out2);
1129
4092
</pre></blockquote>
1130
4093
 
1131
 
If we define a structure 'MyDouble' containing a double and use some typemaps we can solve this problem, for example we could put the following through SWIG:
 
4094
If we define a structure <tt>MyDouble</tt> containing a <tt>double</tt> member variable and use some typemaps we can solve this problem. For example we could put the following through SWIG:
1132
4095
<blockquote><pre>
1133
 
%pragma make_default
1134
4096
%module example
1135
4097
 
 
4098
/* Define a new structure to use instead of double * */
 
4099
%inline %{
 
4100
typedef struct {
 
4101
    double value;
 
4102
} MyDouble;
 
4103
%}
 
4104
 
 
4105
 
1136
4106
%{
1137
4107
/* Returns a status value and two values in out1 and out2 */
1138
4108
int spam(double a, double b, double *out1, double *out2) {
1143
4113
};
1144
4114
%}
1145
4115
 
1146
 
/* Define a new structure to use instead of double* */
1147
 
%inline %{
1148
 
typedef struct {
1149
 
    double value;
1150
 
} MyDouble;
1151
 
%}
1152
 
 
1153
4116
/* 
1154
 
This typemap will make any double* function parameters with name 'OutValue' take an
1155
 
argument of MyDouble instead of double*. Requires -shadow commandline option. This will 
1156
 
allow the calling function to read the double* value after returning from the function.
 
4117
This typemap will make any double * function parameters with name <tt>OUTVALUE</tt> take an
 
4118
argument of MyDouble instead of double *. This will 
 
4119
allow the calling function to read the double * value after returning from the function.
1157
4120
*/
1158
 
%typemap(in) double *OutValue {
1159
 
    jclass clazz = jenv-&gt;FindClass("MyDouble");
1160
 
    jfieldID fid = jenv-&gt;GetFieldID(clazz, "_cPtr", "J");
1161
 
    jlong cPtr = jenv-&gt;GetLongField($input, fid);
1162
 
    MyDouble* pMyDouble;
1163
 
    *(MyDouble*)&pMyDouble = *(MyDouble*)&cPtr;
1164
 
    $1 = &pMyDouble-&gt;value;
 
4121
%typemap(in) double *OUTVALUE {
 
4122
    jclass clazz = jenv->FindClass("MyDouble");
 
4123
    jfieldID fid = jenv->GetFieldID(clazz, "swigCPtr", "J");
 
4124
    jlong cPtr = jenv->GetLongField($input, fid);
 
4125
    MyDouble *pMyDouble = NULL;
 
4126
    *(MyDouble *)&pMyDouble = *(MyDouble *)&cPtr;
 
4127
    $1 = &pMyDouble->value;
1165
4128
}
1166
4129
 
1167
 
/* This tells SWIG what Java type to use */
1168
 
%typemap(jtype) double* OutValue "MyDouble"
1169
 
%typemap(jstype) double* OutValue "MyDouble"
 
4130
%typemap(jtype) double *OUTVALUE "MyDouble"
 
4131
%typemap(jstype) double *OUTVALUE "MyDouble"
 
4132
%typemap(jni) double *OUTVALUE "jobject"
1170
4133
 
1171
 
/* This tells SWIG what the matching JNI type for the Java type is */
1172
 
%typemap(jni) double* OutValue "jobject"
 
4134
%typemap(javain) double *OUTVALUE "$javainput"
1173
4135
 
1174
4136
/* Now we apply the typemap to the named variables */
1175
 
%apply double* OutValue { double *out1, double* out2 };
 
4137
%apply double *OUTVALUE { double *out1, double *out2 };
1176
4138
int spam(double a, double b, double *out1, double *out2);
1177
4139
</pre></blockquote>
1178
4140
 
1179
 
Note that the C++ JNI calling convention has been used this time and so must be compiled as C++ and the -c++ commandline must be passed to SWIG. Also this will only work with shadow classes enabled (-shadow commandline option) as the MyDouble shadow class contains the member variable '_cPtr' which we need in the 'in' typemap. JNI error checking has been omitted for clarity.<p>
 
4141
Note that the C++ JNI calling convention has been used this time and so must be compiled as C++ and the -c++ commandline must be passed to SWIG. 
 
4142
JNI error checking has been omitted for clarity.<p>
1180
4143
 
1181
 
What the typemaps do are make the named double* function parameters use our new MyDouble wrapper structure. The 'in' typemap takes this structure, gets the C++ pointer to it, is then able to get the 'double value' member variable to pass to the C++ <tt>spam</tt> function. In Java, when the function returns, we use the SWIG created <tt>getValue()</tt> function to get the output value. The following Java program demonstrates this:
 
4144
What the typemaps do are make the named <tt>double*</tt> function parameters use our new <tt>MyDouble</tt> wrapper structure. 
 
4145
The "in" typemap takes this structure, gets the C++ pointer to it, takes the <tt>double value</tt> member variable and passes it to the C++ <tt>spam</tt> function. 
 
4146
In Java, when the function returns, we use the SWIG created <tt>getValue()</tt> function to get the output value. 
 
4147
The following Java program demonstrates this:
1182
4148
<blockquote><pre>
1183
4149
// File: main.java
1184
 
import example.*;
1185
4150
 
1186
4151
public class main {
1187
4152
 
1209
4174
1 12.0  340.0
1210
4175
</pre></blockquote>
1211
4176
 
1212
 
<a name="n128"></a><h3> Accessing array structure members</h3>
1213
 
 
1214
 
Consider the following data structure :<p>
1215
 
<p>
1216
 
<blockquote><pre>
1217
 
#define LEN   5
1218
 
typedef struct {
1219
 
  int numbers[LEN];
1220
 
} Data;
1221
 
</pre></blockquote>
1222
 
 
1223
 
By default, the Java module supplies the memberin typemap in the Lib/java/java_arrays file to set array members. It is generic, but not particularly efficient as it copies one array member at a time. You may want to override it for the above Data struct as follows:<p>
1224
 
<p>
1225
 
<blockquote><pre>
1226
 
%typemap(memberin) int[LEN] {
1227
 
  /* Copy at most LEN characters into $1 */
1228
 
  memcpy($1,$input,sizeof(int)*LEN);
1229
 
}
1230
 
</pre></blockquote>
1231
 
 
1232
 
Whenever a <tt>int[LEN]</tt> type is encountered in a structure or class, this typemap provides a safe mechanism for setting its value.   An alternative implementation might choose to print an error message if the Java supplied array was too long to fit into the field.<p>
1233
 
<p>
1234
 
It should be noted that the <tt>[LEN]</tt> array size is attached to the typemap. A datatype involving some other kind of array would not be affected.   However, you can write a typemap to match any sized array using the <tt>ANY</tt> keyword as follows :<p>
1235
 
<p>
1236
 
<blockquote><pre>
1237
 
%typemap(memberin) int [ANY] {
1238
 
  memcpy($1,$input,sizeof(int)*$dim0);
1239
 
}
1240
 
</pre></blockquote>
1241
 
<p>
1242
 
During code generation, <tt>$dim0</tt> will be filled in with the real array dimension.  <p>
1243
 
 
1244
 
<a name="n129"></a><h3> Pointer handling</h3>
1245
 
Unlike other language modules, the Java SWIG pointer library has not been written. The consequence of this is that there is no access to the SWIG runtime type checker which is used by the pointer library. 
1246
 
This also means that your own pointer handling functions will have to be written or use some of the concepts shown in the typemap examples. The typemaps.i library file will be useful for pointer handling as previously mentioned. All is not lost as this does not apply when using shadow classes and non-primitive data types, as the section on Shadow classes demonstrates.
1247
 
<p>
1248
 
 
1249
 
Pointers are stored in a Java long, which is a 64 bit number. However most JVMs are 32 bit applications so any JNI code must also be compiled as 32 bit. This means that the pointers in JNI code are also 32 bits. What happens for various reasons is on big endian machines the pointer is stored in the high order 4bytes, whereas on little endian machines the pointer is stored in the low order 4bytes. 
1250
 
As a result, care must be taken if you intend to manipulate the pointer directly from Java. This can of course can be changed with judicious use of typemaps, but normally you needn't worry about any of this unless you want to modify pointers within Java code.<p>
1251
 
 
1252
 
By now you hopefully have the idea that typemaps are a powerful mechanism for building more specialized applications.  While writing typemaps can be technical, many have already been written for you.  See the Typemaps chapter for more information about using library files.<p>
1253
 
 
1254
 
 
1255
 
<a name="n8"></a><h2>The gory details of shadow classes</h2>
1256
 
This section describes the process by which SWIG creates shadow classes and some of the more subtle aspects of using them.<p>
1257
 
<a name="n130"></a><h3> A simple shadow class</h3>
1258
 
Consider the following barebones C++ class:<p>
1259
 
<p>
1260
 
<blockquote><pre>
1261
 
%module example
1262
 
 
1263
 
%inline %{
1264
 
 
1265
 
class Simple {
1266
 
public:
1267
 
    Simple() {};
1268
 
    ~Simple() {};
1269
 
};
1270
 
 
1271
 
%}
1272
 
</pre></blockquote>
1273
 
<p>
1274
 
The SWIG generated class in file Simple.java looks like the following:<p>
1275
 
<p>
1276
 
<blockquote><pre>
1277
 
// File Simple.java
1278
 
import example;
1279
 
 
1280
 
public class Simple {
1281
 
  protected long _cPtr;
1282
 
  protected boolean _cMemOwn;
1283
 
 
1284
 
  public Simple(long cPointer, boolean cMemoryOwn) {
1285
 
    _cPtr = cPointer;
1286
 
    _cMemOwn = cMemoryOwn;
1287
 
  }
1288
 
 
1289
 
  public long getCPtr() {
1290
 
    return _cPtr;
1291
 
  }
1292
 
 
1293
 
  public Simple() {
1294
 
    _cPtr = example.new_Simple();
1295
 
    _cMemOwn = true;
1296
 
  }
1297
 
 
1298
 
  protected void finalize() {
1299
 
    _delete();
1300
 
  }
1301
 
 
1302
 
  public void _delete() {
1303
 
    if(_cPtr!=0 && _cMemOwn) {
1304
 
      example.delete_Simple(_cPtr);
1305
 
      _cPtr = 0;
1306
 
    }
1307
 
  }
1308
 
 
1309
 
}
1310
 
</pre></blockquote>
1311
 
<a name="n131"></a><h3> Generated class</h3>
1312
 
Shadow classes are built using the low-level SWIG generated C interface.  The simple interface is wrapped into a Java class named after the module name, 'example' here. The Java code for the shadow class is created in many different files. The name of each file is the name of the shadow class, which in turn is named after the class/struct/union that is being shadowed (proxied). This has to be the case as in Java a class called 'A' must be in a file called A.java. Except for a couple of memory management methods and constructors, the methods in the shadow class simply call the SWIG generated functions in the simple interface. The shadow class is a lot easier to use as it wraps the C++ 'this' pointer making memory management a lot easier and less error prone. Shadow classes generally fit in with the Java programming paradigm.<p>
1313
 
 
1314
 
<a name="n132"></a><h3> The this pointer</h3>
1315
 
Each generated shadow class has the above member variables and functions, except derived classes, which will be covered later. The <tt>_cPtr</tt> holds the pointer to an instance of the C/C++ class/struct/union, so it contains the C++ 'this' pointer. If you need the pointer it can be obtained by using the getCPtr(), as <tt>_cPtr</tt> is protected data. The shadow classes have been written with easy memory management in mind for most cases so you should normally not need to use <tt>_cPtr</tt>, nor its public accessor function getCPtr(). 
1316
 
 
1317
 
</pre></blockquote>
1318
 
The <tt>Grid2d</tt> class, on the other hand, is used when you want to create a new <tt>Grid2d</tt> object from Java.   In reality, it inherits all of the attributes of a <tt>Grid2dPtr</tt>, except that its constructor calls the corresponding C++ constructor to create a new object.    Thus, in Java, this would look something like the following :<p>
1319
 
<p>
1320
 
<blockquote><pre>&gt;&gt;&gt; g = Grid2d(50,50)           # Create a new Grid2d
1321
 
&gt;&gt;&gt; g.xpoints
1322
 
50
1323
 
&gt;&gt;&gt;
1324
 
 
1325
 
</pre></blockquote>
1326
 
<a name="n133"></a><h3> Object ownership</h3>
1327
 
Ownership is a critical issue when mixing C++ and Java.  For example, suppose I create a new object in C++, but later use it  to create a Java object.  If that object is being used elsewhere in the C++ code, we clearly don't want Java to delete the C++ object when the Java object is deleted.  Similarly, what if I create a new object in Java, but C++ saves a pointer to it and starts using it repeatedly.  Clearly, we need some notion of who owns what.  Since sorting out all of the possibilities is probably impossible, the shadow class always has an attribute "<tt>_cMemOwn</tt>" that indicates whether or not Java owns an object.  <p>
1328
 
 
1329
 
The default object ownership falls into 2 cases:<br>
1330
 
<ol>
1331
 
<li>Whenever an object is created in Java, Java will be given ownership by setting <tt>_cMemOwn </tt> to <tt>true</tt>.  </li>
1332
 
<li>When a Java class is created from a pre-existing SWIG generated shadow class, ownership is assumed to belong to the C/C++ code and <tt>_cMemOwn</tt> will be set to <tt>false</tt>. </li>
1333
 
</ol>
1334
 
When <tt>_cMemOwn</tt> is set, Java will attempt to call the C/C++ destructor when the object is deleted, that is garbage collected. If it is zero, Java will never call the C/C++ destructor. Ownership of an object is set up using the appropriate constructors. Note that sometimes the garbage collector does not call finalizers. Please see the section on Shadow classes and Garbage collection for more information.<p>
1335
 
 
1336
 
<a name="n134"></a><h3> Constructors and destructors</h3>
1337
 
C++ constructors are mapped into an equivalent Java constructor. An additional constructor is available for use which overrides the default memory handling/memory ownership. For the above example, this constructor is shown as:
1338
 
<blockquote><pre>
1339
 
  public Simple(long cPointer, boolean cMemoryOwn) {
1340
 
    _cPtr = cPointer;
1341
 
    _cMemOwn = cMemoryOwn;
1342
 
  }
1343
 
</pre></blockquote>
1344
 
It allows one to override the above default <tt>_cPtr</tt> and <tt>_cMemOwn</tt> values on construction.<p>
1345
 
 
1346
 
The <tt>finalize()</tt> method is generated by default, but it can be turned off using the -nofinalize commandline option. It calls the <tt>_delete()</tt> method which calls the C++ destructor only if the Java object owns the C++ memory.
1347
 
 
1348
 
If there is no C++ default constructor, a default constructor is required by Java and so a protected constructor is generated as follows:
1349
 
<blockquote><pre>
1350
 
  protected Simple() {
1351
 
    _cPtr = 0;
1352
 
    _cMemOwn = false;
1353
 
  }
1354
 
</pre></blockquote>
1355
 
It is highly recommended to use the %make_default directive in your interface file so that SWIG generates default constructors and destructors if none exist. This is useful as these do not exist if you are using C. Note that when using C++ the compiler generates a default constructor and destructor for you if none exist, so this is different to SWIG's default behaviour. 
1356
 
 
1357
 
Note that SWIG currently does not support method overloading and thus constructor overloading, but this is likely to change in a future release.
1358
 
 
1359
 
<a name="n135"></a><h3> Member data</h3>
1360
 
Member data of a C/C++ object is accessed through getter and setter methods. For example, if a public member variable and a public static member variable is added to the previous bare bones class as such:<p>
1361
 
<blockquote><pre>
1362
 
class Simple {
1363
 
public:
1364
 
    Simple() {};
1365
 
    ~Simple() {};
1366
 
    int Number;
1367
 
    static int StaticNumber;
1368
 
};
1369
 
</pre></blockquote>
1370
 
The class can be used as follows to read and write to the variables:
1371
 
<blockquote><pre>
1372
 
Simple simp = new Simple();
1373
 
simp.setNumber(10);
1374
 
int number = simp.getNumber();
1375
 
 
1376
 
Simple.setStaticNumber(10);
1377
 
number = Simple.getStaticNumber();
1378
 
</pre></blockquote>
1379
 
Note that the C++ static member variable is mapped using Java static getters and setters.
1380
 
 
1381
 
<a name="n136"></a><h3> Shadow Functions</h3>
1382
 
Suppose you have the following declarations in an interface file :<p>
1383
 
<p>
1384
 
<blockquote><pre>
1385
 
%module example
1386
 
struct Vector {
1387
 
    Vector();
1388
 
    ~Vector();
1389
 
    double x,y,z;
1390
 
    static Vector addv(Vector a, Vector b);
1391
 
};
1392
 
</pre></blockquote>
1393
 
By default in the simple SWIG interface, the function <tt>addv</tt> will operate on Vector pointers (a Java long), not Java classes:
1394
 
 
1395
 
<blockquote><pre>
1396
 
// Member function in class example (SWIG's simple interface)
1397
 
  public final static native long Vector_addv(long jarg0, long jarg1);
1398
 
</pre></blockquote>
1399
 
 
1400
 
However, when using shadow classes, the Java SWIG module is smart enough to know that <tt>Vector</tt> has been wrapped into a Java class so it will create the following shadow function for the <tt>addv()</tt> function.<p>
1401
 
 
1402
 
<blockquote><pre>
1403
 
// Member function in class Vector (the shadow class)
1404
 
public static Vector addv(Vector a, Vector b) {
1405
 
  return new Vector(example.Vector_addv(a.getCPtr(), b.getCPtr()), true);
1406
 
}
1407
 
</pre></blockquote>
1408
 
 
1409
 
Function arguments are modified to pick up the "this" pointer from a Java Vector object.  The return value is a pointer to the result which has been allocated by malloc or new (this behavior is described in the chapter on SWIG basics), so we simply create a new Vector class with the return value.  Since the result involved an implicit malloc, we set the ownership to <tt>true</tt> indicating that the result is to be owned by Java and that it should be deleted when the Java object is deleted.  As a result, operations like this  are perfectly legal and result in no memory leaks:<p>
1410
 
<p>
1411
 
<blockquote><pre>
1412
 
Vector v = Vector.addv(Vector.addv(Vector.addv(Vector.addv(a,b),c),d),e);
1413
 
</pre></blockquote>
1414
 
 
1415
 
<a name="n137"></a><h3> Shadow class pointer handling</h3>
1416
 
Now let's take the previous example and in a new function <tt>cross_product</tt> and use Vector pointers for the parameters as well as the return type:
1417
 
 
1418
 
<blockquote><pre>
1419
 
%module example
1420
 
struct Vector {
1421
 
    Vector();
1422
 
    ~Vector();
1423
 
    double x,y,z;
1424
 
    static Vector addv(Vector a, Vector b);
1425
 
    static Vector *cross_product(Vector *v1, Vector *v2);
1426
 
};
1427
 
</pre></blockquote>
1428
 
By default in the simple SWIG interface, the function <tt>cross_product</tt> will also operate on Vector pointers (a Java long):
1429
 
 
1430
 
<blockquote><pre>
1431
 
// Member function in class example (SWIG's simple interface)
1432
 
  public final static native long Vector_cross_product(long jarg0, long jarg1);
1433
 
</pre></blockquote>
1434
 
 
1435
 
When using shadow classes, the Java SWIG module still allows us to use a <tt>Vector</tt> proper:
1436
 
<blockquote><pre>
1437
 
// Member function in class Vector (the shadow class)
1438
 
  public static Vector cross_product(Vector v1, Vector v2) {
1439
 
    return new Vector(example.Vector_cross_product(v1.getCPtr(), v2.getCPtr()), false);
1440
 
  }
1441
 
 
1442
 
</pre></blockquote>
1443
 
 
1444
 
The shadow function gets the pointer for us from the Vector class. Note that the return value is a Vector whose memory ownership is set to <tt>false</tt> indicating that the memory is not owned by Java. The following section discusses this further.<p>
1445
 
 
1446
 
An important observation to note when using shadow classes is the differences in wrapping pointers to complex datatypes and pointers to primitive types. Pointers to complex data types are wrapped using a Java class, such as Vector for Vector*. Pointers to primitive types are wrapped in the same manner as the simple interface, that is a Java long for short*, int* etc.<p>
1447
 
 
1448
 
<a name="n138"></a><h3> Methods that return new objects</h3>
1449
 
By default SWIG assumes that constructors are the only functions returning new objects to Java.  However, you may have other functions that return new objects as well.  If we take our previous Vector example and examine the <tt>cross_product</tt> implementation:<p>
1450
 
<blockquote><pre>
1451
 
Vector *Vector::cross_product(Vector *v1, Vector *v2) {
1452
 
    Vector *result = new Vector();
1453
 
    result = ... compute cross product ...
1454
 
    return result;
1455
 
}
1456
 
</pre></blockquote>
1457
 
When the value is returned to Java, we want Java to assume ownership as the memory has been created on the heap. However, SWIG has no way of knowing that it should take ownership, so by default it does not. The memory has to be deleted after calling the cross_product function:<p>
1458
 
 
1459
 
<blockquote><pre>
1460
 
Vector a = new Vector();
1461
 
Vector b = new Vector();
1462
 
// ... populate a and b ...
1463
 
 
1464
 
Vector c = Vector.cross_product(a, b);
1465
 
 
1466
 
// clean up the memory allocated by cross_product
1467
 
example.delete_Vector(c.getCPtr());
1468
 
</pre></blockquote>
1469
 
 
1470
 
Unfortunately, this is ugly, is likely to be forgotten and it doesn't work if we use the result as a  temporary value :<p>
1471
 
<p>
1472
 
<blockquote><pre>
1473
 
Vector w = Vector.addv(Vector.cross_product(a,b),c);     // Results in a memory leak
1474
 
</pre></blockquote>
1475
 
However, you can provide a hint to SWIG when working with such a function as shown :<p>
1476
 
 
1477
 
<blockquote><pre>
1478
 
// C/C++ Function returning a new object
1479
 
struct Vector {
1480
 
...
1481
 
%new static Vector *cross_product(Vector *v1, Vector *v2);
1482
 
...
1483
 
};
1484
 
</pre></blockquote>
1485
 
The <tt>%new</tt> directive provides a hint that the function is returning a new object.  The Java module will assign proper ownership of the object when this is used. This can be seen as this time it uses <tt>true</tt> in the constructor:<p>
1486
 
 
1487
 
<blockquote><pre>
1488
 
// Member function in class Vector (the shadow class)
1489
 
  public static Vector cross_product(Vector v1, Vector v2) {
1490
 
    return new Vector(example.Vector_cross_product(v1.getCPtr(), v2.getCPtr()), true);
1491
 
  }
1492
 
</pre></blockquote>
1493
 
 
1494
 
<a name="n139"></a><h3> Global variables and functions</h3>
1495
 
Substitution of complex datatypes occurs for all shadow functions and shadow member functions involving structures, unions or class definitions.  Currently no shadow classes are produced for global variables nor global functions. Only the low-level C interface is produced. This is an important limitation. The recommended approach is to put all global access into a dummy structure with static function access:<p>
1496
 
 
1497
 
<blockquote><pre>
1498
 
%module example
1499
 
%pragma make_default
1500
 
 
1501
 
%inline %{
1502
 
struct Vector {
1503
 
    Vector() {};
1504
 
    ~Vector() {};
1505
 
    double x,y,z;
1506
 
    static Vector addv(Vector a, Vector b);
1507
 
};
1508
 
 
1509
 
// Global function and variable
1510
 
Vector global_subv(Vector a, Vector b);
1511
 
Vector global_vec;
1512
 
 
1513
 
// Global function and variable wrapped into this structure
1514
 
struct Globals {
1515
 
    static Vector sub1(Vector a, Vector b) { return global_subv(a, b); };
1516
 
    static void setGlobal_vec(Vector v) { global_vec = v; };
1517
 
    static Vector getGlobal_vec(void) { return global_vec; };
1518
 
};
1519
 
%}
1520
 
 
1521
 
// Alternative way to wrap global functions into a structure
1522
 
%addmethods Globals { static Vector sub2(Vector a, Vector b) { return global_subv(a, b); }
1523
 
</pre></blockquote>
1524
 
The dummy class consists entirely of static member functions. Note the two different ways that global_subv can be wrapped into Globals. Access to the global function <tt>global_subv</tt> is then much neater:
1525
 
 
1526
 
<blockquote><pre>
1527
 
Vector a = new Vector();
1528
 
Vector b = new Vector();
1529
 
// ... setup a and b ...
1530
 
 
1531
 
// Access to global function which has been wrapped into the Globals shadow class
1532
 
Vector c1 = Globals.sub1(a,b);
1533
 
Vector c2 = Globals.sub2(a,b);
1534
 
 
1535
 
// Access to global function using simple interface
1536
 
Vector c3 = new Vector(example.global_subv(a.getCPtr(), b.getCPtr()), true); 
1537
 
</pre></blockquote>
1538
 
 
1539
 
This is one area where the Java module needs improving in the future so that all global functions are for instance automatically accessible through a shadow class.<p>
1540
 
 
1541
 
<a name="n140"></a><h3> Nested objects</h3>
1542
 
SWIG shadow classes support nesting of complex objects.  For example, suppose you had the following interface file :<p>
1543
 
<p>
1544
 
<blockquote><pre>
1545
 
%module example
1546
 
%pragma make_default
1547
 
 
1548
 
%inline %{
1549
 
 
1550
 
struct Vector {
1551
 
    double x,y,z;
1552
 
    static Vector addv(Vector a, Vector b);
1553
 
};
1554
 
 
1555
 
typedef struct {
1556
 
  Vector r;
1557
 
  Vector v;
1558
 
  Vector f;
1559
 
  int    type;
1560
 
} Particle;
1561
 
 
1562
 
%}
1563
 
</pre></blockquote>
1564
 
<p>
1565
 
In this case you will be able to read and write to members as follows :<p>
1566
 
<p>
1567
 
<blockquote><pre>
1568
 
Vector v1 = new Vector();
1569
 
Vector v2 = new Vector();
1570
 
// ... populate v1 and v2 ...
1571
 
 
1572
 
Particle p = new Particle();
1573
 
p.getR().setX(0.0);
1574
 
p.getR().setY(-1.5);
1575
 
p.getR().setZ(2.0);
1576
 
p.setV( Vector.addv(v1, v2) );
1577
 
</pre></blockquote>
1578
 
 
1579
 
Nested structures such as the following are also supported by SWIG. These types of structures tend to arise frequently in database and information processing applications.<p>
1580
 
 
1581
 
<blockquote><pre>
1582
 
typedef struct {  
1583
 
        unsigned int dataType;
1584
 
        union {
1585
 
                int       intval;
1586
 
                double    doubleval;
1587
 
                char     *charval;
1588
 
                void     *ptrvalue;
1589
 
                long      longval;
1590
 
                struct {
1591
 
                        int    i;
1592
 
                        double f;
1593
 
                        void   *v;
1594
 
                        char name[32];
1595
 
              } v;
1596
 
        } u;
1597
 
} ValueStruct;
1598
 
 
1599
 
</pre></blockquote>
1600
 
Access is provided like this:<p>
1601
 
 
1602
 
<blockquote><pre>
1603
 
ValueStruct v = new ValueStruct();
1604
 
// ... populate ValueStruct somehow ...
1605
 
 
1606
 
long dataType = v.getDataType();
1607
 
int intval = v.getU().getIntval();
1608
 
double f = v.getU().getV().getF();
1609
 
</pre></blockquote>
1610
 
 
1611
 
To support the embedded structure definitions, SWIG has to extract the internal structure definitions and use them to create new Java classes.  In this example, the following shadow classes are created:<p>
1612
 
 
1613
 
<blockquote><pre>
1614
 
//Class corresponding to union u member
1615
 
ValueStruct_u u = v.getU();
1616
 
 
1617
 
//Class corresponding to struct v member of union u
1618
 
ValueStruct_u_v uv = v.getU().getV();
1619
 
</pre></blockquote>
1620
 
<p>
1621
 
The names of the new classes are formed by appending the member names of each embedded structure.<p>
1622
 
 
1623
 
<a name="n141"></a><h3> Inheritance and shadow classes</h3>
1624
 
Since shadow classes are implemented in Java, you can use any of the automatically generated classes as a base class for more Java classes.<p>
1625
 
 
1626
 
SWIG can detect C++ classes that are abstract. This means that the Java shadow class can accurately shadow the C++ class. For example, given the abstract base class Shape and its derived class Circle:
1627
 
 
1628
 
<blockquote><pre>
1629
 
class Shape {
1630
 
  double  x, y;   
1631
 
public:
1632
 
  Shape();
1633
 
  virtual ~Shape();
1634
 
  void    move(double dx, double dy);
1635
 
  virtual double area() = 0;
1636
 
};
1637
 
 
1638
 
class Circle : public Shape {
1639
 
private:
1640
 
  double radius;
1641
 
public:
1642
 
  Circle(double r) : radius(r) { };
1643
 
  virtual double area();
1644
 
};
1645
 
</pre></blockquote>
1646
 
 
1647
 
The Shape shadow class becomes an abstract Java class with the pure virtual function <tt>area</tt> being declared as a Java abstract method. The constructor is also made protected:
1648
 
 
1649
 
<blockquote><pre>
1650
 
// File Shape.java
1651
 
import example;
1652
 
 
1653
 
public abstract class Shape {
1654
 
  protected long _cPtr;
1655
 
  protected boolean _cMemOwn;
1656
 
 
1657
 
  public Shape(long cPointer, boolean cMemoryOwn) {
1658
 
    _cPtr = cPointer;
1659
 
    _cMemOwn = cMemoryOwn;
1660
 
  }
1661
 
 
1662
 
  public long getCPtr() {
1663
 
    return _cPtr;
1664
 
  }
1665
 
 
1666
 
  protected Shape() {
1667
 
    _cPtr = 0;
1668
 
    _cMemOwn = false;
1669
 
  }
1670
 
 
1671
 
  protected void finalize() {
1672
 
    _delete();
1673
 
  }
1674
 
 
1675
 
  public void _delete() {
1676
 
    if(_cPtr!=0 && _cMemOwn) {
1677
 
      example.delete_Shape(_cPtr);
1678
 
      _cPtr = 0;
1679
 
    }
1680
 
  }
1681
 
 
1682
 
  public void move(double dx, double dy) {
1683
 
    example.Shape_move(_cPtr, dx, dy);
1684
 
  }
1685
 
 
1686
 
  public abstract double area();
1687
 
 
1688
 
}
1689
 
</pre></blockquote>
1690
 
 
1691
 
The Circle class extends Shape mirroring the C++ class inheritance hierarchy.
1692
 
 
1693
 
<blockquote><pre>
1694
 
// File Circle.java
1695
 
import example;
1696
 
 
1697
 
public class Circle extends Shape {
1698
 
  public Circle(long cPointer, boolean cMemoryOwn) {
1699
 
    super(cPointer, cMemoryOwn);
1700
 
  }
1701
 
 
1702
 
  protected Circle() {
1703
 
  }
1704
 
 
1705
 
  public Circle(double r) {
1706
 
    super(0, false);
1707
 
    _cPtr = example.new_Circle(r);
1708
 
    _cMemOwn = true;
1709
 
    // The above will be optimised in the future to: 
1710
 
    // super(example.new_Circle(r), true);
1711
 
  }
1712
 
 
1713
 
  public double area() {
1714
 
    return example.Circle_area(_cPtr);
1715
 
  }
1716
 
 
1717
 
}
1718
 
</pre></blockquote>
1719
 
It is then of course possible to extend Shape using your own Java classes. If say <tt>Circle</tt> is provided by the C++ code, you could for example add in a pure Java class <tt>Rectangle</tt>. There is a caveat and that is any C++ code will not know about your Java class <tt>Rectangle</tt> so this type of derivation is restricted.<p>
1720
 
 
1721
 
Note that Java does not support multiple inheritance so any multiple inheritance in the C++ code is not going to work. A warning is given when multiple inheritance is detected and only the first base class is used. 
1722
 
 
1723
 
<a name="n142"></a><h3>Shadow classes and garbage collection</h3>
1724
 
If you get SWIG to produce shadow classes, you will notice the generated <code>_delete()</code> and <code>finalize()</code> methods. The <code>finalize()</code> method calls <code>_delete()</code> which frees any SWIG malloced c memory for wrapped structs or deletes any SWIG wrapped classes created on the heap, which in turn calls the class' destructor. The idea is for <code>_delete()</code> to be called when you have finished with the C/C++ object. Ideally you need not call <code>_delete()</code>, but rather leave it to the garbage collector to call it from the finalizer. The unfortunate thing is that Sun, in their wisdom, do not guarantee that the finalizers will be called. When a program exits, the garbage collector does not always call the finalizers. Depending on what the finalizers do and which operating system you use, this may or may not be a problem. 
1725
 
<p>
1726
 
 
1727
 
If the <code>_delete()</code> call into JNI code is just for memory handling, there is not a problem when run on Windows and Unix. Say your JNI code creates memory on the heap which your finalizers will clean up, the finalizers may or may not be called before the program exits. In Windows and Unix all memory that a process uses is returned to the system, so this isn't a problem. This is not the case in some operating systems like vxWorks. If however, your finalizer calls into JNI code invoking the C++ destructor which in turn releases a TCP/IP socket for example, there is no guarantee that it will be released. Note that the garbage collector will eventually run, so long running programs will have their unreferenced object's finalizers called.
1728
 
<p>
1729
 
 
1730
 
Some not so ideal solutions are:
1731
 
<ol>
1732
 
<li start=1>
1733
 
Call the <code>System.runFinalizersOnExit(true)</code> or <code>Runtime.getRuntime().runFinalizersOnExit(true)</code> to ensure the finalizers are called before the program exits. The catch is that this is a deprecated function call as the documenation says: 
1734
 
<blockquote><i>
1735
 
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.
1736
 
</i></blockquote> 
1737
 
In many cases you will be lucky and find that it works, but it is not to be advocated. Have a look at <a href=http://java.sun.com>Sun's Java web site</a> and search for <code>runFinalizersOnExit</code>.
1738
 
</li>
1739
 
<p>
1740
 
<li>
1741
 
From jdk1.3 onwards a new function, <code>addShutdownHook()</code>, was introduced which is guaranteed to be called when your program exits. You can encourage the garbage collector to call the finalizers, for example, add this static block to the class that has the <code>main()</code> function: 
1742
 
<blockquote><pre>
1743
 
  static {
1744
 
    Runtime.getRuntime().addShutdownHook( 
1745
 
      new Thread() {
1746
 
        public void run() { System.gc(); System.runFinalization(); }
1747
 
      }
1748
 
    );
1749
 
  }
1750
 
</pre></blockquote>
1751
 
Although this usually works, the documentation doesn't guarantee that <code>runFinalization()</code> will actually call the finalizers. As the the shutdown hook is guaranteed you could also make a JNI call to clean up any resources that are being tracked by the C/C++ code.
1752
 
</li>
1753
 
<p>
1754
 
<li>
1755
 
Call the <code>_delete()</code> function manually. As a suggestion it may be a good idea to set the object to null so that should the object be inadvertantly used again a Java null pointer exception is thrown, the alternative would crash the JVM by using a null c pointer. For example given a SWIG generated class A:
1756
 
<blockquote><pre>
1757
 
A myA = new A();
1758
 
// use myA ...
1759
 
myA._delete();
1760
 
// any use of myA here would crash the JVM 
1761
 
myA=null;
1762
 
// any use of myA here would cause a Java null pointer exception to be thrown
1763
 
</pre></blockquote>
1764
 
The SWIG generated code ensures that the memory is not deleted twice, in the event the finalizers get called in addition to the manual <code>_delete()</code> call.
1765
 
</li>
1766
 
 
1767
 
<p>
1768
 
<li>
1769
 
Write your own object manager in Java. You could derive all SWIG classes from a single base class which could track which objects have had their finalizers run, then call the rest of them on program termination. Currently you cannot tell SWIG to derive a SWIG shadow class from any named Java class, but this is planned in the near future. An alternative is to add the object handling code to all generated shadow classes using the shadow pragma.
1770
 
</li>
1771
 
</ol>
1772
 
 
1773
 
<a name="n143"></a><h3> Performance concerns and hints</h3>
1774
 
Shadow classing is primarily intended to be a convenient way of accessing C/C++ objects from Java.   However, if you're directly manipulating huge arrays of complex objects from Java, performance may suffer greatly.  In these cases, you should consider implementing the functions in C or thinking of ways to optimize the problem. Try and minimise the expensive JNI calls to C/C++ functions, perhaps by using temporary Java variables instead of accessing the information directly from the C/C++ object.<p>
1775
 
<p>
1776
 
 
1777
 
If performance is really critical you can use the low-level interface which eliminates all of the overhead of going through the shadow classes (at the expense of coding simplicity).<p>
1778
 
 
1779
 
<p><hr>
1780
 
 
1781
 
<a name="n9"></a><h2>Java pragmas</h2>
1782
 
There are two groups of pragmas in the Java module. The first group modify the Java module output file and the second modify the Java shadow output file. The pragmas beginning with <b>module</b> apply to the module output file. The pragmas beginning with <b>allshadow</b> apply to all shadow output classes. The pragmas beginning with <b>shadow</b> apply to the currently active shadow class so these pragmas can only be specified within the definition of a class or struct. Some examples:
1783
 
<blockquote><pre>
1784
 
/* TestStruct.i */
1785
 
#ifdef SWIG
1786
 
%pragma(java) modulecode=%{ /*This code gets added to the module class*/ %}
1787
 
%pragma(java) modulecode=%{ /*This code gets added to the module class*/ %}
1788
 
%pragma(java) allshadowcode=%{ /*This code gets added to every shadow class*/ %}
1789
 
#endif
1790
 
typedef struct TestStruct {
1791
 
#ifdef SWIG
1792
 
%pragma(java) shadowcode=%{ /*This code gets added to the TestStruct shadow class only*/ %}
1793
 
#endif
1794
 
  int    myInt;
1795
 
} TestStruct;
1796
 
</pre></blockquote>
1797
 
<br>
1798
 
Note that pragmas will take either " " or %{ %} as delimeters. If the pragma requires the string quote it must be preceded with a backslash or alternatively use the %{ %} delimeters, for example either of these can be used to obtain the desired effect:
1799
 
 
1800
 
<blockquote><pre>
1801
 
%pragma(java) modulecode= "  public void sayHello() { System.out.println(\"Hello\"); } "
1802
 
%pragma(java) modulecode=%{  public void sayHello() { System.out.println("Hello"); } %}
1803
 
</pre></blockquote>
1804
 
<br>
1805
 
 
1806
 
A complete list of pragmas follows:
1807
 
<br><br>
1808
 
<table BORDER>
1809
 
<tr VALIGN=TOP>
1810
 
<td><b>Pragma</b></td>
1811
 
<td><b>Description</b></td>
1812
 
<td><b>Example</b></td>
1813
 
</tr>
1814
 
<tr>
1815
 
<td>modulebase</td>
1816
 
<td>Specifies a base class for the Java module class.</td>
1817
 
<td>%pragma(java) modulebase="BaseClass"</td>
1818
 
</tr>
1819
 
<tr>
1820
 
<td>shadowbase</td>
1821
 
<td>Specifies a base class for the Java shadow class.</td>
1822
 
<td>%pragma(java) shadowbase="BaseClass"</td>
1823
 
</tr>
1824
 
<tr>
1825
 
<td>allshadowbase</td>
1826
 
<td>Specifies a base class for all Java shadow classes.</td>
1827
 
<td>%pragma(java) allshadowbase="BaseClass"</td>
1828
 
</tr>
1829
 
<tr>
1830
 
<td>modulecode</td>
1831
 
<td>Adds code to the Java module class.</td>
1832
 
<td>%pragma(java) modulecode=%{/*module code*/%}</td>
1833
 
</tr>
1834
 
<tr>
1835
 
<td>shadowcode</td>
1836
 
<td>Adds code to the Java shadow class. See the JavaDoc section below about using this pragma for JavaDoc comments.</td>
1837
 
<td>%pragma(java) shadowcode=%{/*shadow code*/%}</td>
1838
 
</tr>
1839
 
<tr>
1840
 
<td>allshadowcode</td>
1841
 
<td>Adds code to all Java classes.</td>
1842
 
<td>%pragma(java) allshadowcode=%{/*all shadow code*/%}</td>
1843
 
</tr>
1844
 
<tr>
1845
 
<td>moduleclassmodifiers</td>
1846
 
<td>Overrides the default Java module class modifiers. The default is public.</td>
1847
 
<td>%pragma(java) moduleclassmodifiers="public final"</td>
1848
 
</tr>
1849
 
<tr>
1850
 
<td>shadowclassmodifiers</td>
1851
 
<td>Overrides the default Java shadow class modifiers. The default is public. Also overrides allshadowclassmodifiers if present.</td>
1852
 
<td>%pragma(java) shadowclassmodifiers="public final"</td>
1853
 
</tr>
1854
 
<tr>
1855
 
<td>allshadowclassmodifiers</td>
1856
 
<td>Overrides the default modifiers for all Java classes. The default is public.</td>
1857
 
<td>%pragma(java) allshadowclassmodifiers="public final"</td>
1858
 
</tr>
1859
 
<tr>
1860
 
<td>moduleimport</td>
1861
 
<td>Adds an import statement to the Java module class file.</td>
1862
 
<td>%pragma(java) moduleimport="java.lang.*"</td>
1863
 
</tr>
1864
 
<tr>
1865
 
<td>shadowimport</td>
1866
 
<td>Adds an import statement to the Java shadow class file. Adds to any imports specified in allshadowimport.</td>
1867
 
<td>%pragma(java) shadowimport="java.lang.*"</td>
1868
 
</tr>
1869
 
<tr>
1870
 
<td>allshadowimport</td>
1871
 
<td>Adds an import statement to all Java shadow class files.</td>
1872
 
<td>%pragma(java) allshadowimport="java.lang.*"</td>
1873
 
</tr>
1874
 
<tr>
1875
 
<td>moduleinterface</td>
1876
 
<td>Specifies an interface which the Java module output class implements. Can be used multiple times as Java supports multiple interfaces.</td>
1877
 
<td>%pragma(java) moduleinterface="SomeInterface"</td>
1878
 
</tr>
1879
 
<tr>
1880
 
<td>shadowinterface</td>
1881
 
<td>Specifies an interface which the Java shadow class implements. Can be used multiple times as Java supports multiple interfaces. Adds to any interfaces specified in allshadowinterface.</td>
1882
 
<td>%pragma(java) shadowinterface="SomeInterface"</td>
1883
 
</tr>
1884
 
<tr>
1885
 
<td>allshadowinterface</td>
1886
 
<td>Specifies an interface which all Java shadow classes implement. Can be used multiple times as Java supports multiple interfaces.</td>
1887
 
<td>%pragma(java) allshadowinterface="SomeInterface"</td>
1888
 
</tr>
1889
 
<tr>
1890
 
<td>modulemethodmodifiers</td>
1891
 
<td>Overrides the native default method modifiers for the module class. The default is public final static.</td>
1892
 
<td>%pragma(java) modulemethodmodifiers="protected final static synchronized"</td>
1893
 
</tr>
1894
 
</table>
1895
 
 
1896
 
</dl>
1897
 
 
1898
 
<a name="n144"></a><h3> Deprecated pragmas</h3>
1899
 
The following pragmas were in Swig 1.3a3 and have since been deprecated:<br>
1900
 
<b>import</b>: Please replace with <b>moduleimport</b>, <b>shadowimport</b> and/or <b>allshadowimport</b> pragmas.<br>
1901
 
<b>module</b>: Please replace with the <b>modulecode</b> pragma.<br>
1902
 
<b>shadow</b>: Please replace with the <b>allshadowcode</b> pragma.<br>
1903
 
<b>modifiers</b>: Please replace with the <b>modulemethodmodifiers</b> pragma.<br>
1904
 
 
1905
 
<a name="n145"></a><h3> Pragma uses</h3>
1906
 
The pragmas are used primarily to modify the default Java output code. They provide flexibility as to how Java and C++ interact. In the pragma notation below, <b>xxxcode</b> for example would be used to denote the 3 similar 'code' pragmas, that is <b>modulecode</b>, <b>shadowcode</b> and <b>allshadowcode</b>. 
1907
 
 
1908
 
<h4> Derive C++ from Java and visa-versa</h4>
1909
 
It is possible to derive a Java class from a shadow class (i.e. a C++ class) with the Java module. However, with the pragmas it is also possible to derive the SWIG produced Java shadow classes (i.e. C++ class) from your own Java class by using the <b>xxxbase</b> pragma with the <b>xxximport</b>, <b>xxxcode</b> and <b>xxxclassmodifiers</b> pragmas. It is also possible for the SWIG produced Java classes to implement interfaces using the <b>xxxinterface</b> pragmas.
1910
 
 
1911
 
<h4> JavaDoc and the shadowcode pragma</h4>
1912
 
The SWIG documentation feature is not currently present in the 1.3 versions of SWIG. However a limited form of JavaDoc documentation can be implemented by placing JavaDoc comments in the <b>shadowcode</b> pragma. Just put your JavaDoc comment in a <b>shadowcode</b> pragma before the function to which you want it to apply.
1913
 
 
1914
 
<h4> Tips for using the shadow pragmas</h4>
1915
 
Note that an out of scope warning is issued if any of the <b>shadow</b> pragmas are used outside of the class/struct/union definition. This requires one of these pragmas to be placed within the definition of the class/struct/union. It may seem that the original C/C++ code has to be modified when using the <tt>%include</tt> pragma. A technique to avoid this is to place the pragma within the <tt>%addmethods</tt> directive. For example:
1916
 
<blockquote><pre>
1917
 
%module example
 
4177
<a name="adding_downcasts"></a>
 
4178
<a name="n68"></a><H3>17.9.4 Adding Java downcasts to polymorphic return types</H3>
 
4179
 
 
4180
 
 
4181
SWIG support for polymorphism works in that the appropriate virtual function is called. However, the default generated code does not allow for downcasting. 
 
4182
Let's examine this with the follow code:
 
4183
 
 
4184
<blockquote><pre>
 
4185
%include "std_string.i"
 
4186
 
 
4187
#include &lt;iostream&gt;
 
4188
using namespace std;
 
4189
class Vehicle {
 
4190
public:
 
4191
    virtual void start() = 0;
 
4192
...
 
4193
};
 
4194
 
 
4195
class Ambulance : public Vehicle {
 
4196
    string vol;
 
4197
public:
 
4198
    Ambulance(string volume) : vol(volume) {}
 
4199
    virtual void start() {
 
4200
        cout << "Ambulance started" << endl;
 
4201
    }
 
4202
    void sound_siren() {
 
4203
        cout << vol << " siren sounded!" << endl;
 
4204
    }
 
4205
...
 
4206
};
 
4207
 
 
4208
Vehicle *vehicle_factory() {
 
4209
    return new Ambulance("Very loud");
 
4210
}
 
4211
</pre></blockquote>
 
4212
 
 
4213
If we execute the following Java code:
 
4214
 
 
4215
<blockquote><pre>
 
4216
Vehicle vehicle = example.vehicle_factory();
 
4217
vehicle.start();
 
4218
 
 
4219
Ambulance ambulance = (Ambulance)vehicle;
 
4220
ambulance.sound_siren();
 
4221
</pre></blockquote>
 
4222
 
 
4223
We get:
 
4224
 
 
4225
<blockquote><pre>
 
4226
Ambulance started
 
4227
java.lang.ClassCastException
 
4228
        at main.main(main.java:16)
 
4229
</pre></blockquote>
 
4230
 
 
4231
Even though we know from examination of the C++ code that <tt>vehicle_factory</tt> returns an object of type <tt>Ambulance</tt>, 
 
4232
we are not able to use this knowledge to perform the downcast in Java.
 
4233
This occurs because the runtime type information is not completely passed from C++ to Java when returning the type from <tt>vehicle_factory()</tt>.
 
4234
Usually this is not a problem as virtual functions do work by default, such as in the case of <tt>start()</tt>. 
 
4235
There are a few solutions to getting downcasts to work.
 
4236
<p>
 
4237
 
 
4238
The first is not to use a Java cast but a call to C++ to make the cast. Add this to your code:
 
4239
<blockquote><pre>
 
4240
%exception Ambulance::dynamic_cast(Vehicle *vehicle) {
 
4241
    $action
 
4242
    if (!result) {
 
4243
        jclass excep = jenv->FindClass("java/lang/ClassCastException");
 
4244
        if (excep) {
 
4245
            jenv->ThrowNew(excep, "dynamic_cast exception");
 
4246
        }
 
4247
    }
 
4248
}
 
4249
%extend Ambulance {
 
4250
    static Ambulance *dynamic_cast(Vehicle *vehicle) {
 
4251
        return dynamic_cast&lt;Ambulance *&gt;(vehicle);
 
4252
    }
 
4253
};
 
4254
</pre></blockquote>
 
4255
 
 
4256
It would then be used from Java like this
 
4257
 
 
4258
<blockquote><pre>
 
4259
Ambulance ambulance = Ambulance.dynamic_cast(vehicle);
 
4260
ambulance.sound_siren();
 
4261
</pre></blockquote>
 
4262
Should <tt>vehicle</tt> not be of type <tt>ambulance</tt> then a Java <tt>ClassCastException</tt> is thrown.
 
4263
The next solution is a purer solution in that Java downcasts can be performed on the types.
 
4264
Add the following before the definition of <tt>vehicle_factory</tt>:
 
4265
 
 
4266
<blockquote><pre>
 
4267
%typemap(out) Vehicle * {
 
4268
    Ambulance *downcast = dynamic_cast&lt;Ambulance *&gt;($1);
 
4269
    *(Ambulance **)&$result = downcast;
 
4270
}
 
4271
 
 
4272
%typemap(javaout) Vehicle * {
 
4273
    return new Ambulance($jnicall, $owner);
 
4274
  }
 
4275
</pre></blockquote>
 
4276
 
 
4277
Here we are using our knowledge that <tt>vehicle_factory</tt> always returns type <tt>Ambulance</tt> so that the Java proxy is created as a type <tt>Ambulance</tt>.
 
4278
If <tt>vehicle_factory</tt> can manufacture any type of <tt>Vehicle</tt> and we want to be able to downcast using Java casts for any of these types, then a different approach is needed.
 
4279
Consider expanding our example with a new Vehicle type and a more flexible factory function:
 
4280
 
 
4281
<blockquote><pre>
 
4282
class FireEngine : public Vehicle {
 
4283
public:
 
4284
    FireEngine() {}
 
4285
    virtual void start() {
 
4286
        cout << "FireEngine started" << endl;
 
4287
    }
 
4288
    void roll_out_hose() {
 
4289
        cout << "Hose rolled out" << endl;
 
4290
    }
 
4291
 ...
 
4292
};
 
4293
Vehicle *vehicle_factory(int vehicle_number) {
 
4294
    if (vehicle_number == 0)
 
4295
        return new Ambulance("Very loud");
 
4296
    else
 
4297
        return new FireEngine();
 
4298
}
 
4299
</pre></blockquote>
 
4300
 
 
4301
To be able to downcast with this sort of Java code:
 
4302
 
 
4303
<blockquote><pre>
 
4304
FireEngine fireengine = (FireEngine)example.vehicle_factory(1);
 
4305
fireengine.roll_out_hose();
 
4306
Ambulance ambulance = (Ambulance)example.vehicle_factory(0);
 
4307
ambulance.sound_siren();
 
4308
</pre></blockquote>
 
4309
 
 
4310
the following typemaps targeted at the <tt>vehicle_factory</tt> function will achieve this. 
 
4311
Note that in this case, the Java class is constructed using JNI code rather than passing a pointer across the JNI boundary in a Java long for construction in Java code.
 
4312
 
 
4313
<blockquote><pre>
 
4314
%typemap(jni) Vehicle *vehicle_factory "jobject"
 
4315
%typemap(jtype) Vehicle *vehicle_factory "Vehicle"
 
4316
%typemap(jstype) Vehicle *vehicle_factory "Vehicle"
 
4317
%typemap(javaout) Vehicle *vehicle_factory {
 
4318
    return $jnicall;
 
4319
  }
 
4320
 
 
4321
%typemap(out) Vehicle *vehicle_factory {
 
4322
    Ambulance *ambulance = dynamic_cast&lt;Ambulance *&gt;($1);
 
4323
    FireEngine *fireengine = dynamic_cast&lt;FireEngine *&gt;($1);
 
4324
    if (ambulance) {
 
4325
        // call the Ambulance(long cPtr, boolean cMemoryOwn) constructor
 
4326
        jclass clazz = jenv->FindClass("Ambulance");
 
4327
        if (clazz) {
 
4328
            jmethodID mid = jenv->GetMethodID(clazz, "<init>", "(JZ)V");
 
4329
            if (mid) {
 
4330
                jlong cptr = 0;
 
4331
                *(Ambulance **)&cptr = ambulance; 
 
4332
                $result = jenv->NewObject(clazz, mid, cptr, false);
 
4333
            }
 
4334
        }
 
4335
    } else if (fireengine) {
 
4336
        // call the FireEngine(long cPtr, boolean cMemoryOwn) constructor
 
4337
        jclass clazz = jenv->FindClass("FireEngine");
 
4338
        if (clazz) {
 
4339
            jmethodID mid = jenv->GetMethodID(clazz, "<init>", "(JZ)V");
 
4340
            if (mid) {
 
4341
                jlong cptr = 0;
 
4342
                *(FireEngine **)&cptr = fireengine; 
 
4343
                $result = jenv->NewObject(clazz, mid, cptr, false);
 
4344
            }
 
4345
        }
 
4346
    }
 
4347
    else {
 
4348
        cout << "Unexpected type " << endl;
 
4349
    }
 
4350
 
 
4351
    if (!$result)
 
4352
        cout << "Failed to create new java object" << endl;
 
4353
}
 
4354
</pre></blockquote>
 
4355
 
 
4356
Better error handling would need to be added into this code. 
 
4357
There are other solutions to this problem, but this last example demonstrates some more involved JNI code.
 
4358
SWIG usually generates code which constructs the proxy classes using Java code as it is easier to handle error conditions and is faster. 
 
4359
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.
 
4360
 
 
4361
<a name="adding_equals_method"></a>
 
4362
<a name="n69"></a><H3>17.9.5 Adding an equals method to the Java classes</H3>
 
4363
 
 
4364
 
 
4365
When a pointer is returned from a JNI function, it is wrapped using a new Java proxy class or type wrapper class. 
 
4366
Even when the pointers are the same, it will not be possible to know that the two Java classes containing those pointers are actually the same object.
 
4367
It is common in Java to use the <tt>equals()</tt> method to check whether two objects are equivalent.
 
4368
An equals method is easily added to all proxy classes. For example:
 
4369
 
 
4370
<blockquote>
 
4371
<pre>
 
4372
%typemap(javacode) SWIGTYPE %{
 
4373
  public boolean equals(Object obj) {
 
4374
    boolean equal = false;
 
4375
    if (obj instanceof $javaclassname)
 
4376
      equal = ((($javaclassname)obj).swigCPtr == this.swigCPtr);
 
4377
    return equal;
 
4378
  }
 
4379
%}
 
4380
 
 
4381
class Foo { };
 
4382
Foo* returnFoo(Foo *foo) { return foo; }
 
4383
</pre>
 
4384
</blockquote>
 
4385
 
 
4386
The following would display <tt>false</tt> without the <tt>javacode</tt> typemap above. With the typemap defining the <tt>equals</tt> method the result is <tt>true</tt>.
 
4387
 
 
4388
<blockquote>
 
4389
<pre>
 
4390
Foo foo1 = new Foo();
 
4391
Foo foo2 = example.returnFoo(foo1);
 
4392
System.out.println("foo1? " + foo1.equals(foo2));
 
4393
</pre>
 
4394
</blockquote>
 
4395
 
 
4396
 
 
4397
<a name="void_pointers"></a>
 
4398
<a name="n70"></a><H3>17.9.6 Void pointers and a common Java base class</H3>
 
4399
 
 
4400
 
 
4401
One might wonder why the common code that SWIG emits for the proxy and type wrapper classes is not pushed into a base class. 
 
4402
The reason is that although <tt>swigCPtr</tt> could be put into a common base class for all classes 
 
4403
wrapping C structures, it would not work for C++ classes involved in an inheritance chain.
 
4404
Each class derived from a base needs a separate <tt>swigCPtr</tt> because C++ compilers sometimes use a different pointer value when casting a derived class to a base.
 
4405
Additionally as Java only supports single inheritance, it would not be possible to derive wrapped classes from your own pure Java classes if the base class has been 'used up' by SWIG.
 
4406
However, you may want to move some of the common code into a base class. 
 
4407
Here is an example which uses a common base class for all proxy classes and type wrapper classes:
 
4408
 
 
4409
<blockquote>
 
4410
<pre>
 
4411
%typemap(javabase) SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE [], SWIGTYPE (CLASS::*) "SWIG"
 
4412
 
 
4413
%typemap(javacode) SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE [], SWIGTYPE (CLASS::*) %{
 
4414
  protected long getPointer() {
 
4415
    return swigCPtr;
 
4416
  }
 
4417
%}
 
4418
</pre>
 
4419
</blockquote>
 
4420
 
 
4421
<p>
 
4422
Define new base class called SWIG:
 
4423
 
 
4424
<blockquote>
 
4425
<pre>
 
4426
public abstract class SWIG {
 
4427
  protected abstract long getPointer();
 
4428
 
 
4429
  public boolean equals(Object obj) {
 
4430
    boolean equal = false;
 
4431
    if (obj instanceof SWIG)
 
4432
      equal = (((SWIG)obj).getPointer() == this.getPointer());
 
4433
    return equal;
 
4434
  }
 
4435
  
 
4436
  SWIGTYPE_p_void getVoidPointer() {
 
4437
    return new SWIGTYPE_p_void(getPointer(), false);
 
4438
  }
 
4439
}
 
4440
</pre>
 
4441
</blockquote>
 
4442
 
 
4443
This example contains some useful functionality which you may want in your code. 
 
4444
<ul>
 
4445
    <li> It has an <tt>equals()</tt> method. Unlike the previous example, the method code isn't replicated in all classes.
 
4446
    <li> It also has a function which effectively implements a cast from the type of the proxy/type wrapper class to a void pointer. This is necessary for passing a proxy class or a type wrapper class to a function that takes a void pointer.
 
4447
</ul>
 
4448
 
 
4449
<a name="java_directors_faq"></a>
 
4450
<a name="n71"></a><H2>17.10 Living with Java Directors</H2>
 
4451
 
 
4452
 
 
4453
<p>
 
4454
  This section is intended to address frequently asked questions and frequently encountered problems when using Java directors.
 
4455
</p>
 
4456
<ol>
 
4457
  <li><i>When my program starts up, it complains that </i>method_foo<i> cannot
 
4458
  be found in a Java method called </i>swig_module_init<i>. How do I fix
 
4459
  this?</i></li>
 
4460
 
 
4461
  <p>
 
4462
  Open up the C++ wrapper source code file and look for <code>"method_foo"</code> (include the double quotes, they are important!)
 
4463
  Look at the JNI field descriptor and make sure that each class that occurs in the descriptor has the correct package name in front of it.
 
4464
  If the package name is incorrect, put a "javapackage" typemap in your SWIG interface file.
 
4465
  </p>
 
4466
 
 
4467
  <li><i>I'm compiling my code and I'm using templates. I provided a
 
4468
  javapackage typemap, but SWIG doesn't generate the right JNI field
 
4469
  descriptor.</i></li>
 
4470
  <p>
 
4471
  Use the template's renamed name as the argument to the "javapackage" typemap:
 
4472
  <br>
 
4473
<blockquote>
 
4474
<pre>
 
4475
%typemap(javapackage)  std::vector<int>  "your.package.here"
 
4476
%template(VectorOfInt) std::vector<int>;
 
4477
</pre>
 
4478
</blockquote>
 
4479
  </p>
 
4480
 
 
4481
  <li><i>When I pass class pointers or references through a C++ upcall and I
 
4482
  try to type cast them, Java complains with a ClassCastException. What am I
 
4483
  doing wrong?</i></li>
 
4484
  <p>
 
4485
  Normally, a non-director generated Java proxy class creates temporary Java objects as follows:
 
4486
<blockquote>
 
4487
<pre>
 
4488
public static void MyClass_method_upcall(MyClass self, long jarg1)
 
4489
{
 
4490
  Foo darg1 = new Foo(jarg1, false);
 
4491
 
 
4492
  self.method_upcall(darg1);
 
4493
}
 
4494
</pre>
 
4495
</blockquote>
 
4496
  <br>
 
4497
  Unfortunately, this loses the Java type information that is part of the underlying Foo director proxy class's java object pointer causing the type cast to fail.
 
4498
  The SWIG Java module's director code attempts to correct the problem, <b>but only for director-enabled classes</b>, since the director class retains a global reference to its Java object.
 
4499
  Thus, for director-enabled classes <b>and only for director-enabled classes</b>, the generated proxy Java code looks somthing like:
 
4500
 
 
4501
<blockquote>
 
4502
<pre>
 
4503
public static void MyClass_method_upcall(MyClass self, long jarg1, Foo jarg1_object)
 
4504
{
 
4505
  Foo darg1 = (jarg1_object != null ? jarg1_object : new Foo(jarg1, false));
 
4506
 
 
4507
  self.method_upcall(darg1);
 
4508
}
 
4509
</pre>
 
4510
</blockquote>
 
4511
 
 
4512
  When you import a SWIG interface file containing class definitions, the classes you want to be director-enabled must be have the <code>feature("director")</code> enabled for type symmetry to work.
 
4513
  This applies even when the class being wrapped isn't a director-enabled class but takes parameters that are director-enabled classes.
 
4514
  </p>
 
4515
  <p>
 
4516
  The current "type symmetry" design will work for simple C++ inheritance, but will most likely fail for anything more compicated such as tree or diamond C++ inheritance hierarchies.
 
4517
  Those who are interested in challenging problems are more than welcome to hack the <code>Java::Java_director_declaration</code> method in <code>Source/Modules/java.cxx</code>.
 
4518
  </p>
 
4519
  <p>
 
4520
  If all else fails, you can use the downcastXXXXX() method to attempt to recover the director class's Java object pointer.
 
4521
  For the Java Foo proxy class, the Foo director class's java object pointer can be accessed through the javaObjectFoo() method.
 
4522
  The generated method's signature is:
 
4523
 
 
4524
<blockquote>
 
4525
<pre>
 
4526
  public static Foo javaObjectFoo(Foo obj);
 
4527
</pre>
 
4528
</blockquote>
 
4529
 
 
4530
  From your code, this method is invoked as follows:
 
4531
 
 
4532
<blockquote>
 
4533
<pre>
 
4534
public class MyClassDerived {
 
4535
  public void method_upcall(Foo foo_object)
 
4536
  {
 
4537
    FooDerived    derived = (foo_object != null ? (FooDerived) Foo.downcastFoo(foo_object) : null);
 
4538
    /* rest of your code here */
 
4539
  }
 
4540
}
 
4541
</pre>
 
4542
</blockquote>
 
4543
 
 
4544
  An good approach for managing downcasting is placing a static method in each derived class that performs the downcast from the superclass, e.g.,
 
4545
<blockquote>
 
4546
<pre>
 
4547
public class FooDerived extends Foo {
 
4548
  /* ... */
 
4549
  public static FooDerived downcastFooDerived(Foo foo_object)
 
4550
  {
 
4551
    try {
 
4552
     return (foo_object != null ? (FooDerived) Foo.downcastFoo(foo_object);
 
4553
    }
 
4554
 
 
4555
    catch (ClassCastException exc) {
 
4556
      // Wasn't a FooDerived object, some other sublcass of Foo
 
4557
      return null;
 
4558
    }
 
4559
  }
 
4560
}
 
4561
</pre>
 
4562
</blockquote>
 
4563
 
 
4564
  Then change the code in MyClassDerived as follows:
 
4565
 
 
4566
<blockquote>
 
4567
<pre>
 
4568
public class MyClassDerived extends MyClass {
 
4569
  /* ... */
 
4570
  public void method_upcall(Foo foo_object)
 
4571
  {
 
4572
    FooDerived    derived = FooDerived.downcastFooDerived(foo_object) : null);
 
4573
    /* rest of your code here */
 
4574
  }
 
4575
}
 
4576
</pre>
 
4577
</blockquote>
 
4578
 
 
4579
  <p>
 
4580
 
 
4581
  <li><i>Why isn't the proxy class declared abstract? Why aren't the director
 
4582
  upcall methods in the proxy class declared abstract?</i></li>
 
4583
  <p>
 
4584
  Declaring the proxy class and its methods abstract would break the JNI argument marshalling and SWIG's downcall functionality (going from Java to C++.)
 
4585
  Create an abstract Java subclass that inherits from the director-enabled class instead.
 
4586
  Using the previous Foo class example:
 
4587
 
 
4588
<blockquote>
 
4589
<pre>
 
4590
public abstract class UserVisibleFoo extends Foo {
 
4591
  /** Make sure user overrides this method, it's where the upcall
 
4592
   * happens.
 
4593
   */
 
4594
  public abstract void method_upcall(Foo foo_object);
 
4595
 
 
4596
  /// Downcast from Foo to UserVisibleFoo
 
4597
  public static UserVisibleFoo downcastUserVisibleFoo(Foo foo_object)
 
4598
  {
 
4599
    try {
 
4600
     return (foo_object != null ? (FooDerived) Foo.downcastFoo(foo_object) : null);
 
4601
    }
 
4602
 
 
4603
    catch (ClassCastException exc) {
 
4604
      // Wasn't a FooDerived object, some other sublcass of Foo
 
4605
      return null;
 
4606
    }
 
4607
  }
 
4608
}
 
4609
</pre>
 
4610
</blockquote>
 
4611
  This doesn't prevent the user from creating subclasses derived from Foo, however, UserVisibleFoo provides the safety net that reminds the user to override the <code>method_upcall()</code> method.
 
4612
  </p>
 
4613
</ol>
 
4614
 
 
4615
<a name="odds_ends"></a>
 
4616
<a name="n72"></a><H2>17.11 Odds and ends</H2>
 
4617
 
 
4618
 
 
4619
<a name="javadoc_comments"></a>
 
4620
<a name="n73"></a><H3>17.11.1 JavaDoc comments</H3>
 
4621
 
 
4622
 
 
4623
The SWIG documentation system is currently deprecated. 
 
4624
When it is resurrected JavaDoc comments will be fully supported. 
 
4625
If you can't wait for the full documentation system a couple of workarounds are available. 
 
4626
The <tt>%javamethodmodifiers</tt> feature can be used for adding proxy class method comments and module class method comments. 
 
4627
The "javaimports" typemap can be hijacked for adding in proxy class JavaDoc comments. 
 
4628
The <tt>jniclassimports</tt> or <tt>jniclassclassmodifiers</tt> pragmas can also be used for adding intermediary JNI class comments and likewise the <tt>moduleimports</tt> or <tt>moduleclassmodifiers</tt> pragmas for the module class. 
 
4629
Here is an example adding in a proxy class and method comment:
 
4630
 
 
4631
<blockquote>
 
4632
<pre>
 
4633
%javamethodmodifiers Barmy::lose_marbles() "
 
4634
  /**
 
4635
    * Calling this method will make you mad.
 
4636
    * Use with &lt;b&gt;utmost&lt;/b&gt; caution. 
 
4637
    */
 
4638
  public";
 
4639
 
 
4640
%typemap(javaimports) Barmy "
 
4641
/** The crazy class. Use as a last resort. */"
 
4642
 
 
4643
class Barmy {
 
4644
public:
 
4645
  void lose_marbles() {}
 
4646
};
 
4647
</pre>
 
4648
</blockquote>
 
4649
 
 
4650
Note the "public" added at the end of the <tt>%javamethodmodifiers</tt> as this is the default for this feature. 
 
4651
The generated proxy class with JavaDoc comments is then as follows:
 
4652
<blockquote>
 
4653
<pre>
 
4654
/** The crazy class. Use as a last resort. */
 
4655
public class Barmy {
 
4656
...
 
4657
  /**
 
4658
    * Calling this method will make you mad.
 
4659
    * Use with &lt;b&gt;utmost&lt;/b&gt; caution. 
 
4660
    */
 
4661
  public void lose_marbles() {
 
4662
    ...
 
4663
  }
 
4664
...
 
4665
}
 
4666
</pre>
 
4667
</blockquote>
 
4668
 
 
4669
 
 
4670
 
 
4671
<a name="functional_interface"></a>
 
4672
<a name="n74"></a><H3>17.11.2 Functional interface without proxy classes</H3>
 
4673
 
 
4674
 
 
4675
It is possible to run SWIG in a mode that does not produce proxy classes by using the -noproxy commandline option.
 
4676
The interface is rather primitive when wrapping structures or classes and is accessed through function calls to the module class.
 
4677
All the functions in the module class are wrapped by functions with identical names as those in the intermediary JNI class.
 
4678
<p>
 
4679
 
 
4680
Consider the example we looked at when examining proxy classes:
 
4681
<blockquote>
 
4682
<pre>
 
4683
class Foo {
 
4684
public:
 
4685
     int x;
 
4686
     int spam(int num, Foo* foo);
 
4687
};
 
4688
</pre>
 
4689
</blockquote>
 
4690
 
 
4691
When using <tt>-noproxy</tt>, type wrapper classes are generated instead of proxy classes.
 
4692
Access to all the functions and variables is through a C like set of functions where the first parameter passed is the pointer to the class, that is an instance of a type wrapper class.
 
4693
Here is what the module class looks like:
 
4694
 
 
4695
<blockquote>
 
4696
<pre>
 
4697
public class example {
 
4698
  public static void set_Foo_x(SWIGTYPE_p_Foo self, int x) {...}
 
4699
  public static int get_Foo_x(SWIGTYPE_p_Foo self) {...}
 
4700
  public static int Foo_spam(SWIGTYPE_p_Foo self, int num, SWIGTYPE_p_Foo foo) {...}
 
4701
  public static SWIGTYPE_p_Foo new_Foo() {...}
 
4702
  public static void delete_Foo(SWIGTYPE_p_Foo self) {...}
 
4703
}
 
4704
</pre>
 
4705
</blockquote>
 
4706
 
 
4707
This approach is not nearly as natural as using proxy classes as the functions need to be used like this:
 
4708
 
 
4709
<blockquote>
 
4710
<pre>
 
4711
SWIGTYPE_p_Foo foo = example.new_Foo();
 
4712
example.set_Foo_x(foo, 10);
 
4713
int var = example.get_Foo_x(foo);
 
4714
example.Foo_spam(foo, 20, foo);
 
4715
example.delete_Foo(foo);
 
4716
</pre>
 
4717
</blockquote>
 
4718
 
 
4719
Unlike proxy classes, there is no attempt at tracking memory.
 
4720
All destructors have to be called manually for example the <tt>delete_Foo(foo)</tt> call above.
 
4721
 
 
4722
 
 
4723
<a name="using_own_jni_functions"></a>
 
4724
<a name="n75"></a><H3>17.11.3 Using your own JNI functions</H3>
 
4725
 
 
4726
 
 
4727
You may have some hand written JNI functions that you want to use in addition to the SWIG generated JNI functions.
 
4728
Adding these to your SWIG generated package is possible using the <tt>%native</tt> directive.
 
4729
If you don't want SWIG to wrap your JNI function then of course you can simply use the <tt>%ignore</tt> directive.
 
4730
However, if you want SWIG to generate just the Java code for a JNI function then use the <tt>%native</tt> directive.
 
4731
The C types for the parameters and return type must be specified in place of the JNI types and the function name must be the native method name.
 
4732
For example:
 
4733
 
 
4734
<blockquote><pre>
 
4735
%native (HandRolled) void HandRolled(int, char *);
1918
4736
%{
1919
 
#include "MyClass.h"
 
4737
JNIEXPORT void JNICALL Java_packageName_moduleName_HandRolled(JNIEnv *, jclass, jlong, jstring);
1920
4738
%}
1921
 
%include "MyClass.h"
1922
 
 
1923
 
// Use a shadow pragma without modifying the original code in MyClass.h
1924
 
%addmethods MyClass{
1925
 
%pragma(java) shadowcode="/* Some extra shadow code for MyClass */"
1926
 
}
1927
 
</pre></blockquote>
1928
 
 
1929
 
 
1930
 
<a name="n10"></a><h2>Dynamic linking problems</h2>
1931
 
The code to load a native library is <code>System.loadLibrary("name")</code>. This can fail and it can be due to a number of reasons. 
1932
 
<br><br>
1933
 
The most common is an incorrect naming of the native library for the name passed to the <code>loadLibrary</code> function. The text passed to the <code>loadLibrary</code> function must not include the the extension name in the text, that is <i>.dll</i> or <i>.so</i>. The text must be <i>name</i> and not <i>libname</i> for all platforms. On Windows the native library must then be called <i>name.dll</i> and on Unix it must be called <i>libname.so</i>. If you are debugging using <code> java -debug</code>, then the native library must be called <i>name_g.dll</i> on Windows and <i>libname_g.so</i> on Unix.
1934
 
<br><br>
1935
 
Another common reason for the native library not loading is because it is not in your path. On Unix make sure that your <i>LD_LIBRARY_PATH</i> contains the path to the native library. On Windows make sure the <i>path</i> environment variable contains the path to the native library. SWIG code usually works if you have <i>LD_LIBRARY_PATH</i> set to '.' (or no modification to <i>path</i> in Windows).
1936
 
<br><br>
1937
 
The native library will also not load if there are any unresolved symbols in the compiled C/C++ code. Unresolved symbols will be described if you use the -verbose:jni commandline switch when running java.
1938
 
<br><br>
1939
 
Ensure that you are using the correct C/C++ compiler and linker combination and options for successful native library loading. The Examples/Makefile must have these set up correctly for your system. The SWIG installation package makes a best attempt at getting these correct but does not get it right 100% of the time.
1940
 
<br><br>
1941
 
Linking problems used to occur when there were underscores in the module name or package name. This was fixed in SWIG 1.3.7.
1942
 
 
1943
 
<a name="n11"></a><h2>Tips</h2>
1944
 
 
1945
 
<ul>
1946
 
The %native directive can be used to mix hand written JNI functions with the auto generated functions.
1947
 
</ul>
1948
 
 
1949
 
<a name="n12"></a><h2>Known bugs</h2>
1950
 
<ul>
1951
 
<li>Function pointers produce code that won't compile. Your own typemaps will overcome this.</li>
1952
 
</ul>
 
4739
</pre></blockquote>
 
4740
 
 
4741
No C JNI function will be generated and the <tt>Java_packageName_moduleName_HandRolled</tt> function will be accessible using the SWIG generated Java native method call in the intermediary JNI class which will look like this:
 
4742
 
 
4743
<blockquote><pre>
 
4744
  public final static native void HandRolled(int jarg1, String jarg2);
 
4745
</pre></blockquote>
 
4746
 
 
4747
and as usual this function is wrapped by another which for a global C function would appear in the module class:
 
4748
 
 
4749
<blockquote><pre>
 
4750
  public static void HandRolled(int arg0, String arg1) {
 
4751
    exampleJNI.HandRolled(arg0, arg1);
 
4752
  }
 
4753
</pre></blockquote>
 
4754
 
 
4755
The <tt>packageName</tt> and <tt>moduleName</tt> must of course be correct else you will get linker errors when the JVM dynamically loads the JNI function.
 
4756
You may have to add in some "jtype", "jstype", "javain" and "javaout" typemaps when wrapping some JNI types.
 
4757
Here the default typemaps work for for <tt>int</tt> and <tt>char *</tt>.
 
4758
<p>
 
4759
 
 
4760
In summary the <tt>%native</tt> directive is telling SWIG to generate the Java code to access the JNI C code, but not the JNI C function itself.
 
4761
This directive is only really useful if you want to mix your own hand crafted JNI code and the SWIG generated code into one Java class or package.
 
4762
 
 
4763
 
 
4764
<a name="performance"></a>
 
4765
<a name="n76"></a><H3>17.11.4 Performance concerns and hints</H3>
 
4766
 
 
4767
 
 
4768
If you're directly manipulating huge arrays of complex objects from Java, performance may suffer greatly when using the array functions in <tt>arrays_java.i</tt>.
 
4769
Try and minimise the expensive JNI calls to C/C++ functions, perhaps by using temporary Java variables instead of accessing the information directly from the C/C++ object.<p>
 
4770
 
 
4771
Java classes without any finalizers generally speed up code execution as there is less for the garbage collector to do. Finalizer generation can be stopped by using an empty <tt>javafinalize</tt> typemap: 
 
4772
 
 
4773
<blockquote><pre>
 
4774
%typemap(javafinalize) SWIGTYPE ""
 
4775
</pre></blockquote>
 
4776
 
 
4777
However, you will have to be careful about memory management and make sure that you code in a call to the <tt>delete()</tt> member function. 
 
4778
This method calls the C++ destructor or <tt>free()</tt> for C code.
 
4779
<p>
 
4780
 
 
4781
 
 
4782
<a name="java_examples"></a>
 
4783
<a name="n77"></a><H2>17.12 Examples</H2>
 
4784
 
 
4785
 
 
4786
The directory Examples/java has a number of further examples. 
 
4787
Take a look at these if you want to see some of the techniques described in action.
 
4788
The Examples/index.html file in the parent directory contains the SWIG Examples Documentation and is a useful starting point. 
 
4789
If your SWIG installation went well Unix users should be able to type <tt>make</tt> in each example directory, then <tt>java main</tt> to see them running.
 
4790
For the benefit of Windows users, there are also Visual C++ project files in a couple of the <a href="Windows.html#examples">Windows Examples</a>.
1953
4791
 
1954
4792
</body>
1955
 
</html>
 
4793
</html>
 
 
b'\\ No newline at end of file'