import source from 1.3.40
[external/swig.git] / Doc / Manual / Java.html
1 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
2 <html>
3 <head>
4 <title>SWIG and Java</title>
5 <link rel="stylesheet" type="text/css" href="style.css">
6 </head>
7 <body bgcolor="#FFFFFF">
8 <H1><a name="Java"></a>21 SWIG and Java</H1>
9 <!-- INDEX -->
10 <div class="sectiontoc">
11 <ul>
12 <li><a href="#java_overview">Overview</a>
13 <li><a href="#java_preliminaries">Preliminaries</a>
14 <ul>
15 <li><a href="#running_swig">Running SWIG</a>
16 <li><a href="#java_commandline">Additional Commandline Options</a>
17 <li><a href="#getting_right_headers">Getting the right header files</a>
18 <li><a href="#compiling_dynamic">Compiling a dynamic module</a>
19 <li><a href="#using_module">Using your module</a>
20 <li><a href="#dynamic_linking_problems">Dynamic linking problems</a>
21 <li><a href="#compilation_problems_cpp">Compilation problems and compiling with C++</a>
22 <li><a href="#building_windows">Building on Windows</a>
23 <ul>
24 <li><a href="#visual_studio">Running SWIG from Visual Studio</a>
25 <li><a href="#nmake">Using NMAKE</a>
26 </ul>
27 </ul>
28 <li><a href="#java_basic_tour">A tour of basic C/C++ wrapping</a>
29 <ul>
30 <li><a href="#module_packages_classes">Modules, packages and generated Java classes</a>
31 <li><a href="#functions">Functions</a>
32 <li><a href="#global_variables">Global variables</a>
33 <li><a href="#constants">Constants</a>
34 <li><a href="#enumerations">Enumerations</a>
35 <ul>
36 <li><a href="#anonymous_enums">Anonymous enums</a>
37 <li><a href="#typesafe_enums">Typesafe enums</a>
38 <li><a href="#proper_enums">Proper Java enums</a>
39 <li><a href="#typeunsafe_enums">Type unsafe enums</a>
40 <li><a href="#simple_enums">Simple enums</a>
41 </ul>
42 <li><a href="#pointers">Pointers</a>
43 <li><a href="#structures">Structures</a>
44 <li><a href="#classes">C++ classes</a>
45 <li><a href="#inheritance">C++ inheritance</a>
46 <li><a href="#pointers_refs_arrays">Pointers, references, arrays and pass by value</a>
47 <ul>
48 <li><a href="#null_pointers">Null pointers</a>
49 </ul>
50 <li><a href="#overloaded_functions">C++ overloaded functions</a>
51 <li><a href="#java_default_arguments">C++ default arguments</a>
52 <li><a href="#namespaces">C++ namespaces</a>
53 <li><a href="#templates">C++ templates</a>
54 <li><a href="#smart_pointers">C++ Smart Pointers</a>
55 </ul>
56 <li><a href="#further_details">Further details on the generated Java classes</a>
57 <ul>
58 <li><a href="#imclass">The intermediary JNI class</a>
59 <ul>
60 <li><a href="#imclass_pragmas">The intermediary JNI class pragmas</a>
61 </ul>
62 <li><a href="#java_module_class">The Java module class</a>
63 <ul>
64 <li><a href="#module_class_pragmas">The Java module class pragmas</a>
65 </ul>
66 <li><a href="#java_proxy_classes">Java proxy classes</a>
67 <ul>
68 <li><a href="#memory_management">Memory management</a>
69 <li><a href="#inheritance_mirroring">Inheritance</a>
70 <li><a href="#proxy_classes_gc">Proxy classes and garbage collection</a>
71 <li><a href="#java_pgcpp">The premature garbage collection prevention parameter for proxy class marshalling</a>
72 <li><a href="#java_multithread_libraries">Single threaded applications and thread safety</a>
73 </ul>
74 <li><a href="#type_wrapper_classes">Type wrapper classes</a>
75 <li><a href="#enum_classes">Enum classes</a>
76 <ul>
77 <li><a href="#typesafe_enums_classes">Typesafe enum classes</a>
78 <li><a href="#proper_enums_classes">Proper Java enum classes</a>
79 <li><a href="#typeunsafe_enums_classes">Type unsafe enum classes</a>
80 </ul>
81 </ul>
82 <li><a href="#java_directors">Cross language polymorphism using directors</a>
83 <ul>
84 <li><a href="#java_enabling_directors">Enabling directors</a>
85 <li><a href="#java_directors_classes">Director classes</a>
86 <li><a href="#java_directors_overhead">Overhead and code bloat</a>
87 <li><a href="#java_directors_example">Simple directors example</a>
88 <li><a href="#java_directors_threading">Director threading issues</a>
89 </ul>
90 <li><a href="#java_allprotected">Accessing protected members</a>
91 <li><a href="#common_customization">Common customization features</a>
92 <ul>
93 <li><a href="#helper_functions">C/C++ helper functions</a>
94 <li><a href="#class_extension">Class extension with %extend</a>
95 <li><a href="#exception_handling">Exception handling with %exception and %javaexception</a>
96 <li><a href="#method_access">Method access with %javamethodmodifiers</a>
97 </ul>
98 <li><a href="#tips_techniques">Tips and techniques</a>
99 <ul>
100 <li><a href="#input_output_parameters">Input and output parameters using primitive pointers and references</a>
101 <li><a href="#simple_pointers">Simple pointers</a>
102 <li><a href="#c_arrays">Wrapping C arrays with Java arrays</a>
103 <li><a href="#unbounded_c_arrays">Unbounded C Arrays</a>
104 <li><a href="#java_heap_allocations">Overriding new and delete to allocate from Java heap</a>
105 </ul>
106 <li><a href="#java_typemaps">Java typemaps</a>
107 <ul>
108 <li><a href="#default_primitive_type_mappings">Default primitive type mappings</a>
109 <li><a href="#Java_default_non_primitive_typemaps">Default typemaps for non-primitive types</a>
110 <li><a href="#jvm64">Sixty four bit JVMs</a>
111 <li><a href="#what_is_typemap">What is a typemap?</a>
112 <li><a href="#typemaps_c_to_java_types">Typemaps for mapping C/C++ types to Java types</a>
113 <li><a href="#typemap_attributes">Java typemap attributes</a>
114 <li><a href="#special_variables">Java special variables</a>
115 <li><a href="#typemaps_for_c_and_cpp">Typemaps for both C and C++ compilation</a>
116 <li><a href="#java_code_typemaps">Java code typemaps</a>
117 <li><a href="#java_directors_typemaps">Director specific typemaps</a>
118 </ul>
119 <li><a href="#typemap_examples">Typemap Examples</a>
120 <ul>
121 <li><a href="#simpler_enum_classes">Simpler Java enums for enums without initializers</a>
122 <li><a href="#exception_typemap">Handling C++ exception specifications as Java exceptions</a>
123 <li><a href="#nan_exception_typemap">NaN Exception - exception handling for a particular type</a>
124 <li><a href="#converting_java_string_arrays">Converting Java String arrays to char ** </a>
125 <li><a href="#expanding_java_object">Expanding a Java object to multiple arguments</a>
126 <li><a href="#using_typemaps_return_arguments">Using typemaps to return arguments</a>
127 <li><a href="#adding_downcasts">Adding Java downcasts to polymorphic return types</a>
128 <li><a href="#adding_equals_method">Adding an equals method to the Java classes</a>
129 <li><a href="#void_pointers">Void pointers and a common Java base class</a>
130 <li><a href="#struct_pointer_pointer">Struct pointer to pointer</a>
131 <li><a href="#java_memory_management_member_variables">Memory management when returning references to member variables</a>
132 <li><a href="#java_memory_management_objects">Memory management for objects passed to the C++ layer</a>
133 <li><a href="#java_date_marshalling">Date marshalling using the javain typemap and associated attributes</a>
134 </ul>
135 <li><a href="#java_directors_faq">Living with Java Directors</a>
136 <li><a href="#odds_ends">Odds and ends</a>
137 <ul>
138 <li><a href="#javadoc_comments">JavaDoc comments</a>
139 <li><a href="#functional_interface">Functional interface without proxy classes</a>
140 <li><a href="#using_own_jni_functions">Using your own JNI functions</a>
141 <li><a href="#performance">Performance concerns and hints</a>
142 <li><a href="#java_debugging">Debugging</a>
143 </ul>
144 <li><a href="#java_examples">Examples</a>
145 </ul>
146 </div>
147 <!-- INDEX -->
148
149
150
151 <p>
152 This chapter describes SWIG's support of Java. 
153 It covers most SWIG features, but certain low-level details are covered in less depth than in earlier chapters. 
154 </p>
155
156
157 <H2><a name="java_overview"></a>21.1 Overview</H2>
158
159
160 <p>
161 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 
162 want to take advantage of Java but are forced into using some native (C/C++) code.
163 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. 
164 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.
165 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.
166 If only one or two JNI functions are needed then using SWIG may be overkill.
167 SWIG enables a Java program to easily call into C/C++ code from Java.
168 Historically, SWIG was not able to generate any code to call into Java code from C++.
169 However, SWIG now supports full cross language polymorphism and code is generated to call up from C++ to Java when wrapping C++ virtual methods.
170 </p>
171
172 <p>
173 Java is one of the few non-scripting language modules in SWIG.
174 As SWIG utilizes the type safety that the Java language offers, it takes a somewhat different approach to that used for scripting languages.
175 In particular runtime type checking and the runtime library are not used by Java.
176 This should be borne in mind when reading the rest of the SWIG documentation.
177 This chapter on Java is relatively self contained and will provide you with nearly everything you need for using SWIG and Java.
178 However, the "<a href="SWIG.html#SWIG">SWIG Basics</a>" chapter will be a useful read in conjunction with this one.
179 </p>
180
181 <p>
182 This chapter starts with a few practicalities on running SWIG and compiling the generated code.
183 If you are looking for the minimum amount to read, have a look at the sections up to and including the
184 <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.
185 Following this section are details of the C/C++ code and Java classes that SWIG generates.
186 Due to the complexities of C and C++ there are different ways in which C/C++ code could be wrapped and called from Java.
187 SWIG is a powerful tool and the rest of the chapter details how the default code wrapping can be tailored.
188 Various customisation tips and techniques using SWIG directives are covered.
189 The latter sections cover the advanced techniques of using typemaps for complete control of the wrapping process.
190 </p>
191
192 <H2><a name="java_preliminaries"></a>21.2 Preliminaries</H2>
193
194
195 <p>
196 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.
197 Given the choice, you should probably use the latest version of Sun's JDK. 
198 The SWIG Java module is known to work using Sun's JVM on Solaris, Linux and the various flavours of Microsoft Windows including Cygwin. 
199 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. 
200 The generated code is also known to work on vxWorks using WindRiver's PJava 3.1. 
201 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. 
202 Run <tt>make -k check</tt> from the SWIG root directory after installing SWIG on Unix systems. </p>
203
204 <p>
205 The Java module requires your system to support shared libraries and dynamic loading. 
206 This is the commonly used method to load JNI code so your system will more than likely support this.</p>
207
208 <H3><a name="running_swig"></a>21.2.1 Running SWIG</H3>
209
210
211 <p>
212 Suppose that you defined a SWIG module such as the following:
213 </p>
214
215 <div class="code">
216 <pre>
217 /* File: example.i */
218 %module test
219 %{
220 #include "stuff.h"
221 %}
222 int fact(int n);
223 </pre>
224 </div>
225
226
227 <p>
228 To build a Java module, run SWIG using the <tt>-java</tt> option :</p>
229
230 <div class="code"><pre>
231 %swig -java example.i
232 </pre></div>
233
234 <p>
235 If building C++, add the <tt>-c++</tt> option:
236 </p>
237
238 <div class="code"><pre>
239 $ swig -c++ -java example.i
240 </pre></div>
241
242 <p>
243 This creates two different files; a C/C++ source file <tt>example_wrap.c</tt> or
244 <tt>example_wrap.cxx</tt> and numerous Java files.   The generated
245 C/C++ source file contains the JNI wrapper code that needs to be compiled and linked with the
246 rest of your C/C++ application. 
247 </p>
248
249 <p>
250 The name of the wrapper file is derived from the name of the input file.  For example, if the
251 input file is <tt>example.i</tt>, the name of the wrapper file is <tt>example_wrap.c</tt>.
252 To change this, you can use the <tt>-o</tt> option. 
253 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>.
254 </p>
255
256 <p>
257 The module name, specified with <tt>%module</tt>, determines the name of various generated classes as discussed <a href=#module_packages_classes>later</a>.
258 Note that the module name does not define a Java package and by default, the generated Java classes do not have a Java package.
259 The <tt>-package</tt> option described below can specify a Java package name to use.
260 </p>
261
262 <p>
263 The following sections have further practical examples and details on how you might go about
264 compiling and using the generated files.
265 </p>
266
267 <H3><a name="java_commandline"></a>21.2.2 Additional Commandline Options</H3>
268
269
270 <p>
271 The following table list the additional commandline options available for the Java module. They can also be seen by using: 
272 </p>
273
274 <div class="code"><pre>
275 swig -java -help 
276 </pre></div>
277
278 <table summary="Java specific options">
279 <tr>
280 <th>Java specific options</th>
281 </tr>
282
283 <tr>
284 <td>-nopgcpp</td>
285 <td>suppress the premature garbage collection prevention parameter</td>
286 </tr>
287
288 <tr>
289 <td>-noproxy</td>
290 <td>generate the low-level functional interface instead of proxy classes </td>
291 </tr>
292
293 <tr>
294 <td>-package &lt;name&gt;</td>
295 <td>set name of the Java package to &lt;name&gt;</td>
296 </tr>
297
298 </table>
299
300 <p>
301 Their use will become clearer by the time you have finished reading this section on SWIG and Java.
302 </p>
303
304 <H3><a name="getting_right_headers"></a>21.2.3 Getting the right header files</H3>
305
306
307 <p>
308 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. 
309 They are usually in directories like this:</p>
310
311 <div class="code"><pre>
312 /usr/java/include
313 /usr/java/include/&lt;operating_system&gt;
314 </pre></div>
315
316 <p>
317 The exact location may vary on your machine, but the above locations are typical. </p>
318
319 <H3><a name="compiling_dynamic"></a>21.2.4 Compiling a dynamic module</H3>
320
321
322 <p>
323 The JNI code exists in a dynamic module or shared library (DLL on Windows) and gets loaded by the JVM. 
324 To build a shared library file, you need to compile your module in a manner similar to the following (shown for Solaris):</p>
325
326 <div class="code"><pre>
327 $ swig -java example.i
328 $ gcc -c example_wrap.c  -I/usr/java/include -I/usr/java/include/solaris
329 $ ld -G example_wrap.o  -o libexample.so
330 </pre></div>
331
332 <p>
333 The exact commands for doing this vary from platform to platform. 
334 However, SWIG tries to guess the right options when it is installed.  Therefore, 
335 you may want to start with one of the examples in the <tt>Examples/java</tt> 
336 directory.   If that doesn't work, you will need to read the man-pages for
337 your compiler and linker to get the right set of options.  You might also
338 check the <a href="http://www.dabeaz.com/cgi-bin/wiki.pl">SWIG Wiki</a> for
339 additional information.
340 <a href="http://weblogs.java.net/blog/kellyohair/archive/2006/01/compilation_of.html">JNI compilation</a>
341 is a useful reference for compiling on different platforms.
342 </p>
343
344 <p>
345 <b>Important</b> <br>
346 If you are going to use optimisations turned on with gcc (for example -O2), ensure you also compile with -fno-strict-aliasing. The GCC optimisations have become 
347 more aggressive from gcc-4.0 onwards and will result in code that fails with strict aliasing optimisations turned on. See the <a href="#typemaps_c_to_java_types">C/C++ to Java typemaps</a> section for more details.
348 </p>
349
350 <p>
351 The name of the shared library output file is important. 
352 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). 
353 The name of the module is specified using the <tt>%module</tt> directive or<tt> -module</tt> command line option.</p>
354
355 <H3><a name="using_module"></a>21.2.5 Using your module</H3>
356
357
358 <p>
359 To load your shared native library module in Java, simply use Java's <tt>System.loadLibrary</tt> method in a Java class:</p>
360
361 <div class="code"><pre>
362 // runme.java
363
364 public class runme {
365   static {
366     System.loadLibrary("example");
367   }
368
369   public static void main(String argv[]) {
370     System.out.println(example.fact(4));
371   }
372 }
373 </pre></div>
374
375 <p>
376 Compile all the Java files and run:
377 </p>
378
379 <div class="code"><pre>
380 $ javac *.java
381 $ java runme
382 24
383 $
384 </pre></div>
385
386 <p>
387 If it doesn't work have a look at the following section which discusses problems loading the shared library.
388 </p>
389
390 <H3><a name="dynamic_linking_problems"></a>21.2.6 Dynamic linking problems</H3>
391
392
393 <p>
394 As shown in the previous section the code to load a native library (shared library) is <tt>System.loadLibrary("name")</tt>. 
395 This can fail with an UnsatisfiedLinkError exception and can be due to a number of reasons.
396 </p>
397
398 <p>
399 You may get an exception similar to this:
400 </p>
401
402 <div class="code"><pre>
403 $ java runme
404 Exception in thread "main" java.lang.UnsatisfiedLinkError: no example in java.library.path
405         at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1312)
406         at java.lang.Runtime.loadLibrary0(Runtime.java:749)
407         at java.lang.System.loadLibrary(System.java:820)
408         at runme.&lt;clinit&gt;(runme.java:5)
409 </pre></div>
410
411 <p>
412 The most common cause for this is an incorrect naming of the native library for the name passed to the <tt>loadLibrary</tt> function. 
413 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>. 
414 The string must be <i>name</i> and not <i>libname</i> for all platforms. 
415 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>. 
416 </p>
417
418 <p>
419 Another common reason for the native library not loading is because it is not in your path. 
420 On Windows make sure the <i>path</i> environment variable contains the path to the native library. 
421 On Unix make sure that your <i>LD_LIBRARY_PATH</i> contains the path to the native library. 
422 Adding paths to <i>LD_LIBRARY_PATH</i> can slow down other programs on your system so you may want to consider alternative approaches.
423 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).
424 You could use a command such as <tt>ldconfig</tt> (Linux) or
425 <tt>crle</tt> (Solaris) to add additional search paths to the default
426 system configuration (this requires root access and you will need to read the man pages).
427 </p>
428
429 <p>
430 The native library will also not load if there are any unresolved symbols in the compiled C/C++ code. 
431 The following exception is indicative of this:
432 </p>
433
434 <div class="code"><pre>
435 $ java runme
436 Exception in thread "main" java.lang.UnsatisfiedLinkError: libexample.so: undefined
437 symbol: fact
438         at java.lang.ClassLoader$NativeLibrary.load(Native Method)
439         at java.lang.ClassLoader.loadLibrary0(ClassLoader.java, Compiled Code)
440         at java.lang.ClassLoader.loadLibrary(ClassLoader.java, Compiled Code)
441         at java.lang.Runtime.loadLibrary0(Runtime.java, Compiled Code)
442         at java.lang.System.loadLibrary(System.java, Compiled Code)
443         at runme.&lt;clinit&gt;(runme.java:5)
444 $
445 </pre></div>
446
447 <p>
448 This error usually indicates that you forgot to include some object files or libraries in the linking of the native library file.  
449 Make sure you compile both the SWIG wrapper file and the code you are wrapping into the native library file.  
450 If you forget to compile and link in the SWIG wrapper file into your native library file, you will get a message similar to the following:
451 </p>
452
453 <div class="code"><pre>
454 $ java runme
455 Exception in thread "main" java.lang.UnsatisfiedLinkError: exampleJNI.gcd(II)I
456         at exampleJNI.gcd(Native Method)
457         at example.gcd(example.java:12)
458         at runme.main(runme.java:18)
459 </pre></div>
460
461 <p>
462 where <tt>gcd</tt> is the missing JNI function that SWIG generated into the wrapper file.
463 Also make sure you pass all of the required libraries to the linker.  
464 The <tt>java -verbose:jni</tt> commandline switch is also a great way to get more information on unresolved symbols.
465 One last piece of advice is to beware of the common faux pas of having more than one native library version in your path.
466 </p>
467
468 <p>
469 In summary, ensure that you are using the correct C/C++ compiler and linker combination and options for successful native library loading. 
470 If you are using the examples that ship with SWIG, then the Examples/Makefile must have these set up correctly for your system. 
471 The SWIG installation package makes a best attempt at getting these correct but does not get it right 100% of the time.
472 The <a href="http://www.dabeaz.com/cgi-bin/wiki.pl">SWIG Wiki</a> also has some settings for commonly used compiler and operating system combinations.
473 The following section also contains some C++ specific linking problems and solutions.
474 </p>
475
476
477 <H3><a name="compilation_problems_cpp"></a>21.2.7 Compilation problems and compiling with C++</H3>
478
479
480 <p>
481 On most machines, shared library files should be linked using the C++
482 compiler.  For example:
483 </p>
484
485 <div class="code"><pre>
486 % swig -c++ -java example.i
487 % g++ -c -fpic example.cxx
488 % g++ -c -fpic example_wrap.cxx -I/usr/java/j2sdk1.4.1/include -I/usr/java/
489 j2sdk1.4.1/include/linux
490 % g++ -shared example.o example_wrap.o -o libexample.so
491 </pre></div>
492
493 <p>
494 In addition to this, you may need to include additional library
495 files to make it work.  For example, if you are using the Sun C++ compiler on
496 Solaris, you often need to add an extra library <tt>-lCrun</tt> like this:
497 </p>
498
499 <div class="code"><pre>
500 % swig -c++ -java example.i
501 % CC -c example.cxx
502 % CC -c example_wrap.cxx -I/usr/java/include -I/usr/java/include/solaris
503 % CC -G example.o example_wrap.o -L/opt/SUNWspro/lib -o libexample.so -lCrun
504 </pre></div>
505
506 <p>
507 If you aren't entirely sure about the linking for C++, you
508 might look at an existing C++ program.  On many Unix machines, the
509 <tt>ldd</tt> command will list library dependencies.  This should give
510 you some clues about what you might have to include when you link your
511 shared library. For example:
512 </p>
513
514 <div class="code">
515 <pre>
516 $ ldd swig
517         libstdc++-libc6.1-1.so.2 =&gt; /usr/lib/libstdc++-libc6.1-1.so.2 (0x40019000)
518         libm.so.6 =&gt; /lib/libm.so.6 (0x4005b000)
519         libc.so.6 =&gt; /lib/libc.so.6 (0x40077000)
520         /lib/ld-linux.so.2 =&gt; /lib/ld-linux.so.2 (0x40000000)
521 $
522 </pre>
523 </div>
524
525 <p>
526 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.
527 </p>
528
529
530 <H3><a name="building_windows"></a>21.2.8 Building on Windows</H3>
531
532
533 <p>
534 Building on Windows is roughly similar to the process used with Unix.  
535 You will want to produce a DLL that can be loaded by the Java Virtual Machine.  
536 This section covers the process of using SWIG with Microsoft Visual C++ 6 although the procedure may be similar with other compilers.  
537 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>
538
539 <H4><a name="visual_studio"></a>21.2.8.1 Running SWIG from Visual Studio</H4>
540
541
542 <p>
543 If you are developing your application within Microsoft Visual studio, SWIG can be invoked as a custom build option. 
544 The Examples\java directory has a few <a href="Windows.html#Windows_examples">Windows Examples</a> containing Visual Studio project (.dsp) files.
545 The process to re-create the project files for a C project are roughly:</p>
546
547 <ul>
548 <li>Open up a new workspace and use the AppWizard to select a DLL project.
549 <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>).   
550 Don't worry if the wrapper file doesn't exist yet--Visual Studio will keep a reference to it.
551 <li>Select the SWIG interface file and go to the settings menu. Under settings, select the "Custom Build" option.
552 <li>Enter "SWIG" in the description field.
553 <li>Enter "<tt>swig -java -o $(ProjDir)\$(InputName)_wrap.c $(InputPath)</tt>" in the "Build command(s) field"
554 <li>Enter "<tt>$(ProjDir)\$(InputName)_wrap.c</tt>" in the "Output files(s) field".
555 <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".
556 <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).
557 <li>Next, select the example.c and example_wrap.c files and go to the C/C++ tab and select the Precompiled Headers tab in the project settings. Disabling precompiled headers for these files will overcome any precompiled header errors while building.
558 <li>Finally, add the java compilation as a post build rule in the Post-build step tab in project settings, eg, "c:\jdk1.3\bin\javac *.java" 
559 <li>Build your project.
560 </ul>
561
562 <p>
563 Note: If using C++, choose a C++ suffix for the wrapper file, for example <tt>example_wrap.cxx</tt>.
564 Use <tt>_wrap.cxx</tt> instead of <tt>_wrap.c</tt> in the instructions above and add -c++ when invoking swig.
565 </p>
566
567 <p>
568 Now, assuming all went well, SWIG will be automatically invoked when you build your project.  
569 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.
570 </p>
571
572 <p>
573 The Java classes that SWIG output should also be compiled into .class files. 
574 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. 
575 If the library fails to load have a look at <a href="#dynamic_linking_problems">Dynamic linking problems</a>.
576 </p>
577
578 <H4><a name="nmake"></a>21.2.8.2 Using NMAKE</H4>
579
580
581 <p>
582 Alternatively, a Makefile for use by NMAKE can be written.   
583 Make sure the environment variables for MSVC++ are available and the MSVC++ tools are in your path.   
584 Now, just write a short Makefile like this :</p>
585
586 <div class="code"><pre>
587 # Makefile for using SWIG and Java for C code
588
589 SRCS          = example.c
590 IFILE         = example
591 INTERFACE     = $(IFILE).i
592 WRAPFILE      = $(IFILE)_wrap.c
593
594 # Location of the Visual C++ tools (32 bit assumed)
595
596 TOOLS         = c:\msdev
597 TARGET        = example.dll
598 CC            = $(TOOLS)\bin\cl.exe
599 LINK          = $(TOOLS)\bin\link.exe
600 INCLUDE32     = -I$(TOOLS)\include
601 MACHINE       = IX86
602
603 # C Library needed to build a DLL
604
605 DLLIBC        = msvcrt.lib oldnames.lib  
606
607 # Windows libraries that are apparently needed
608 WINLIB        = kernel32.lib advapi32.lib user32.lib gdi32.lib comdlg32.lib winspool.lib
609
610 # Libraries common to all DLLs
611 LIBS          = $(DLLIBC) $(WINLIB) 
612
613 # Linker options
614 LOPT      = -debug:full -debugtype:cv /NODEFAULTLIB /RELEASE /NOLOGO \
615              /MACHINE:$(MACHINE) -entry:_DllMainCRTStartup@12 -dll
616
617 # C compiler flags
618
619 CFLAGS        = /Z7 /Od /c /nologo
620 JAVA_INCLUDE    = -ID:\jdk1.3\include -ID:\jdk1.3\include\win32
621
622 java::
623         swig -java -o $(WRAPFILE) $(INTERFACE)
624         $(CC) $(CFLAGS) $(JAVA_INCLUDE) $(SRCS) $(WRAPFILE)
625         set LIB=$(TOOLS)\lib
626         $(LINK) $(LOPT) -out:example.dll $(LIBS) example.obj example_wrap.obj
627         javac *.java
628 </pre></div>
629
630 <p>
631 To build the DLL and compile the java code, run NMAKE (you may need to run <tt>vcvars32</tt> first). 
632 This is a pretty simplistic Makefile, but hopefully its enough to get you started.
633 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.
634 </p>
635
636
637 <H2><a name="java_basic_tour"></a>21.3 A tour of basic C/C++ wrapping</H2>
638
639
640 <p>
641 By default, SWIG attempts to build a natural Java interface
642 to your C/C++ code.  Functions are wrapped as functions, classes are wrapped as classes, 
643 variables are wrapped with JavaBean type getters and setters and so forth.
644 This section briefly covers the essential aspects of this wrapping.
645 </p>
646
647 <H3><a name="module_packages_classes"></a>21.3.1 Modules, packages and generated Java classes</H3>
648
649
650 <p>
651 The SWIG <tt>%module</tt> directive specifies the name of the Java
652 module. When you specify `<tt>%module example</tt>', the <i>module name</i>
653 determines the name of some of the generated files in the module.
654 The generated code consists of a <i>module class</i> file <tt>example.java</tt>, an
655 <i>intermediary JNI class</i> file, <tt>exampleJNI.java</tt> as well as numerous other Java <i>proxy class</i> files.
656 Each proxy class is named after the structs, unions and classes you are wrapping.
657 You may also get a <i>constants interface</i> file if you are wrapping any unnamed enumerations or constants, for example <tt>exampleConstants.java</tt>.
658 When choosing a module name, make sure you don't use the same name as one of the generated
659 proxy class files nor a Java keyword. Sometimes a C/C++ type cannot be wrapped by a proxy class, for 
660 example a pointer to a primitive type. In these situations a <i>type wrapper class</i> is generated.
661 Wrapping an enum generates an <i>enum class</i>, either a proper Java enum or a Java class that simulates the enums pattern.
662 Details of all these generated classes will unfold as you read this section.
663 </p>
664
665 <p>
666 The JNI (C/C++) code is generated into a file which also contains the module name, for example <tt>example_wrap.cxx</tt>
667 or <tt>example_wrap.c</tt>. These C or C++ files complete the contents of the module.
668 </p>
669
670 <p>
671 The generated Java classes can be placed into a Java package by using the <tt>-package</tt> commandline option.
672 This is often combined with the <tt>-outdir</tt> to specify a package directory for generating the Java files.
673 </p>
674
675 <div class="code"><pre>
676 swig -java -package com.bloggs.swig -outdir com/bloggs/swig example.i
677 </pre></div>
678
679 SWIG won't create the directory, so make sure it exists beforehand.
680
681 <H3><a name="functions"></a>21.3.2 Functions</H3>
682
683
684 <p>
685 There is no such thing as a global Java function so global C functions are wrapped as static methods in 
686 the module class. For example,
687 </p>
688
689 <div class="code"><pre>
690 %module example
691 int fact(int n);
692
693 </pre></div>
694
695 <p>
696 creates a static function that works exactly like you think it might:</p>
697
698 <div class="code"><pre>
699 public class example {
700   public static int fact(int n) {
701     // makes call using JNI to the C function
702   }
703 }
704 </pre></div>
705
706
707 <p>
708 The Java class <tt>example</tt> is the <i>module class</i>. The function can be used as follows from Java:</p>
709
710 <div class="code"><pre>
711 System.out.println(example.fact(4));
712 </pre></div>
713
714
715 <H3><a name="global_variables"></a>21.3.3 Global variables</H3>
716
717
718 <p>
719 C/C++ global variables are fully supported by SWIG.  
720 Java does not allow the overriding of the dot operator so all variables are accessed through getters and setters. 
721 Again because there is no such thing as a
722 Java global variable, access to C/C++ global variables is done through static getter and setter functions in the module class.
723 </p>
724
725 <div class="code"><pre>
726 // SWIG interface file with global variables
727 %module example
728 ...
729 %inline %{
730 extern int My_variable;
731 extern double density;
732 %}
733 ...
734 </pre></div>
735
736 <p>
737 Now in Java :</p>
738
739 <div class="code"><pre>
740 // Print out value of a C global variable
741 System.out.println("My_variable = " + example.getMy_variable());
742 // Set the value of a C global variable
743 example.setDensity(0.8442);
744 </pre></div>
745
746 <p>
747 The value returned by the getter will always be up to date even if the value is changed in C. 
748 Note that the getters and setters produced follow the JavaBean property design pattern. 
749 That is the first letter of the variable name is capitalized and preceded with set or get.
750 If you have the misfortune of wrapping two variables that differ only in the capitalization of their first letters,
751 use %rename to change one of the variable names. For example:
752 </p>
753
754 <div class="code"><pre>
755 %rename Clash RenamedClash;
756 float Clash;
757 int clash;
758 </pre></div>
759
760 <p>
761 If a variable is declared as <tt>const</tt>, it is wrapped as a read-only variable.  
762 That is only a getter is produced.
763 </p>
764
765 <p>
766 To make ordinary variables read-only, you can use the <tt>%immutable</tt> directive. For example:
767 </p>
768
769 <div class="code">
770 <pre>
771 %{
772 extern char *path;
773 %}
774 %immutable;
775 extern char *path;
776 %mutable;
777 </pre>
778 </div>
779
780 <p>
781 The <tt>%immutable</tt> directive stays in effect until it is explicitly disabled or cleared using
782 <tt>%mutable</tt>.
783 See the <a href="SWIG.html#SWIG_readonly_variables">Creating read-only variables</a> section for further details.
784 </p>
785
786 <p>
787 If you just want to make a specific variable immutable, supply a declaration name.  For example:
788 </p>
789
790 <div class="code">
791 <pre>
792 %{
793 extern char *path;
794 %}
795 %immutable path;
796 ...
797 extern char *path;      // Read-only (due to %immutable)
798 </pre>
799 </div>
800
801
802 <H3><a name="constants"></a>21.3.4 Constants</H3>
803
804
805 <p>
806 C/C++ constants are wrapped as Java static final variables.
807 To create a constant, use <tt>#define</tt> or the
808 <tt>%constant</tt> directive.  For example:
809 </p>
810
811 <div class="code">
812 <pre>
813 #define PI 3.14159
814 #define VERSION "1.0"
815 %constant int FOO = 42;
816 %constant const char *path = "/usr/local";
817 </pre>
818 </div>
819
820 <p>
821 By default the generated static final variables are initialized by making a JNI call to get their value.
822 The constants are generated into the constants interface and look like this:
823 </p>
824
825 <div class="code"><pre>
826 public interface exampleConstants {
827   public final static double PI = exampleJNI.PI_get();
828   public final static String VERSION = exampleJNI.VERSION_get();
829   public final static int FOO = exampleJNI.FOO_get();
830   public final static String path = exampleJNI.path_get();
831 }
832 </pre></div>
833
834 <p>
835 Note that SWIG has inferred the C type and used an appropriate Java type that will fit the range of all possible values for the C type.
836 By default SWIG generates <b>runtime constants</b>. They are not <b>compiler constants</b> that can, for example, be used 
837 in a switch statement. This can be changed by using the <tt>%javaconst(flag)</tt> directive. It works like all
838 the other <a href="Customization.html#features">%feature directives</a>. The default is <tt>%javaconst(0)</tt>. 
839 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.
840 Putting it at the top of your interface file would ensure this.
841 Here is an example:
842 </p>
843
844 <div class="code"><pre>
845 %javaconst(1);
846 %javaconst(0) BIG;
847 %javaconst(0) LARGE;
848
849 #define EXPRESSION (0x100+5)
850 #define BIG 1000LL
851 #define LARGE 2000ULL
852 </pre></div>
853
854 <p>
855 generates:
856 </p>
857
858 <div class="code"><pre>
859 public interface exampleConstants {
860   public final static int EXPRESSION = (0x100+5);
861   public final static long BIG = exampleJNI.BIG_get();
862   public final static java.math.BigInteger LARGE = exampleJNI.LARGE_get();
863 }
864 </pre></div>
865
866 <p>
867 Note that SWIG has inferred the C <tt>long long</tt> type from <tt>BIG</tt> and used an appropriate Java type (<tt>long</tt>) as
868 a Java <tt>long</tt> is the smallest sized Java type that will take all possible values for a C <tt>long long</tt>.
869 Similarly for <tt>LARGE</tt>.
870 </p>
871
872 <p>
873 Be careful using the <tt>%javaconst(1)</tt> directive as not all C code will compile as Java code. For example neither the 
874 <tt>1000LL</tt> value for <tt>BIG</tt> nor <tt>2000ULL</tt> for <tt>LARGE</tt> above would generate valid Java code. 
875 The example demonstrates how you can target particular constants (<tt>BIG</tt> and <tt>LARGE</tt>) with <tt>%javaconst</tt>.
876 SWIG doesn't use <tt>%javaconst(1)</tt> as the default as it tries to generate code that will always compile.
877 However, using a <tt>%javaconst(1)</tt> at the top of your interface file is strongly recommended as the preferred compile time constants
878 will be generated and most C constants will compile as Java code and in any case the odd constant that doesn't can be fixed using <tt>%javaconst(0)</tt>.
879 </p>
880
881 <p>
882 There is an alternative directive which can be used for these rare constant values that won't compile as Java code.
883 This is the <tt>%javaconstvalue(value)</tt> directive, where <tt>value</tt> is a Java code replacement for the C constant and can be either a string or a number.
884 This is useful if you do not want to use either the parsed C value nor a JNI call,
885 such as when the C parsed value will not compile as Java code and a compile time constant is required.
886 The same example demonstrates this:
887 </p>
888
889 <div class="code"><pre>
890 %javaconst(1);
891 %javaconstvalue("new java.math.BigInteger(\"2000\")") LARGE;
892 %javaconstvalue(1000) BIG;
893
894 #define EXPRESSION (0x100+5)
895 #define BIG 1000LL
896 #define LARGE 2000ULL
897 </pre></div>
898
899 <p>
900 Note the string quotes for <tt>"2000"</tt> are escaped. The following is then generated:
901 </p>
902
903 <div class="code"><pre>
904 public interface exampleConstants {
905   public final static int EXPRESSION = (0x100+5);
906   public final static long BIG = 1000;
907   public final static java.math.BigInteger LARGE = new java.math.BigInteger("2000");
908 }
909 </pre></div>
910
911 <p>
912 Note:  declarations declared as <tt>const</tt> are wrapped as read-only variables and
913 will be accessed using a getter as described in the previous section.  They
914 are not wrapped as constants.
915 The exception to this rule are static const integral values defined within a class/struct, where they are wrapped as constants, eg:.
916 </p>
917
918 <div class="code"><pre>
919 struct Maths {
920   static const int FIVE = 5;
921 };
922 </pre></div>
923
924
925 <p>
926 <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.
927 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):
928 </p>
929
930 <div class="code"><pre>
931 public class example implements exampleConstants {
932 }
933 </pre></div>
934
935 <p>
936 You thus have the choice of accessing these constants from either the module class or the constants interface, for example,
937 <tt>example.EXPRESSION</tt> or <tt>exampleConstants.EXPRESSION</tt>.
938 Or if you decide this practice isn't so bad and your own class implements <tt>exampleConstants</tt>, you can of course just use <tt>EXPRESSION</tt>.
939 </p>
940
941
942 <H3><a name="enumerations"></a>21.3.5 Enumerations</H3>
943
944
945 <p>
946 SWIG handles both named and unnamed (anonymous) enumerations.
947 There is a choice of approaches to wrapping named C/C++ enums.
948 This is due to historical reasons as SWIG's initial support for enums was limited and Java did not originally have support for enums.
949 Each approach has advantages and disadvantages and it is important for the user to decide which is the most appropriate solution.
950 There are four approaches of which the first is the default approach based on the so called Java typesafe enum pattern.
951 The second generates proper Java enums.
952 The final two approaches use simple integers for each enum item.
953 Before looking at the various approaches for wrapping named C/C++ enums, anonymous enums are considered.
954 </p>
955
956 <H4><a name="anonymous_enums"></a>21.3.5.1 Anonymous enums</H4>
957
958
959 <p>
960 There is no name for anonymous enums and so they are handled like constants. For example:
961 </p>
962
963 <div class="code">
964 <pre>
965 enum { ALE, LAGER=10, STOUT, PILSNER, PILZ=PILSNER };
966 </pre>
967 </div>
968
969 <p>
970 is wrapped into the constants interface, in a similar manner as constants (see previous section):
971 </p>
972
973 <div class="code"><pre>
974 public interface exampleConstants {
975   public final static int ALE = exampleJNI.ALE_get();
976   public final static int LAGER = exampleJNI.LAGER_get();
977   public final static int STOUT = exampleJNI.STOUT_get();
978   public final static int PILSNER = exampleJNI.PILSNER_get();
979   public final static int PILZ = exampleJNI.PILZ_get();
980 }
981 </pre></div>
982
983 <p>
984 The <tt>%javaconst(flag)</tt> and <tt>%javaconstvalue(value)</tt> directive introduced in the previous section on constants can also be used with enums.
985 As is the case for constants, the default is <tt>%javaconst(0)</tt> as not all C values will compile as Java code.
986 However, it is strongly recommended to add in a <tt>%javaconst(1)</tt> directive at the top of your 
987 interface file as it is only on very rare occasions that this will produce code that won't compile under Java.
988 Using <tt>%javaconst(1)</tt> will ensure compile time constants are generated, thereby allowing the enum values to be used in Java switch statements. 
989 Example usage:
990 </p>
991
992 <div class="code">
993 <pre>
994 %javaconst(1);
995 %javaconst(0) PILSNER;
996 enum { ALE, LAGER=10, STOUT, PILSNER, PILZ=PILSNER };
997 </pre>
998 </div>
999
1000 <p>
1001 generates:
1002 </p>
1003
1004 <div class="code"><pre>
1005 public interface exampleConstants {
1006   public final static int ALE = 0;
1007   public final static int LAGER = 10;
1008   public final static int STOUT = LAGER + 1;
1009   public final static int PILSNER = exampleJNI.PILSNER_get();
1010   public final static int PILZ = PILSNER;
1011 }
1012 </pre></div>
1013
1014 <p>
1015 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>.
1016 </p>
1017
1018
1019 <H4><a name="typesafe_enums"></a>21.3.5.2 Typesafe enums</H4>
1020
1021
1022 <p>
1023 This is the default approach to wrapping named enums.
1024 The typesafe enum pattern is a relatively well known construct to work around the lack of enums in versions of Java prior to JDK 1.5.
1025 It basically defines a class for the enumeration and permits a limited number of final static instances of the class.
1026 Each instance equates to an enum item within the enumeration.
1027 The implementation is in the "enumtypesafe.swg" file.
1028 Let's look at an example:
1029 </p>
1030
1031 <div class="code">
1032 <pre>
1033 %include "enumtypesafe.swg" // optional as typesafe enums are the default
1034 enum Beverage { ALE, LAGER=10, STOUT, PILSNER, PILZ=PILSNER };
1035 </pre>
1036 </div>
1037
1038 <p>will generate:</p>
1039
1040 <div class="code">
1041 <pre>
1042 public final class Beverage {
1043   public final static Beverage ALE = new Beverage("ALE");
1044   public final static Beverage LAGER = new Beverage("LAGER", exampleJNI.LAGER_get());
1045   public final static Beverage STOUT = new Beverage("STOUT");
1046   public final static Beverage PILSNER = new Beverage("PILSNER");
1047   public final static Beverage PILZ = new Beverage("PILZ", exampleJNI.PILZ_get());
1048   [... additional support methods omitted for brevity ...]
1049 }
1050 </pre>
1051 </div>
1052
1053 <p>
1054 See <a href="#typesafe_enums_classes">Typesafe enum classes</a> to see the omitted support methods.
1055 Note that the enum item with an initializer (LAGER) is initialized with the enum value obtained via a JNI call.
1056 However, as with anonymous enums and constants, use of the <tt>%javaconst</tt> directive is strongly recommended to change this behaviour:
1057 </p>
1058
1059 <div class="code">
1060 <pre>
1061 %include "enumtypesafe.swg" // optional as typesafe enums are the default
1062 %javaconst(1);
1063 enum Beverage { ALE, LAGER=10, STOUT, PILSNER, PILZ=PILSNER };
1064 </pre>
1065 </div>
1066
1067 <p>
1068 will generate:
1069 </p>
1070
1071 <div class="code">
1072 <pre>
1073 public final class Beverage {
1074   public final static Beverage ALE = new Beverage("ALE");
1075   public final static Beverage LAGER = new Beverage("LAGER", 10);
1076   public final static Beverage STOUT = new Beverage("STOUT");
1077   public final static Beverage PILSNER = new Beverage("PILSNER");
1078   public final static Beverage PILZ = new Beverage("PILZ", PILSNER);
1079   [... additional support methods omitted for brevity ...]
1080 }
1081 </pre>
1082 </div>
1083
1084 <p>
1085 The generated code is easier to read and more efficient as a true constant is used instead of a JNI call.
1086 As is the case for constants, the default is <tt>%javaconst(0)</tt> as not all C values will compile as Java code.
1087 However, it is recommended to add in a <tt>%javaconst(1)</tt> directive at the top of your 
1088 interface file as it is only on very rare occasions that this will produce code that won't compile under Java.
1089 The <tt>%javaconstvalue(value)</tt> directive can also be used for typesafe enums.
1090 Note that global enums are generated into a Java class within whatever package you are using.
1091 C++ enums defined within a C++ class are generated into a static final inner Java class within the Java proxy class.
1092 </p>
1093
1094 <p>
1095 Typesafe enums have their advantages over using plain integers in that they they can be used in a typesafe manner.
1096 However, there are limitations. For example, they cannot be used in switch statements and serialization is an issue.
1097 Please look at the following references for further information: 
1098
1099 <a href="http://java.sun.com/developer/Books/shiftintojava/page1.html#replaceenums">Replace Enums with Classes</a> in <i>Effective Java Programming</i> on the Sun website,
1100 <a href="http://www.javaworld.com/javaworld/jw-07-1997/jw-07-enumerated.html">Create enumerated constants in Java</a> JavaWorld article,
1101 <a href="http://www.javaworld.com/javaworld/javatips/jw-javatip133.html">Java Tip 133: More on typesafe enums</a> and
1102 <a href="http://www.javaworld.com/javaworld/javatips/jw-javatip122.html">Java Tip 122: Beware of Java typesafe enumerations</a> JavaWorld tips.
1103 </p>
1104
1105 <p>
1106 Note that the syntax required for using typesafe enums is the same as that for proper Java enums.
1107 This is useful during the period that a project has to support legacy versions of Java.
1108 When upgrading to JDK 1.5 or later, proper Java enums could be used instead, without users having to change their code.
1109 The following section details proper Java enum generation.
1110 </p>
1111
1112 <H4><a name="proper_enums"></a>21.3.5.3 Proper Java enums</H4>
1113
1114
1115 <p>
1116 Proper Java enums were only introduced in JDK 1.5 so this approach is only compatible with more recent versions of Java.
1117 Java enums have been designed to overcome all the limitations of both typesafe and type unsafe enums
1118 and should be the choice solution, provided older versions of Java do not have to be supported.
1119 In this approach, each named C/C++ enum is wrapped by a Java enum.
1120 Java enums, by default, do not support enums with initializers.
1121 Java enums are in many respects similar to Java classes in that they can be customised with additional methods.
1122 SWIG takes advantage of this feature to facilitate wrapping C/C++ enums that have initializers.
1123 In order to wrap all possible C/C++ enums using proper Java enums, the "enums.swg" file must be used.
1124 Let's take a look at an example.
1125 </p>
1126
1127 <div class="code">
1128 <pre>
1129 %include "enums.swg"
1130 %javaconst(1);
1131 enum Beverage { ALE, LAGER=10, STOUT, PILSNER, PILZ=PILSNER };
1132 </pre>
1133 </div>
1134
1135 <p>
1136 will generate:
1137 </p>
1138
1139 <div class="code">
1140 <pre>
1141 public enum Beverage {
1142   ALE,
1143   LAGER(10),
1144   STOUT,
1145   PILSNER,
1146   PILZ(PILSNER);
1147   [... additional support methods omitted for brevity ...]
1148 }
1149 </pre>
1150 </div>
1151
1152 <p>
1153 See <a href="#proper_enums_classes">Proper Java enum classes</a> to see the omitted support methods.
1154 The generated Java enum has numerous additional methods to support enums with initializers, such as <tt>LAGER</tt> above.
1155 Note that as with the typesafe enum pattern, enum items with initializers are by default initialized with the enum value obtained via a JNI call.
1156 However, this is not the case above as we have used the recommended <tt>%javaconst(1)</tt> to avoid the JNI call.
1157 The <tt>%javaconstvalue(value)</tt> directive covered in the <a href="#constants">Constants</a> section can also be used for proper Java enums.
1158 </p>
1159
1160 <p>
1161 The additional support methods need not be generated if none of the enum items have initializers and this is covered later in the 
1162 <a href="#simpler_enum_classes">Simpler Java enums for enums without initializers</a> section.
1163 </p>
1164
1165 <H4><a name="typeunsafe_enums"></a>21.3.5.4 Type unsafe enums</H4>
1166
1167
1168 <p>
1169 In this approach each enum item in a named enumeration is wrapped as a static final integer in a class named after the C/C++ enum name.
1170 This is a commonly used pattern in Java to simulate C/C++ enums, but it is not typesafe.
1171 However, the main advantage over the typesafe enum pattern is enum items can be used in switch statements.
1172 In order to use this approach, the "enumtypeunsafe.swg" file must be used.
1173 Let's take a look at an example.
1174 </p>
1175
1176 <div class="code">
1177 <pre>
1178 %include "enumtypeunsafe.swg"
1179 %javaconst(1);
1180 enum Beverage { ALE, LAGER=10, STOUT, PILSNER, PILZ=PILSNER };
1181 </pre>
1182 </div>
1183
1184 <p>
1185 will generate:
1186 </p>
1187
1188 <div class="code">
1189 <pre>
1190 public final class Beverage {
1191   public final static int ALE = 0;
1192   public final static int LAGER = 10;
1193   public final static int STOUT = LAGER + 1;
1194   public final static int PILSNER = STOUT + 1;
1195   public final static int PILZ = PILSNER;
1196 }
1197 </pre>
1198 </div>
1199
1200 <p>
1201 As is the case previously, the default is <tt>%javaconst(0)</tt> as not all C/C++ values will compile as Java code.
1202 However, again it is recommended to add in a <tt>%javaconst(1)</tt> directive.
1203 and the <tt>%javaconstvalue(value)</tt> directive covered in the <a href="#constants">Constants</a> section can also be used for type unsafe enums.
1204 Note that global enums are generated into a Java class within whatever package you are using.
1205 C++ enums defined within a C++ class are generated into a static final inner Java class within the Java proxy class.
1206 </p>
1207
1208 <p>
1209 Note that unlike typesafe enums, this approach requires users to mostly use different syntax compared with proper Java enums.
1210 Thus the upgrade path to proper enums provided in JDK 1.5 is more painful.
1211 </p>
1212
1213 <H4><a name="simple_enums"></a>21.3.5.5 Simple enums</H4>
1214
1215
1216 <p>
1217 This approach is similar to the type unsafe approach.
1218 Each enum item is also wrapped as a static final integer.
1219 However, these integers are not generated into a class named after the C/C++ enum.
1220 Instead, global enums are generated into the constants interface.
1221 Also, enums defined in a C++ class have their enum items generated directly into the Java proxy class rather than an inner class within the Java proxy class.
1222 In fact, this approach is effectively wrapping the enums as if they were anonymous enums and the resulting code is as per <a href="#anonymous_enums">anonymous enums</a>.
1223 The implementation is in the "enumsimple.swg" file.
1224 </p>
1225
1226 <p>
1227 <b>Compatibility Note:</b>
1228 SWIG-1.3.21 and earlier versions wrapped all enums using this approach.
1229 The type unsafe approach is preferable to this one and this simple approach is only included for backwards compatibility with these earlier versions of SWIG.
1230 </p>
1231
1232 <H3><a name="pointers"></a>21.3.6 Pointers</H3>
1233
1234
1235 <p>
1236 C/C++ pointers are fully supported by SWIG.  Furthermore, SWIG has no problem working with
1237 incomplete type information.  Here is a rather simple interface:
1238 </p>
1239
1240 <div class="code">
1241 <pre>
1242 %module example
1243
1244 FILE *fopen(const char *filename, const char *mode);
1245 int fputs(const char *, FILE *);
1246 int fclose(FILE *);
1247 </pre>
1248 </div>
1249
1250 <p>
1251 When wrapped, you will be able to use the functions in a natural way from Java. For example:
1252 </p>
1253
1254 <div class="code">
1255 <pre>
1256 SWIGTYPE_p_FILE f = example.fopen("junk","w");
1257 example.fputs("Hello World\n", f);
1258 example.fclose(f);
1259 </pre>
1260 </div>
1261
1262 <p>
1263 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.
1264 Many other SWIG language modules use an encoding of the pointer in a string. 
1265 These scripting languages use the SWIG runtime type checker for dynamic type checking as they do not support static type checking by a compiler.
1266 In order to implement static type checking of pointers within Java, they are wrapped by a simple Java class. 
1267 In the example above the <tt>FILE *</tt> pointer is wrapped with a <i>type wrapper class </i> 
1268 called <tt>SWIGTYPE_p_FILE</tt>.
1269 </p>
1270
1271 <p>
1272 Once obtained, a type wrapper object can be freely passed around to different C functions that
1273 expect to receive an object of that type.  The only thing you can't do is 
1274 dereference the pointer from Java. Of course, that isn't much of a concern in this example.
1275 </p>
1276
1277 <p>
1278 As much as you might be inclined to modify a pointer value directly
1279 from Java, don't.  The value is not necessarily the
1280 same as the logical memory address of the underlying object.  The value will
1281 vary depending on the native byte-ordering of the platform (i.e.,
1282 big-endian vs. little-endian).  
1283 Most JVMs are 32 bit applications so any JNI code must also be compiled as 32 bit. 
1284 The net result is pointers in JNI code are also 32 bits and 
1285 are stored in the high order 4 bytes on big-endian machines and in the low order 4 bytes on little-endian machines. 
1286 By design it is also not possible to manually cast
1287 a pointer to a new type by using Java casts as it is particularly dangerous especially when
1288 casting C++ objects.  If you need to cast a pointer or
1289 change its value, consider writing some helper functions instead.  For
1290 example:
1291 </p>
1292
1293 <div class="code">
1294 <pre>
1295 %inline %{
1296 /* C-style cast */
1297 Bar *FooToBar(Foo *f) {
1298    return (Bar *) f;
1299 }
1300
1301 /* C++-style cast */
1302 Foo *BarToFoo(Bar *b) {
1303    return dynamic_cast&lt;Foo*&gt;(b);
1304 }
1305
1306 Foo *IncrFoo(Foo *f, int i) {
1307     return f+i;
1308 }
1309 %}
1310 </pre>
1311 </div>
1312
1313 <p>
1314 Also, if working with C++, you should always try
1315 to use the new C++ style casts.  For example, in the above code, the
1316 C-style cast may return a bogus result whereas as the C++-style cast will return
1317 a NULL pointer if the conversion can't be performed.
1318 </p>
1319
1320 <H3><a name="structures"></a>21.3.7 Structures</H3>
1321
1322
1323 <p>
1324 If you wrap a C structure, it is wrapped by a Java class with getters and setters for access to the
1325 member variables. For example,
1326 </p>
1327
1328 <div class="code"><pre>
1329 struct Vector {
1330         double x,y,z;
1331 };
1332
1333 </pre></div>
1334
1335 <p>
1336 is used as follows:
1337 </p>
1338
1339 <div class="code"><pre>
1340 Vector v = new Vector();
1341 v.setX(3.5);
1342 v.setY(7.2);
1343 double x = v.getX();
1344 double y = v.getY();
1345 </pre></div>
1346
1347 <p>
1348 The variable setters and getters are also based on the JavaBean design pattern already covered under the Global variables section.
1349 Similar access is provided for unions and the public data members of C++ classes.</p>
1350
1351 <p>
1352 This object is actually an instance of a Java class that has been wrapped around a pointer to the C structure.  
1353 This instance doesn't actually do anything--it just serves as a proxy.
1354 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.
1355 Further details about Java proxy classes are covered a little later.
1356 </p>
1357
1358 <p>
1359 <tt>const</tt> members of a structure are read-only. Data members
1360 can also be forced to be read-only using the <tt>%immutable</tt> directive. For example:
1361 </p>
1362
1363 <div class="code">
1364 <pre>
1365 struct Foo {
1366    ...
1367    %immutable;
1368    int x;        /* Read-only members */
1369    char *name;
1370    %mutable;
1371    ...
1372 };
1373 </pre>
1374 </div>
1375
1376 <p>
1377 When <tt>char *</tt> members of a structure are wrapped, the contents are assumed to be
1378 dynamically allocated using <tt>malloc</tt> or <tt>new</tt> (depending on whether or not
1379 SWIG is run with the -c++ option).   When the structure member is set, the old contents will be 
1380 released and a new value created.   If this is not the behavior you want, you will have to use
1381 a typemap (described later).
1382 </p>
1383
1384 <p>
1385 If a structure contains arrays, access to those arrays is managed through pointers.  For
1386 example, consider this:
1387 </p>
1388
1389 <div class="code">
1390 <pre>
1391 struct Bar {
1392     int  x[16];
1393 };
1394 </pre>
1395 </div>
1396
1397 <p>
1398 If accessed in Java, you will see behavior like this:
1399 </p>
1400
1401 <div class="code">
1402 <pre>
1403 Bar b = new Bar();
1404 SWIGTYPE_p_int x = b.getX();
1405 </pre>
1406 </div>
1407
1408 <p>
1409 This pointer can be passed around to functions that expect to receive
1410 an <tt>int *</tt> (just like C).   You can also set the value of an array member using
1411 another pointer.  For example:
1412 </p>
1413
1414 <div class="code">
1415 <pre>
1416 Bar b = new Bar();
1417 SWIGTYPE_p_int x = b.getX();
1418 Bar c = new Bar();
1419 c.setX(x);                    // Copy contents of b.x to c.x
1420 </pre>
1421 </div>
1422
1423 <p>
1424 For array assignment (setters not getters), SWIG copies the entire contents of the array starting with the data pointed
1425 to by <tt>b.x</tt>.   In this example, 16 integers would be copied.  Like C, SWIG makes
1426 no assumptions about bounds checking---if you pass a bad pointer, you may get a segmentation
1427 fault or access violation.
1428 The default wrapping makes it hard to set or get just one element of the array and so array access from Java is somewhat limited.
1429 This can be changed easily though by using the approach outlined later in the <a href="#c_arrays">Wrapping C arrays with Java arrays</a> and
1430 <a href="#unbounded_c_arrays">Unbounded C Arrays</a> sections.
1431 </p>
1432
1433 <p>
1434 When a member of a structure is itself a structure, it is handled as a
1435 pointer.  For example, suppose you have two structures like this:
1436 </p>
1437
1438 <div class="code">
1439 <pre>
1440 struct Foo {
1441    int a;
1442 };
1443
1444 struct Bar {
1445    Foo f;
1446 };
1447 </pre>
1448 </div>
1449
1450 <p>
1451 Now, suppose that you access the <tt>f</tt> member of <tt>Bar</tt> like this:
1452 </p>
1453
1454 <div class="code">
1455 <pre>
1456 Bar b = new Bar();
1457 Foo x = b.getF();
1458 </pre>
1459 </div>
1460
1461 <p>
1462 In this case, <tt>x</tt> is a pointer that points to the <tt>Foo</tt> that is inside <tt>b</tt>.
1463 This is the same value as generated by this C code:
1464 </p>
1465
1466 <div class="code">
1467 <pre>
1468 Bar b;
1469 Foo *x = &amp;b-&gt;f;       /* Points inside b */
1470 </pre>
1471 </div>
1472
1473 <p>
1474 Because the pointer points inside the structure, you can modify the contents and 
1475 everything works just like you would expect. For example:
1476 </p>
1477
1478 <div class="code">
1479 <pre>
1480 Bar b = new Bar();
1481 b.getF().setA(3);   // Modify b.f.a
1482 Foo x = b.getF();                   
1483 x.setA(3);          // Modify x.a - this is the same as b.f.a
1484 </pre>
1485 </div>
1486
1487
1488 <H3><a name="classes"></a>21.3.8 C++ classes</H3>
1489
1490
1491 <p>
1492 C++ classes are wrapped by Java classes as well. For example, if you have this class,
1493 </p>
1494
1495 <div class="code"><pre>
1496 class List {
1497 public:
1498   List();
1499   ~List();
1500   int  search(char *item);
1501   void insert(char *item);
1502   void remove(char *item);
1503   char *get(int n);
1504   int  length;
1505 };
1506 </pre></div>
1507
1508 <p>
1509 you can use it in Java like this:
1510 </p>
1511
1512 <div class="code"><pre>
1513 List l = new List();
1514 l.insert("Ale");
1515 l.insert("Stout");
1516 l.insert("Lager");
1517 String item = l.get(2);
1518 int length = l.getLength();
1519 </pre></div>
1520
1521 <p>
1522 Class data members are accessed in the same manner as C structures.  
1523 </p>
1524
1525 <p>
1526 Static class members are unsurprisingly wrapped as static members of the Java class:
1527 </p>
1528
1529 <div class="code">
1530 <pre>
1531 class Spam {
1532 public:
1533    static void foo();
1534    static int bar;
1535 };
1536 </pre>
1537 </div>
1538
1539 <p>
1540 The static members work like any other Java static member:
1541 </p>
1542
1543 <div class="code">
1544 <pre>
1545 Spam.foo();
1546 int bar = Spam.getBar();
1547 </pre>
1548 </div>
1549
1550
1551 <H3><a name="inheritance"></a>21.3.9 C++ inheritance</H3>
1552
1553
1554 <p>
1555 SWIG is fully aware of issues related to C++ inheritance.  Therefore, if you have
1556 classes like this
1557 </p>
1558
1559 <div class="code">
1560 <pre>
1561 class Foo {
1562 ...
1563 };
1564
1565 class Bar : public Foo {
1566 ...
1567 };
1568 </pre>
1569 </div>
1570
1571 <p>
1572 those classes are wrapped into a hierarchy of Java classes that reflect the same inheritance
1573 structure:
1574 </p>
1575
1576 <div class="code">
1577 <pre>
1578 Bar b = new Bar();
1579 Class c = b.getClass();
1580 System.out.println(c.getSuperclass().getName());
1581 </pre>
1582 </div>
1583
1584 <p>
1585 will of course display:
1586 </p>
1587
1588 <div class="code"><pre>
1589 Foo
1590 </pre></div>
1591
1592
1593 <p>
1594 Furthermore, if you have functions like this
1595 </p>
1596
1597 <div class="code">
1598 <pre>
1599 void spam(Foo *f);
1600 </pre>
1601 </div>
1602
1603 <p>
1604 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>.
1605 </p>
1606
1607 <p>
1608 Note that Java does not support multiple inheritance so any multiple inheritance in the C++ code is not going to work. 
1609 A warning is given when multiple inheritance is detected and only the first base class is used. 
1610 </p>
1611
1612 <H3><a name="pointers_refs_arrays"></a>21.3.10 Pointers, references, arrays and pass by value</H3>
1613
1614
1615 <p>
1616 In C++, there are many different ways a function might receive
1617 and manipulate objects.  For example:
1618 </p>
1619
1620 <div class="code">
1621 <pre>
1622 void spam1(Foo *x);      // Pass by pointer
1623 void spam2(Foo &amp;x);      // Pass by reference
1624 void spam3(Foo x);       // Pass by value
1625 void spam4(Foo x[]);     // Array of objects
1626 </pre>
1627 </div>
1628
1629 <p>
1630 In Java, there is no detailed distinction like this--specifically,
1631 there are only instances of classes.  There are no pointers nor references.
1632 Because of this, SWIG unifies all of these types
1633 together in the wrapper code.  For instance, if you actually had the
1634 above functions, it is perfectly legal to do this from Java:
1635 </p>
1636
1637 <div class="code">
1638 <pre>
1639 Foo f = new Foo();  // Create a Foo
1640 example.spam1(f);   // Ok. Pointer
1641 example.spam2(f);   // Ok. Reference
1642 example.spam3(f);   // Ok. Value.
1643 example.spam4(f);   // Ok. Array (1 element)
1644 </pre>
1645 </div>
1646
1647 <p>
1648 Similar behavior occurs for return values.  For example, if you had
1649 functions like this,
1650 </p>
1651
1652 <div class="code">
1653 <pre>
1654 Foo *spam5();
1655 Foo &amp;spam6();
1656 Foo  spam7();
1657 </pre>
1658 </div>
1659
1660 <p>
1661 then all three functions will return a pointer to some <tt>Foo</tt> object.
1662 Since the third function (spam7) returns a value, newly allocated memory is used 
1663 to hold the result and a pointer is returned (Java will release this memory 
1664 when the returned object's finalizer is run by the garbage collector).
1665 </p>
1666
1667 <H4><a name="null_pointers"></a>21.3.10.1 Null pointers</H4>
1668
1669
1670 <p>
1671 Working with null pointers is easy. 
1672 A Java <tt>null</tt> can be used whenever a method expects a proxy class or typewrapper class.
1673 However, it is not possible to pass null to C/C++ functions that take parameters by value or by reference. 
1674 If you try you will get a NullPointerException.
1675 </p>
1676
1677 <div class="code">
1678 <pre>
1679 example.spam1(null);   // Pointer - ok
1680 example.spam2(null);   // Reference - NullPointerException
1681 example.spam3(null);   // Value - NullPointerException
1682 example.spam4(null);   // Array - ok
1683 </pre>
1684 </div>
1685
1686 <p>
1687 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. 
1688 The converse also occurs, that is, NULL pointers are translated into <tt>null</tt> Java objects when returned from a C/C++ function.
1689 </p>
1690
1691 <H3><a name="overloaded_functions"></a>21.3.11 C++ overloaded functions</H3>
1692
1693
1694 <p>
1695 C++ overloaded functions, methods, and constructors are mostly supported by SWIG.  For example,
1696 if you have two functions like this:
1697 </p>
1698
1699 <div class="code">
1700 <pre>
1701 %module example
1702
1703 void foo(int);
1704 void foo(char *c);
1705 </pre>
1706 </div>
1707
1708 <p>
1709 You can use them in Java in a straightforward manner:
1710 </p>
1711
1712 <div class="code">
1713 <pre>
1714 example.foo(3);           // foo(int)
1715 example.foo("Hello");     // foo(char *c)
1716 </pre>
1717 </div>
1718
1719 <p>
1720 Similarly, if you have a class like this,
1721 </p>
1722
1723 <div class="code">
1724 <pre>
1725 class Foo {
1726 public:
1727     Foo();
1728     Foo(const Foo &amp;);
1729     ...
1730 };
1731 </pre>
1732 </div>
1733
1734 <p>
1735 you can write Java code like this:
1736 </p>
1737
1738 <div class="code">
1739 <pre>
1740 Foo f = new Foo();        // Create a Foo
1741 Foo g = new Foo(f);       // Copy f
1742 </pre>
1743 </div>
1744
1745 <p>
1746 Overloading support is not quite as flexible as in C++. Sometimes there are methods that SWIG
1747 cannot disambiguate as there can be more than one C++ type mapping onto a single Java type. For example:
1748 </p>
1749
1750 <div class="code">
1751 <pre>
1752 void spam(int);
1753 void spam(unsigned short);
1754 </pre>
1755 </div>
1756
1757 <p>
1758 Here both int and unsigned short map onto a Java int. 
1759 Here is another example:
1760 </p>
1761
1762 <div class="code">
1763 <pre>
1764 void foo(Bar *b);
1765 void foo(Bar &amp;b);
1766 </pre>
1767 </div>
1768
1769 <p>
1770 If declarations such as these appear, you will get a warning message like this:
1771 </p>
1772
1773 <div class="code">
1774 <pre>
1775 example.i:12: Warning(515): Overloaded method spam(unsigned short) ignored.
1776 Method spam(int) at example.i:11 used.
1777 </pre>
1778 </div>
1779
1780 <p>
1781 To fix this, you either need to either <a href="SWIG.html#SWIG_rename_ignore">rename or ignore</a> one of the methods.  For example:
1782 </p>
1783
1784 <div class="code">
1785 <pre>
1786 %rename(spam_ushort) spam(unsigned short);
1787 ...
1788 void spam(int);    
1789 void spam(unsigned short);   // Now renamed to spam_ushort
1790 </pre>
1791 </div>
1792
1793 <p>
1794 or
1795 </p>
1796
1797 <div class="code">
1798 <pre>
1799 %ignore spam(unsigned short);
1800 ...
1801 void spam(int);    
1802 void spam(unsigned short);   // Ignored
1803 </pre>
1804 </div>
1805
1806 <H3><a name="java_default_arguments"></a>21.3.12 C++ default arguments</H3>
1807
1808
1809 <p>
1810 Any function with a default argument is wrapped by generating an additional function for each argument that is defaulted.
1811 For example, if we have the following C++:
1812 </p>
1813
1814 <div class="code">
1815 <pre>
1816 %module example
1817
1818 void defaults(double d=10.0, int i=0);
1819 </pre>
1820 </div>
1821
1822 <p>
1823 The following methods are generated in the Java module class:
1824 </p>
1825
1826 <div class="code">
1827 <pre>
1828 public class example {
1829   public static void defaults(double d, int i) { ... }
1830   public static void defaults(double d) { ... }
1831   public static void defaults() { ... }
1832 }
1833 </pre>
1834 </div>
1835
1836 <p>
1837 It is as if SWIG had parsed three separate overloaded methods.
1838 The same approach is taken for static methods, constructors and member methods.
1839 </p>
1840
1841 <p>
1842 <b>Compatibility note:</b> Versions of SWIG prior to SWIG-1.3.23 wrapped these with a
1843 single wrapper method and so the default values could not be taken advantage of from Java.
1844 Further details on default arguments and how to restore this approach are given in the more general 
1845 <a href="SWIGPlus.html#SWIGPlus_default_args">Default arguments</a> section.
1846 </p>
1847
1848
1849 <H3><a name="namespaces"></a>21.3.13 C++ namespaces</H3>
1850
1851
1852 <p>
1853 SWIG is aware of C++ namespaces, but namespace names do not appear in
1854 the module nor do namespaces result in a module that is broken up into
1855 submodules or packages.  For example, if you have a file like this,
1856 </p>
1857
1858 <div class="code">
1859 <pre>
1860 %module example
1861
1862 namespace foo {
1863    int fact(int n);
1864    struct Vector {
1865        double x,y,z;
1866    };
1867 };
1868 </pre>
1869 </div>
1870
1871 <p>
1872 it works in Java as follows:
1873 </p>
1874
1875 <div class="code">
1876 <pre>
1877 int f = example.fact(3);
1878 Vector v = new Vector();
1879 v.setX(3.4);
1880 double y = v.getY();
1881 </pre>
1882 </div>
1883
1884 <p>
1885 If your program has more than one namespace, name conflicts (if any) can be resolved using <tt>%rename</tt>
1886 For example:
1887 </p>
1888
1889 <div class="code">
1890 <pre>
1891 %rename(Bar_spam) Bar::spam;
1892
1893 namespace Foo {
1894     int spam();
1895 }
1896
1897 namespace Bar {
1898     int spam();
1899 }
1900 </pre>
1901 </div>
1902
1903 <p>
1904 If you have more than one namespace and you want to keep their
1905 symbols separate, consider wrapping them as separate SWIG modules.
1906 Each SWIG module can be placed into a separate package.
1907 </p>
1908
1909 <H3><a name="templates"></a>21.3.14 C++ templates</H3>
1910
1911
1912 <p>
1913 C++ templates don't present a huge problem for SWIG.  However, in order
1914 to create wrappers, you have to tell SWIG to create wrappers for a particular
1915 template instantiation.  To do this, you use the <tt>%template</tt> directive.
1916 For example:
1917 </p>
1918
1919 <div class="code">
1920 <pre>
1921 %module example
1922 %{
1923 #include &lt;utility&gt;
1924 %}
1925
1926 template&lt;class T1, class T2&gt;
1927 struct pair {
1928    typedef T1 first_type;
1929    typedef T2 second_type;
1930    T1 first;
1931    T2 second;
1932    pair();
1933    pair(const T1&amp;, const T2&amp;);
1934   ~pair();
1935 };
1936
1937 %template(pairii) pair&lt;int,int&gt;;
1938 </pre>
1939 </div>
1940
1941 <p>
1942 In Java:
1943 </p>
1944
1945 <div class="code">
1946 <pre>
1947 pairii p = new pairii(3,4);
1948 int first = p.getFirst();
1949 int second = p.getSecond();
1950 </pre>
1951 </div>
1952
1953 <p>
1954 Obviously, there is more to template wrapping than shown in this example.
1955 More details can be found in the <a href="SWIGPlus.html#SWIGPlus">SWIG and C++</a> chapter.   
1956 </p>
1957
1958 <H3><a name="smart_pointers"></a>21.3.15 C++ Smart Pointers</H3>
1959
1960
1961 <p>
1962 In certain C++ programs, it is common to use classes that have been wrapped by
1963 so-called "smart pointers."   Generally, this involves the use of a template class
1964 that implements <tt>operator-&gt;()</tt> like this:
1965 </p>
1966
1967 <div class="code">
1968 <pre>
1969 template&lt;class T&gt; class SmartPtr {
1970    ...
1971    T *operator-&gt;();
1972    ...
1973 }
1974 </pre>
1975 </div>
1976
1977 <p>
1978 Then, if you have a class like this,
1979 </p>
1980
1981 <div class="code">
1982 <pre>
1983 class Foo {
1984 public:
1985      int x;
1986      int bar();
1987 };
1988 </pre>
1989 </div>
1990
1991 <p>
1992 A smart pointer would be used in C++ as follows:
1993 </p>
1994
1995 <div class="code">
1996 <pre>
1997 SmartPtr&lt;Foo&gt; p = CreateFoo();   // Created somehow (not shown)
1998 ...
1999 p-&gt;x = 3;                        // Foo::x
2000 int y = p-&gt;bar();                // Foo::bar
2001 </pre>
2002 </div>
2003
2004 <p>
2005 To wrap this in Java, simply tell SWIG about the <tt>SmartPtr</tt> class and the low-level
2006 <tt>Foo</tt> object.  Make sure you instantiate <tt>SmartPtr</tt> using <tt>%template</tt> if necessary.
2007 For example:
2008 </p>
2009
2010 <div class="code">
2011 <pre>
2012 %module example
2013 ...
2014 %template(SmartPtrFoo) SmartPtr&lt;Foo&gt;;
2015 ...
2016 </pre>
2017 </div>
2018
2019 <p>
2020 Now, in Java, everything should just "work":
2021 </p>
2022
2023 <div class="code">
2024 <pre>
2025 SmartPtrFoo p = example.CreateFoo(); // Create a smart-pointer somehow
2026 p.setX(3);                           // Foo::x
2027 int y = p.bar();                     // Foo::bar
2028 </pre>
2029 </div>
2030
2031 <p>
2032 If you ever need to access the underlying pointer returned by <tt>operator-&gt;()</tt> itself,
2033 simply use the <tt>__deref__()</tt> method.  For example:
2034 </p>
2035
2036 <div class="code">
2037 <pre>
2038 Foo f = p.__deref__();               // Returns underlying Foo *
2039 </pre>
2040 </div>
2041
2042 <H2><a name="further_details"></a>21.4 Further details on the generated Java classes</H2>
2043
2044
2045 <p>
2046 In the previous section, a high-level view of Java wrapping was
2047 presented.  A key component of this wrapping is that structures and
2048 classes are wrapped by Java proxy classes and type wrapper classes are used
2049 in situations where no proxies are generated.  This provides a very
2050 natural, type safe Java interface to the C/C++ code and fits in with the Java programming paradigm.
2051 However, a number of low-level details were omitted.  This section provides a brief overview
2052 of how the proxy classes work and then covers the type wrapper classes.
2053 Finally enum classes are covered.
2054 First, the crucial intermediary JNI class is considered.
2055 </p>
2056
2057 <H3><a name="imclass"></a>21.4.1 The intermediary JNI class</H3>
2058
2059
2060 <p>
2061 In the <a href="SWIG.html#SWIG">"SWIG basics"</a> and <a href="SWIGPlus.html#SWIGPlus">"SWIG and C++"</a> chapters,
2062 details of low-level structure and class wrapping are described.  To summarize those chapters, if you
2063 have a global function and class like this
2064 </p>
2065
2066 <div class="code">
2067 <pre>
2068 class Foo {
2069 public:
2070      int x;
2071      int spam(int num, Foo* foo);
2072 };
2073 void egg(Foo* chips);
2074 </pre>
2075 </div>
2076
2077 <p>
2078 then SWIG transforms the class into a set of low-level procedural wrappers.
2079 These procedural wrappers essentially perform the equivalent of this C++ code:
2080 </p>
2081
2082 <div class="code">
2083 <pre>
2084 Foo *new_Foo() {
2085     return new Foo();
2086 }
2087 void delete_Foo(Foo *f) {
2088     delete f;
2089 }
2090 int Foo_x_get(Foo *f) {
2091     return f-&gt;x;
2092 }
2093 void Foo_x_set(Foo *f, int value) {
2094     f-&gt;x = value;
2095 }
2096 int Foo_spam(Foo *f, int num, Foo* foo) {
2097     return f-&gt;spam(num, foo);
2098 }
2099 </pre>
2100 </div>
2101
2102 <p>
2103 These procedural function names don't actually exist, but their functionality appears inside the generated
2104 JNI functions. The JNI functions have to follow a particular naming convention so the function names are actually:
2105 </p>
2106
2107 <div class="code">
2108 <pre>
2109 SWIGEXPORT jlong JNICALL Java_exampleJNI_new_1Foo(JNIEnv *jenv, jclass jcls);
2110 SWIGEXPORT void JNICALL Java_exampleJNI_delete_1Foo(JNIEnv *jenv, jclass jcls,
2111                                                     jlong jarg1);
2112 SWIGEXPORT void JNICALL Java_exampleJNI_Foo_1x_1set(JNIEnv *jenv, jclass jcls,
2113                                                     jlong jarg1, jobject jarg1_, jint jarg2);
2114 SWIGEXPORT jint JNICALL Java_exampleJNI_Foo_1x_1get(JNIEnv *jenv, jclass jcls,
2115                                                     jlong jarg1, jobject jarg1_);
2116 SWIGEXPORT jint JNICALL Java_exampleJNI_Foo_1spam(JNIEnv *jenv, jclass jcls,
2117                                                   jlong jarg1, jobject jarg1_, jint jarg2,
2118                                                   jlong jarg3, jobject jarg3_);
2119 SWIGEXPORT void JNICALL Java_exampleJNI_egg(JNIEnv *jenv, jclass jcls,
2120                                             jlong jarg1, jobject jarg1_);
2121 </pre>
2122 </div>
2123
2124 <p>
2125 For every JNI C function there has to be a static native Java function. These appear in the intermediary JNI class:
2126 </p>
2127
2128 <div class="code">
2129 <pre>
2130 class exampleJNI {
2131   public final static native long new_Foo();
2132   public final static native void delete_Foo(long jarg1);
2133   public final static native void Foo_x_set(long jarg1, Foo jarg1_, int jarg2);
2134   public final static native int Foo_x_get(long jarg1, Foo jarg1_);
2135   public final static native int Foo_spam(long jarg1, Foo jarg1_, int jarg2,
2136                                           long jarg3, Foo jarg3_);
2137   public final static native void egg(long jarg1, Foo jarg1_);
2138 }
2139 </pre>
2140 </div>
2141
2142 <p>
2143 This class contains the complete Java - C/C++ interface so all function calls go via this class. 
2144 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.
2145 </p>
2146
2147 <p>
2148 You may notice that SWIG uses a Java long wherever a pointer or class object needs to be marshalled across the Java-C/C++ boundary.
2149 This approach leads to minimal JNI code which makes for better performance as JNI code involves a lot of string manipulation.
2150 SWIG favours generating Java code over JNI code as Java code is compiled into byte code and avoids the costly string operations needed in JNI code.
2151 This approach has a downside though as the proxy class might get collected before the native method has completed.
2152 You might notice above that there is an additional parameters with a underscore postfix, eg <tt>jarg1_</tt>.
2153 These are added in order to prevent <a href="#java_pgcpp">premature garbage collection when marshalling proxy classes</a>.
2154 </p>
2155
2156 <p>
2157 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.
2158 </p>
2159
2160 <a name="java_module_directive"></a>
2161 <p>
2162 The name of the intermediary JNI class can be changed from its default, that is, the module name with JNI appended after it. 
2163 The module directive attribute <tt>jniclassname</tt> is used to achieve this:
2164 </p>
2165
2166 <div class="code">
2167 <pre>
2168 %module (jniclassname="name") modulename
2169 </pre>
2170 </div>
2171
2172 <p>
2173 If <tt>name</tt> is the same as <tt>modulename</tt> then the module class name gets changed
2174 from <tt>modulename</tt> to <tt>modulenameModule</tt>.
2175 </p>
2176
2177 <H4><a name="imclass_pragmas"></a>21.4.1.1 The intermediary JNI class pragmas</H4>
2178
2179
2180 <p>
2181 The intermediary JNI class can be tailored through the use of pragmas, but is not commonly done. The pragmas for this class are:
2182 </p>
2183
2184 <table BORDER summary="Intermediary JNI class pragmas">
2185 <tr VALIGN=TOP>
2186 <td><b>Pragma</b></td>
2187 <td><b>Description</b></td>
2188 </tr>
2189
2190 <tr>
2191     <td>jniclassbase            </td> <td>Base class for the intermediary JNI class</td>
2192 </tr>
2193 <tr>
2194     <td>jniclassclassmodifiers  </td> <td>Class modifiers and class type for the intermediary JNI class</td>
2195 </tr>
2196 <tr>
2197     <td>jniclasscode            </td> <td>Java code is copied verbatim into the intermediary JNI class</td>
2198 </tr>
2199 <tr>
2200     <td>jniclassimports         </td> <td>Java code, usually one or more import statements, placed before the intermediary JNI class definition</td>
2201 </tr>
2202 <tr>
2203     <td>jniclassinterfaces      </td> <td>Comma separated interface classes for the intermediary JNI class</td>
2204 </tr>
2205 </table>
2206
2207 <p>
2208 The pragma code appears in the generated intermediary JNI class where you would expect:
2209 </p>
2210
2211 <div class="code">
2212 <pre>
2213 [ jniclassimports pragma ]
2214 [ jniclassclassmodifiers pragma ] jniclassname extends [ jniclassbase pragma ]
2215                                           implements [ jniclassinterfaces pragma ] {
2216 [ jniclasscode pragma ]
2217 ... SWIG generated native methods ...
2218 }
2219 </pre>
2220 </div>
2221
2222 <p>
2223 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:
2224 </p>
2225
2226 <div class="code">
2227 <pre>
2228 %pragma(java) jniclasscode=%{
2229   static {
2230     try {
2231         System.loadLibrary("example");
2232     } catch (UnsatisfiedLinkError e) {
2233       System.err.println("Native code library failed to load. \n" + e);
2234       System.exit(1);
2235     }
2236   }
2237 %}
2238 </pre>
2239 </div>
2240
2241 <p>
2242 Pragmas will take either <tt>""</tt> or <tt>%{ %}</tt> as delimiters. 
2243 For example, let's change the intermediary JNI class access to public. 
2244 </p>
2245
2246 <div class="code">
2247 <pre>
2248 %pragma(java) jniclassclassmodifiers="public class"
2249 </pre>
2250 </div>
2251
2252 <p>
2253 All the methods in the intermediary JNI class will then be callable outside of the package as the method modifiers are public by default.
2254 </p>
2255
2256 <H3><a name="java_module_class"></a>21.4.2 The Java module class</H3>
2257
2258
2259 <p>
2260 All global functions and variable getters/setters appear in the module class. For our example, there is just one function:
2261 </p>
2262
2263 <div class="code">
2264 <pre>
2265 public class example {
2266   public static void egg(Foo chips) {
2267     exampleJNI.egg(Foo.getCPtr(chips), chips);
2268   }
2269 }
2270 </pre>
2271 </div>
2272
2273 <p>
2274 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:
2275 </p>
2276
2277 <div class="code">
2278 <pre>
2279 example.egg(new Foo());
2280 </pre>
2281 </div>
2282
2283 <p>
2284 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.
2285 </p>
2286
2287 <H4><a name="module_class_pragmas"></a>21.4.2.1 The Java module class pragmas</H4>
2288
2289
2290 <p>
2291 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:
2292 </p>
2293
2294 <table BORDER summary="Java module class pragmas">
2295 <tr VALIGN=TOP>
2296 <td><b>Pragma</b></td>
2297 <td><b>Description</b></td>
2298 </tr>
2299 <tr>
2300     <td>modulebase            </td> <td>Base class for the module class</td>
2301 </tr>
2302 <tr>
2303     <td>moduleclassmodifiers  </td> <td>Class modifiers and class type for the module class</td>
2304 </tr>
2305 <tr>
2306     <td>modulecode            </td> <td>Java code is copied verbatim into the module class</td>
2307 </tr>
2308 <tr>
2309     <td>moduleimports         </td> <td>Java code, usually one or more import statements, placed before the module class definition</td>
2310 </tr>
2311 <tr>
2312     <td>moduleinterfaces      </td> <td>Comma separated interface classes for the module class</td>
2313 </tr>
2314
2315 </table>
2316
2317
2318 <p>
2319 The pragma code appears in the generated module class like this:
2320 </p>
2321
2322 <div class="code">
2323 <pre>
2324 [ moduleimports pragma ]
2325 [ modulemodifiers pragma ] modulename extends [ modulebase pragma ]
2326                                       implements [ moduleinterfaces pragma ] {
2327 [ modulecode pragma ]
2328 ... SWIG generated wrapper functions ...
2329 }
2330 </pre>
2331 </div>
2332
2333 <p>
2334 See <a href="#imclass_pragmas">The intermediary JNI class pragmas</a> section for further details on using pragmas.
2335 </p>
2336
2337
2338 <H3><a name="java_proxy_classes"></a>21.4.3 Java proxy classes</H3>
2339
2340
2341 <p>
2342 A Java proxy class is generated for each structure, union or C++ class that is wrapped.
2343 Proxy classes have also been called <a href="http://java.sun.com/developer/JDCTechTips/2001/tt0612.html#tip2">peer classes</a>.
2344 The default proxy class for our previous example looks like this:
2345 </p>
2346
2347 <div class="code">
2348 <pre>
2349 public class Foo {
2350   private long swigCPtr;
2351   protected boolean swigCMemOwn;
2352
2353   protected Foo(long cPtr, boolean cMemoryOwn) {
2354     swigCMemOwn = cMemoryOwn;
2355     swigCPtr = cPtr;
2356   }
2357
2358   protected static long getCPtr(Foo obj) {
2359     return (obj == null) ? 0 : obj.swigCPtr;
2360   }
2361
2362   protected void finalize() {
2363     delete();
2364   }
2365
2366   public synchronized void delete() {
2367     if(swigCPtr != 0 &amp;&amp; swigCMemOwn) {
2368       swigCMemOwn = false;
2369       exampleJNI.delete_Foo(swigCPtr);
2370     }
2371     swigCPtr = 0;
2372   }
2373
2374   public void setX(int value) {
2375     exampleJNI.Foo_x_set(swigCPtr, this, value);
2376   }
2377
2378   public int getX() {
2379     return exampleJNI.Foo_x_get(swigCPtr, this);
2380   }
2381
2382   public int spam(int num, Foo foo) {
2383     return exampleJNI.Foo_spam(swigCPtr, this, num, Foo.getCPtr(foo), foo);
2384   }
2385
2386   public Foo() {
2387     this(exampleJNI.new_Foo(), true);
2388   }
2389
2390 }
2391 </pre>
2392 </div>
2393
2394
2395 <p>
2396 This class merely holds a pointer to the underlying C++ object (<tt>swigCPtr</tt>).
2397 It also contains all the methods in the C++ class it is proxying plus getters and setters for public
2398 member variables. These functions call the native methods in the intermediary JNI class. 
2399 The advantage of having this extra layer is the type safety that the proxy class functions offer. 
2400 It adds static type checking which leads to fewer surprises at runtime. 
2401 For example, you can see that if you attempt to use the <tt> spam() </tt> 
2402 function it will only compile when the parameters passed are an <tt>int</tt> and a <tt>Foo</tt>. 
2403 From a user's point of view, it makes the class work as if it were a Java class:
2404 </p>
2405
2406 <div class="code">
2407 <pre>
2408 Foo f = new Foo();
2409 f.setX(3);
2410 int y = f.spam(5, new Foo());
2411 </pre>
2412 </div>
2413
2414 <H4><a name="memory_management"></a>21.4.3.1 Memory management</H4>
2415
2416
2417 <p>
2418 Each proxy class has an ownership flag <tt>swigCMemOwn</tt>.   The value of this
2419 flag determines who is responsible for deleting the underlying C++ object.   If set to <tt>true</tt>,
2420 the proxy class's finalizer will destroy the C++ object when the proxy class is 
2421 garbage collected.   If set to false, then the destruction of the proxy class has no effect on the C++ object.
2422 </p>
2423
2424 <p>
2425 When an object is created by a constructor or returned by value, Java automatically takes
2426 ownership of the result. 
2427 On the other hand, when pointers or references are returned to Java, there is often no way to know where
2428 they came from.  Therefore, the ownership is set to false.  For example:
2429 </p>
2430
2431
2432 <div class="code">
2433 <pre>
2434 class Foo {
2435 public:
2436     Foo();
2437     Foo bar1();
2438     Foo &amp;bar2();
2439     Foo *bar2();
2440 };
2441 </pre>
2442 </div>
2443
2444 <p>
2445 In Java:
2446 </p>
2447
2448 <div class="code">
2449 <pre>
2450 Foo f = new Foo();   //  f.swigCMemOwn = true
2451 Foo f1 = f.bar1();   // f1.swigCMemOwn = true
2452 Foo f2 = f.bar2();   // f2.swigCMemOwn = false
2453 Foo f3 = f.bar3();   // f3.swigCMemOwn = false
2454 </pre>
2455 </div>
2456
2457 <p>
2458 This behavior for pointers and references is especially important for classes that act as containers.  
2459 For example, if a method returns a pointer to an object
2460 that is contained inside another object, you definitely don't want
2461 Java to assume ownership and destroy it!
2462 </p>
2463
2464 <p>
2465 For the most part, memory management issues remain hidden.  However,
2466 there are situations where you might have to manually
2467 change the ownership of an object.  For instance, consider code like this:
2468 </p>
2469
2470 <div class="code">
2471 <pre>
2472 class Obj {};
2473 class Node {
2474    Obj *value;
2475 public:
2476    void set_value(Obj *v) { value = v; }
2477 };
2478 </pre>
2479 </div>
2480
2481 <p>
2482 Now, consider the following Java code:
2483 </p>
2484
2485 <div class="code">
2486 <pre>
2487 Node n = new Node();    // Create a node
2488 {
2489   Obj o = new Obj();    // Create an object
2490   n.set_value(o);       // Set value
2491 }                       // o goes out of scope
2492 </pre>
2493 </div>
2494
2495 <p>
2496 In this case, the Node <tt>n</tt> is holding a reference to
2497 <tt>o</tt> internally.  However, SWIG has no way to know that this
2498 has occurred.  The Java proxy class still thinks that it has ownership of 
2499 <tt>o</tt>.  As <tt>o</tt> has gone out of scope, it could be garbage collected in which case the C++ destructor
2500 will be invoked and <tt>n</tt> will then be holding a stale-pointer to <tt>o</tt>.  If
2501 you're lucky, you will only get a segmentation fault.
2502 </p>
2503
2504 <p>
2505 To work around this, the ownership flag of <tt>o</tt> needs changing to <tt>false</tt>. 
2506 The ownership flag is a private member variable of the proxy class so this is not possible without some customization of the proxy class. 
2507 This can be achieved by using a typemap to customise the proxy class with pure Java code as detailed later in the section on 
2508 <a href="#java_typemaps">Java typemaps</a>.
2509 </p>
2510
2511 <p>
2512 Sometimes a function will create memory and return a pointer to a newly allocated object. 
2513 SWIG has no way of knowing this so by default the proxy class does not manage the returned object.
2514 However, you can tell the proxy class to manage the memory if you specify the <tt>%newobject</tt> directive. Consider:
2515 </p>
2516
2517 <div class="code">
2518 <pre>
2519 class Obj {...};
2520 class Factory {
2521 public:
2522     static Obj *createObj() { return new Obj(); }
2523 };
2524 </pre>
2525 </div>
2526
2527 <p>
2528 If we call the factory function, then we have to manually delete the memory:
2529 </p>
2530
2531 <div class="code">
2532 <pre>
2533 Obj obj = Factory.createObj();   // obj.swigCMemOwn = false
2534 ...
2535 obj.delete();
2536 </pre>
2537 </div>
2538
2539 <p>
2540 Now add in the %newobject directive:
2541 </p>
2542
2543 <div class="code">
2544 <pre>
2545 %newobject Factory::createObj();
2546
2547 class Obj {...};
2548 class Factory {
2549 public:
2550     static Obj *createObj() { return new Obj(); }
2551 };
2552 </pre>
2553 </div>
2554
2555 <p>
2556 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.
2557 </p>
2558
2559 <div class="code">
2560 <pre>
2561 Obj obj = Factory.createObj();   // obj.swigCMemOwn = true;
2562 ...
2563 </pre>
2564 </div>
2565
2566 <p>
2567 Some memory management issues are quite tricky to fix and may only be noticeable after using for a long time.
2568 One such issue is premature garbage collection of an object created from Java and resultant usage from C++ code.
2569 The section on typemap examples cover two such scenarios, 
2570 <a href="#java_memory_management_objects">Memory management for objects passed to the C++ layer</a>
2571 and 
2572 <a href="#java_memory_management_member_variables">Memory management when returning references to member variables</a>
2573 </p>
2574
2575
2576 <H4><a name="inheritance_mirroring"></a>21.4.3.2 Inheritance</H4>
2577
2578
2579 <p>
2580 Java proxy classes will mirror C++ inheritance chains. For example, given the base class <tt>Base</tt> and its derived class <tt>Derived</tt>:
2581 </p>
2582
2583 <div class="code"><pre>
2584 class Base {
2585 public:
2586   virtual double foo();
2587 };
2588
2589 class Derived : public Base {
2590 public:
2591   virtual double foo();
2592 };
2593 </pre></div>
2594
2595 <p>
2596 The base class is generated much like any other proxy class seen so far:
2597 </p>
2598
2599 <div class="code"><pre>
2600 public class Base {
2601   private long swigCPtr;
2602   protected boolean swigCMemOwn;
2603
2604   protected Base(long cPtr, boolean cMemoryOwn) {
2605     swigCMemOwn = cMemoryOwn;
2606     swigCPtr = cPtr;
2607   }
2608
2609   protected static long getCPtr(Base obj) {
2610     return (obj == null) ? 0 : obj.swigCPtr;
2611   }
2612
2613   protected void finalize() {
2614     delete();
2615   }
2616
2617   public synchronized void delete() {
2618     if(swigCPtr != 0 &amp;&amp; swigCMemOwn) {
2619       swigCMemOwn = false;
2620       exampleJNI.delete_Base(swigCPtr);
2621     }
2622     swigCPtr = 0;
2623   }
2624
2625   public double foo() {
2626     return exampleJNI.Base_foo(swigCPtr, this);
2627   }
2628
2629   public Base() {
2630     this(exampleJNI.new_Base(), true);
2631   }
2632
2633 }
2634 </pre></div>
2635
2636 <p>
2637 The <tt>Derived</tt> class extends <tt>Base</tt> mirroring the C++ class inheritance hierarchy. 
2638 </p>
2639
2640 <div class="code"><pre>
2641 public class Derived extends Base {
2642   private long swigCPtr;
2643
2644   protected Derived(long cPtr, boolean cMemoryOwn) {
2645     super(exampleJNI.SWIGDerivedUpcast(cPtr), cMemoryOwn);
2646     swigCPtr = cPtr;
2647   }
2648
2649   protected static long getCPtr(Derived obj) {
2650     return (obj == null) ? 0 : obj.swigCPtr;
2651   }
2652
2653   protected void finalize() {
2654     delete();
2655   }
2656
2657   public synchronized void delete() {
2658     if(swigCPtr != 0 &amp;&amp; swigCMemOwn) {
2659       swigCMemOwn = false;
2660       exampleJNI.delete_Derived(swigCPtr);
2661     }
2662     swigCPtr = 0;
2663     super.delete();
2664   }
2665
2666   public double foo() {
2667     return exampleJNI.Derived_foo(swigCPtr, this);
2668   }
2669
2670   public Derived() {
2671     this(exampleJNI.new_Derived(), true);
2672   }
2673
2674 }
2675 </pre></div>
2676
2677 <p>
2678 Note the memory ownership is controlled by the base class. 
2679 However each class in the inheritance hierarchy has its own pointer value which is obtained during construction. 
2680 The <tt>SWIGDerivedUpcast()</tt> call converts the pointer from a <tt>Derived *</tt> to a <tt>Base *</tt>.
2681 This is a necessity as C++ compilers are free to implement pointers in the inheritance hierarchy with different values. 
2682 </p>
2683
2684 <p>
2685 It is of course possible to extend <tt>Base</tt> using your own Java classes. 
2686 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>. 
2687 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.
2688 However, true cross language polymorphism can be achieved using the <a href="#java_directors">directors</a> feature.
2689 </p>
2690
2691
2692 <H4><a name="proxy_classes_gc"></a>21.4.3.3 Proxy classes and garbage collection</H4>
2693
2694
2695 <p>
2696 By default each proxy class has a <tt>delete()</tt> and a <tt>finalize()</tt> method. 
2697 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. 
2698 The idea is for <tt>delete()</tt> to be called when you have finished with the C/C++ object. 
2699 Ideally you need not call <tt>delete()</tt>, but rather leave it to the garbage collector to call it from the finalizer. 
2700 When a program exits, the garbage collector does not guarantee to call all finalizers. 
2701 An insight into the reasoning behind this can be obtained from <a href="http://www.hpl.hp.com/techreports/2002/HPL-2002-335.html">Hans Boehm's Destructors, Finalizers, and Synchronization</a> paper.
2702 Depending on what the finalizers do and which operating system you use, this may or may not be a problem. 
2703 </p>
2704
2705 <p>
2706 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. 
2707 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. 
2708 In Windows and Unix all memory that a process uses is returned to the system on exit, so this isn't a problem. 
2709 This is not the case in some operating systems like vxWorks. 
2710 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. 
2711 Note that with long running programs the garbage collector will eventually run, thereby calling any unreferenced object's finalizers.
2712 </p>
2713
2714 <p>
2715 Some not so ideal solutions are:
2716 </p>
2717
2718 <ol>
2719 <li><p>
2720 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 documentation says: </p>
2721 <div class="code"><i>
2722 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.
2723 </i></div> 
2724 <p>In many cases you will be lucky and find that it works, but it is not to be advocated. 
2725 Have a look at <a href="http://java.sun.com">Sun's Java web site</a> and search for <tt>runFinalizersOnExit</tt>.
2726 </p></li>
2727
2728 <li><p>
2729 From jdk1.3 onwards a new function, <tt>addShutdownHook()</tt>, was introduced which is guaranteed to be called when your program exits. 
2730 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: </p>
2731 <div class="code"><pre>
2732   static {
2733     Runtime.getRuntime().addShutdownHook( 
2734       new Thread() {
2735         public void run() { System.gc(); System.runFinalization(); }
2736       }
2737     );
2738   }
2739 </pre></div>
2740 <p>Although this usually works, the documentation doesn't guarantee that <tt>runFinalization()</tt> will actually call the finalizers. 
2741 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.</p>
2742 </li>
2743
2744 <li>
2745 <p>Call the <tt>delete()</tt> function manually which will immediately invoke the C++ destructor. 
2746 As a suggestion it may be a good idea to set the object to null so that should the object be inadvertently used again a Java null pointer exception is thrown, the alternative would crash the JVM by using a null C pointer. 
2747 For example given a SWIG generated class A:</p>
2748 <div class="code"><pre>
2749 A myA = new A();
2750 // use myA ...
2751 myA.delete();
2752 // any use of myA here would crash the JVM 
2753 myA=null;
2754 // any use of myA here would cause a Java null pointer exception to be thrown
2755 </pre></div>
2756
2757 <p>
2758 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.
2759 </p>
2760 </li>
2761
2762 <li>
2763 <p>
2764 Write your own object manager in Java. 
2765 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.
2766 The section on <a href="#java_typemaps">Java typemaps</a> details how to specify a pure Java base class.
2767 </p>
2768 </li>
2769 </ol>
2770
2771 <p>
2772 See the <a href="http://www.devx.com/Java/Article/30192">How to Handle Java Finalization's Memory-Retention Issues</a> article for alternative approaches to managing memory by avoiding finalizers altogether.
2773 </p>
2774
2775 <H4><a name="java_pgcpp"></a>21.4.3.4 The premature garbage collection prevention parameter for proxy class marshalling</H4>
2776
2777
2778 <p>
2779 As covered earlier, the C/C++ struct/class pointer is stored in the proxy class as a Java long and when needed is passed
2780 into the native method where it is cast into the appropriate type.
2781 This approach provides very fast marshalling but could be susceptible to premature garbage collection.
2782 Consider the following C++ code:
2783 </p>
2784
2785 <div class="code"><pre>
2786 class Wibble {
2787 };
2788 void wobble(Wibble &amp;w);
2789 </pre></div>
2790
2791 <p>
2792 The module class contains the Java wrapper for the global <tt>wobble</tt> method:
2793 </p>
2794
2795 <div class="code"><pre>
2796 public class example {
2797   ...
2798   public static void wobble(Wibble w) {
2799     exampleJNI.wobble(Wibble.getCPtr(w), w);
2800   }
2801 }
2802 </pre></div>
2803
2804 <p>
2805 where <tt>example</tt> is the name of the module. 
2806 All native methods go through the intermediary class which has the native method declared as such:
2807 </p>
2808
2809 <div class="code"><pre>
2810 public class exampleJNI {
2811   ...
2812   public final static native void wobble(long jarg1, Wibble jarg1_);
2813 }
2814 </pre></div>
2815
2816 <p>
2817 The second parameter, <tt>jarg1_</tt>, is the premature garbage collection prevention parameter and is added to the native method parameter list whenever a C/C++ struct or class is marshalled as a Java long.
2818 In order to understand why, consider the alternative where the intermediary class method is declared without the additional parameter:
2819 </p>
2820
2821 <div class="code"><pre>
2822 public class exampleJNI {
2823   ...
2824   public final static native void wobble(long jarg1);
2825 }
2826 </pre></div>
2827
2828 <p>
2829 and the following simple call to <tt>wobble</tt>:
2830 </p>
2831
2832 <div class="code"><pre>
2833 {
2834   Wibble w = new Wibble();
2835   example.wobble(w);
2836 }
2837 </pre></div>
2838
2839 <p>
2840 The hotspot compiler effectively sees something like:
2841 </p>
2842
2843 <div class="code"><pre>
2844 {
2845   Wibble w = new Wibble();
2846   long w_ptr = Wibble.getCPtr(w);
2847   // w is no longer reachable
2848   exampleJNI.wobble(w_ptr);
2849 }
2850 </pre></div>
2851
2852 <p>
2853 The <tt>Wibble</tt> object is no longer reachable after the point shown as in this bit of code, the <tt>Wibble</tt> object is not referenced again after this point.
2854 This means that it is a candidate for garbage collection.
2855 Should <tt>wobble</tt> be a long running method, it is quite likely that the finalizer for the <tt>Wibble</tt> instance will be called.
2856 This in turn will call its underlying C++ destructor which 
2857 is obviously disastrous while the method <tt>wobble</tt> is running using this object.
2858 Even if <tt>wobble</tt> is not a long running method, it is possible for the <tt>Wibble</tt> instance to be finalized.
2859 By passing the <tt>Wibble</tt> instance into the native method, it will not be finalized as the JVM guarantees not to
2860 finalize any objects until the native method returns.
2861 Effectively, the code then becomes
2862 </p>
2863
2864 <div class="code"><pre>
2865 {
2866   Wibble w = new Wibble();
2867   long w_ptr = Wibble.getCPtr(w);
2868   exampleJNI.wobble(w_ptr, w);
2869   // w is no longer reachable
2870 }
2871 </pre></div>
2872
2873 <p>
2874 and therefore there is no possibility of premature garbage collection. In practice, this premature garbage collection was only ever observed in Sun's server JVM from jdk-1.3 onwards and in Sun's client JVM from jdk-1.6 onwards.
2875 </p>
2876
2877 <p>
2878 The premature garbage collection prevention parameter for proxy classes is generated by default whenever proxy classes are passed by value, reference or with a pointer.
2879 The implementation for this extra parameter generation requires the "jtype" typemap to contain <tt>long</tt> and the "jstype" typemap to contain the name of a proxy class.
2880 </p>
2881
2882 <p>
2883 The additional parameter does impose a slight performance overhead and the parameter generation can be suppressed globally with the <tt>-nopgcpp</tt> commandline option.
2884 More selective suppression is possible with the 'nopgcpp' attribute in the "jtype" <a href="#java_typemaps">Java typemap</a>.
2885 The attribute is a flag and so should be set to "1" to enable the suppression, or it can be omitted or set to "0" to disable.
2886 For example:
2887 </p>
2888
2889 <div class="code"><pre>
2890 %typemap(jtype, nopgcpp="1") Wibble &amp; "long"
2891 </pre></div>
2892
2893 <p>
2894 <b>Compatibility note:</b> The generation of this additional parameter did not occur in versions prior to SWIG-1.3.30.
2895 </p>
2896
2897 <H4><a name="java_multithread_libraries"></a>21.4.3.5 Single threaded applications and thread safety</H4>
2898
2899
2900 <p>
2901 Single threaded Java applications using JNI need to consider thread safety.
2902 The same applies for the C# module where the .NET wrappers use PInvoke.
2903 Consider the C++ class:
2904 </p>
2905
2906 <div class="code"><pre>
2907 class Test {
2908   string str;
2909 public:
2910   Test() : str("initial") {}
2911 };
2912 </pre></div>
2913
2914 <p>
2915 and the Java proxy class generated by SWIG:
2916 </p>
2917
2918 <div class="code"><pre>
2919 public class Test {
2920   private long swigCPtr;
2921   protected boolean swigCMemOwn;
2922
2923   protected Test(long cPtr, boolean cMemoryOwn) {
2924     swigCMemOwn = cMemoryOwn;
2925     swigCPtr = cPtr;
2926   }
2927
2928   protected static long getCPtr(Test obj) {
2929     return (obj == null) ? 0 : obj.swigCPtr;
2930   }
2931
2932   protected void finalize() {
2933     delete();
2934   }
2935
2936   // Call C++ destructor
2937   public synchronized void delete() {
2938     if(swigCPtr != 0 &amp;&amp; swigCMemOwn) {
2939       swigCMemOwn = false;
2940       exampleJNI.delete_Test(swigCPtr);
2941     }
2942     swigCPtr = 0;
2943   }
2944
2945   // Call C++ constructor
2946   public Test() {
2947     this(exampleJNI.new_Test(), true);
2948   }
2949
2950 }
2951 </pre></div>
2952
2953
2954 <p>
2955 It has two methods that call JNI methods, namely, <tt>exampleJNI.new_Test()</tt> for the C++ constructor and <tt>exampleJNI.delete_Test()</tt> for the C++ destructor. 
2956 If the garbage collector collects an instance of this class, ie <tt>delete()</tt> is not explicitly called, then the C++ destructor will be run in a different thread to the main thread. 
2957 This is because when an object is marked for garbage collection, any objects with finalizers are added to a finalization queue 
2958 and the objects in the finalization queue have their <tt>finalize()</tt> methods run in a separate finalization thread. 
2959 Therefore, if the C memory allocator is not thread safe, then the heap will get corrupted sooner or later, when a concurrent C++ delete and new are executed. 
2960 It is thus essential, even in single threaded usage, to link to the C multi-thread runtime libraries,
2961 for example, use the /MD option for Visual C++ on Windows.
2962 Alternatively, lock all access to C++ functions that have heap allocation/deallocation. 
2963 </p>
2964
2965 <p>
2966 Note that some of the STL in Visual C++ 6 is not thread safe, so although code might be linked to the multithread runtime libraries, undefined behaviour might still occur in a single threaded Java program.
2967 Similarly some older versions of Sun Studio have bugs in the multi-threaded implementation of the std::string class and so will lead to undefined behaviour in these supposedly single threaded Java applications.
2968 </p>
2969
2970 <p>
2971 The following innocuous Java usage of Test is an example that will crash very quickly on a multiprocessor machine if the JNI compiled code is linked against the single thread C runtime libraries.
2972 </p>
2973  
2974 <div class="code"><pre>
2975 for (int i=0; i&lt;100000; i++) {
2976   System.out.println("Iteration " + i);
2977   for (int k=0; k&lt;10; k++) {
2978     Test test = new Test();
2979   }
2980   System.gc();
2981 }
2982 </pre></div>
2983  
2984
2985 <H3><a name="type_wrapper_classes"></a>21.4.4 Type wrapper classes</H3>
2986
2987
2988 <p>
2989 The generated type wrapper class, for say an <tt>int *</tt>, looks like this:
2990 </p>
2991
2992 <div class="code"><pre>
2993 public class SWIGTYPE_p_int {
2994   private long swigCPtr;
2995
2996   protected SWIGTYPE_p_int(long cPtr, boolean bFutureUse) {
2997     swigCPtr = cPtr;
2998   }
2999
3000   protected SWIGTYPE_p_int() {
3001     swigCPtr = 0;
3002   }
3003
3004   protected static long getCPtr(SWIGTYPE_p_int obj) {
3005     return obj.swigCPtr;
3006   }
3007 }
3008 </pre></div>
3009
3010 <p>
3011 The methods do not have public access, so by default it is impossible to do anything with objects of this class other than 
3012 pass them around. The methods in the class are part of the inner workings of SWIG. 
3013 If you need to mess around with pointers you will have to use some typemaps specific to the Java module to achieve this.
3014 The section on <a href="#java_typemaps">Java typemaps</a> details how to modify the generated code.
3015 </p>
3016
3017 <p>
3018 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
3019 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
3020 is generated for your use. 
3021 </p>
3022
3023 <p>
3024 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. 
3025 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.
3026 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.
3027 Also recall from earlier that SWIG will use a pointer when a class is passed by value or by reference:
3028 </p>
3029
3030 <div class="code">
3031 <pre>
3032 void spam(Snazzy *x, Snazzy &amp;y, Snazzy z);
3033 </pre>
3034 </div>
3035
3036 <p>
3037 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.
3038 The Java function generated is:
3039 </p>
3040
3041 <div class="code">
3042 <pre>
3043 public static void spam(SWIGTYPE_p_Snazzy x, SWIGTYPE_p_Snazzy y, SWIGTYPE_p_Snazzy z) {
3044  ...
3045 }
3046 </pre>
3047 </div>
3048
3049 <p>
3050 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:
3051 </p>
3052
3053
3054 <div class="code">
3055 <pre>
3056 typedef int Snazzy;
3057 void spam(Snazzy *x, Snazzy &amp;y, Snazzy z);
3058 </pre>
3059 </div>
3060
3061 <p>
3062 Because the typedefs have been tracked the Java function generated is:
3063 </p>
3064
3065 <div class="code">
3066 <pre>
3067 public static void spam(SWIGTYPE_p_int x, SWIGTYPE_p_int y, int z) { ... }
3068 </pre>
3069 </div>
3070
3071
3072 <H3><a name="enum_classes"></a>21.4.5 Enum classes</H3>
3073
3074
3075 <p>
3076 SWIG can generate three types of enum classes.
3077 The <a href="#enumerations">Enumerations</a> section discussed these but omitted all the details.
3078 The following sub-sections detail the various types of enum classes that can be generated.
3079 </p>
3080
3081 <H4><a name="typesafe_enums_classes"></a>21.4.5.1 Typesafe enum classes</H4>
3082
3083
3084 <p>
3085 The following example demonstrates the typesafe enum classes which SWIG generates:
3086 </p>
3087
3088 <div class="code">
3089 <pre>
3090 %include "enumtypesafe.swg"
3091 %javaconst(1);
3092 enum Beverage { ALE, LAGER=10, STOUT, PILSNER, PILZ=PILSNER };
3093 </pre>
3094 </div>
3095
3096 <p>
3097 The following is the code that SWIG generates:
3098 </p>
3099
3100 <div class="code">
3101 <pre>
3102 public final class Beverage {
3103   public final static Beverage ALE = new Beverage("ALE");
3104   public final static Beverage LAGER = new Beverage("LAGER", 10);
3105   public final static Beverage STOUT = new Beverage("STOUT");
3106   public final static Beverage PILSNER = new Beverage("PILSNER");
3107   public final static Beverage PILZ = new Beverage("PILZ", PILSNER);
3108
3109   public final int swigValue() {
3110     return swigValue;
3111   }
3112
3113   public String toString() {
3114     return swigName;
3115   }
3116
3117   public static Beverage swigToEnum(int swigValue) {
3118     if (swigValue &lt; swigValues.length &amp;&amp; swigValue &gt;= 0 &amp;&amp;
3119         swigValues[swigValue].swigValue == swigValue)
3120       return swigValues[swigValue];
3121     for (int i = 0; i &lt; swigValues.length; i++)
3122       if (swigValues[i].swigValue == swigValue)
3123         return swigValues[i];
3124     throw new IllegalArgumentException("No enum " + Beverage.class + " with value " +
3125                                                                          swigValue);
3126   }
3127
3128   private Beverage(String swigName) {
3129     this.swigName = swigName;
3130     this.swigValue = swigNext++;
3131   }
3132
3133   private Beverage(String swigName, int swigValue) {
3134     this.swigName = swigName;
3135     this.swigValue = swigValue;
3136     swigNext = swigValue+1;
3137   }
3138
3139   private Beverage(String swigName, Beverage swigEnum) {
3140     this.swigName = swigName;
3141     this.swigValue = swigEnum.swigValue;
3142     swigNext = this.swigValue+1;
3143   }
3144
3145   private static Beverage[] swigValues = { ALE, LAGER, STOUT, PILSNER, PILZ };
3146   private static int swigNext = 0;
3147   private final int swigValue;
3148   private final String swigName;
3149 }
3150 </pre>
3151 </div>
3152
3153 <p>
3154 As can be seen, there are a fair number of support methods for the typesafe enum pattern.
3155 The typesafe enum pattern involves creating a fixed number of static instances of the enum class.
3156 The constructors are private to enforce this.
3157 Three constructors are available - two for C/C++ enums with an initializer and one for those without an initializer.
3158 Note that the two enums with initializers, <tt>LAGER</tt> and <tt>PILZ</tt>, each call one the two different initializer constructors.
3159 In order to use one of these typesafe enums, the <tt>swigToEnum</tt> static method must be called to return a reference to one of the static instances.
3160 The JNI layer returns the enum value from the C/C++ world as an integer and this method is used to find the appropriate Java enum static instance.
3161 The <tt>swigValue</tt> method is used for marshalling in the other direction.
3162 The <tt>toString</tt> method is overridden so that the enum name is available.
3163 </p>
3164
3165 <H4><a name="proper_enums_classes"></a>21.4.5.2 Proper Java enum classes</H4>
3166
3167
3168 <p>
3169 The following example demonstrates the Java enums approach:
3170 </p>
3171
3172 <div class="code">
3173 <pre>
3174 %include "enums.swg"
3175 %javaconst(1);
3176 enum Beverage { ALE, LAGER=10, STOUT, PILSNER, PILZ=PILSNER };
3177 </pre>
3178 </div>
3179
3180 <p>
3181 SWIG will generate the following Java enum:
3182 </p>
3183
3184 <div class="code">
3185 <pre>
3186 public enum Beverage {
3187   ALE,
3188   LAGER(10),
3189   STOUT,
3190   PILSNER,
3191   PILZ(PILSNER);
3192
3193   public final int swigValue() {
3194     return swigValue;
3195   }
3196
3197   public static Beverage swigToEnum(int swigValue) {
3198     Beverage[] swigValues = Beverage.class.getEnumConstants();
3199     if (swigValue &lt; swigValues.length &amp;&amp; swigValue &gt;= 0 &amp;&amp;
3200         swigValues[swigValue].swigValue == swigValue)
3201       return swigValues[swigValue];
3202     for (Beverage swigEnum : swigValues)
3203       if (swigEnum.swigValue == swigValue)
3204         return swigEnum;
3205     throw new IllegalArgumentException("No enum " + Beverage.class +
3206                                        " with value " + swigValue);
3207   }
3208
3209   private Beverage() {
3210     this.swigValue = SwigNext.next++;
3211   }
3212
3213   private Beverage(int swigValue) {
3214     this.swigValue = swigValue;
3215     SwigNext.next = swigValue+1;
3216   }
3217
3218   private Beverage(Beverage swigEnum) {
3219     this.swigValue = swigEnum.swigValue;
3220     SwigNext.next = this.swigValue+1;
3221   }
3222
3223   private final int swigValue;
3224
3225   private static class SwigNext {
3226     private static int next = 0;
3227   }
3228 }
3229 </pre>
3230 </div>
3231
3232 <p>
3233 The enum items appear first.
3234 Like the typesafe enum pattern, the constructors are private.
3235 The constructors are required to handle C/C++ enums with initializers.
3236 The <tt>next</tt> variable is in the <tt>SwigNext</tt> inner class rather than in the enum class as static primitive variables cannot be modified from within enum constructors.
3237 Marshalling between Java enums and the C/C++ enum integer value is handled via the <tt>swigToEnum</tt> and <tt>swigValue</tt> methods.
3238 All the constructors and methods in the Java enum are required just to handle C/C++ enums with initializers.
3239 These needn't be generated if the enum being wrapped does not have any initializers and the 
3240 <a href="#simpler_enum_classes">Simpler Java enums for enums without initializers</a> section describes how typemaps can be used to achieve this.
3241 </p>
3242
3243 <H4><a name="typeunsafe_enums_classes"></a>21.4.5.3 Type unsafe enum classes</H4>
3244
3245
3246 <p>
3247 The following example demonstrates type unsafe enums:
3248 </p>
3249
3250 <div class="code">
3251 <pre>
3252 %include "enumtypeunsafe.swg"
3253 %javaconst(1);
3254 enum Beverage { ALE, LAGER=10, STOUT, PILSNER, PILZ=PILSNER };
3255 </pre>
3256 </div>
3257
3258 <p>
3259 SWIG will generate the following simple class:
3260 </p>
3261
3262 <div class="code">
3263 <pre>
3264 public final class Beverage {
3265   public final static int ALE = 0;
3266   public final static int LAGER = 10;
3267   public final static int STOUT = LAGER + 1;
3268   public final static int PILSNER = STOUT + 1;
3269   public final static int PILZ = PILSNER;
3270 }
3271 </pre>
3272 </div>
3273
3274 <H2><a name="java_directors"></a>21.5 Cross language polymorphism using directors</H2>
3275
3276
3277 <p>
3278 Proxy classes provide a natural, object-oriented way to wrap C++ classes.
3279 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.
3280 </p>
3281
3282 <p>
3283 This arrangement is asymmetric in the sense that no corresponding mechanism exists to pass method calls down the inheritance chain from C++ to Java. 
3284 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. 
3285 Virtual method calls from C++ are thus not able to access the lowest implementation in the inheritance chain.
3286 </p>
3287
3288 <p>
3289 SWIG can address this problem and make the relationship between C++ classes and proxy classes more symmetric. 
3290 To achieve this goal, new classes called directors are introduced at the bottom of the C++ inheritance chain. 
3291 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. 
3292 The upshot is that C++ classes can be extended in Java and from C++ these extensions look exactly like native C++ classes. 
3293 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.
3294 </p>
3295
3296 <H3><a name="java_enabling_directors"></a>21.5.1 Enabling directors</H3>
3297
3298
3299 <p>
3300 The director feature is disabled by default.
3301 To use directors you must make two changes to the interface file.
3302 First, add the "directors" option to the %module directive, like this:
3303 </p>
3304
3305 <div class="code">
3306 <pre>
3307 %module(directors="1") modulename
3308 </pre>
3309 </div>
3310
3311 <p>
3312 Without this option no director code will be generated.
3313 Second, you must use the %feature("director") directive to tell SWIG which classes and methods should get directors.
3314 The %feature directive can be applied globally, to specific classes, and to specific methods, like this:
3315 </p>
3316
3317 <div class="code">
3318 <pre>
3319 // generate directors for all classes that have virtual methods
3320 %feature("director");         
3321
3322 // generate directors for all virtual methods in class Foo
3323 %feature("director") Foo;      
3324
3325 // generate a director for just Foo::bar()
3326 %feature("director") Foo::bar; 
3327 </pre>
3328 </div>
3329
3330 <p>
3331 You can use the %feature("nodirector") directive to turn off directors for specific classes or methods.
3332 So for example,
3333 </p>
3334
3335 <div class="code">
3336 <pre>
3337 %feature("director") Foo;
3338 %feature("nodirector") Foo::bar;
3339 </pre>
3340 </div>
3341
3342 <p>
3343 will generate directors for all virtual methods of class Foo except bar().  
3344 </p>
3345
3346 <p>
3347 Directors can also be generated implicitly through inheritance. 
3348 In the following, class Bar will get a director class that handles the methods one() and two() (but not three()):
3349 </p>
3350
3351 <div class="code">
3352 <pre>
3353 %feature("director") Foo;
3354 class Foo {
3355 public:
3356     virtual void one();
3357     virtual void two();
3358 };
3359
3360 class Bar: public Foo {
3361 public:
3362     virtual void three();
3363 };
3364 </pre>
3365 </div>
3366
3367 <H3><a name="java_directors_classes"></a>21.5.2 Director classes</H3>
3368
3369
3370 <p>
3371 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. 
3372 These new classes, referred to as director classes, can be loosely thought of as the C++ equivalent of the Java proxy classes.
3373 The director classes store a pointer to their underlying Java proxy classes.
3374 </p>
3375
3376 <p>
3377 For simplicity let's ignore the <tt>Swig::Director</tt> class and refer to the original C++ class as the director's base class.
3378 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).
3379 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.
3380 The job of the director methods is to route these method calls to the appropriate place in the inheritance chain.
3381 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.
3382 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.
3383 </p>
3384
3385 <p>
3386 In reality, the "appropriate place" is one of only two possibilities: C++ or Java.
3387 Once this decision is made, the rest is fairly easy.
3388 If the correct implementation is in C++, then the lowest implementation of the method in the C++ inheritance chain is called explicitly.
3389 If the correct implementation is in Java, the Java API is used to call the method of the underlying Java object 
3390 (after which the usual virtual method resolution in Java automatically finds the right implementation).
3391 </p>
3392
3393
3394 <H3><a name="java_directors_overhead"></a>21.5.3 Overhead and code bloat</H3>
3395
3396
3397 <p>
3398 Enabling directors for a class will generate a new director method for every virtual method in the class' inheritance chain.
3399 This alone can generate a lot of code bloat for large hierarchies.
3400 Method arguments that require complex conversions to and from Java types can result in large director methods.
3401 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++.
3402 </p>
3403
3404 <p>
3405 Although directors make it natural to mix native C++ objects with Java objects (as director objects),
3406 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.
3407 Additionally, compared to classes that do not use directors, the call routing in the director methods adds a small overhead.
3408 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.
3409 </p>
3410
3411
3412 <H3><a name="java_directors_example"></a>21.5.4 Simple directors example</H3>
3413
3414
3415 <p>
3416 Consider the following SWIG interface file:
3417 </p>
3418
3419 <div class="code">
3420 <pre>
3421 %module(directors="1") example;
3422
3423 %feature("director") DirectorBase;
3424
3425 class DirectorBase {
3426 public:
3427   virtual ~DirectorBase() {}
3428   virtual void upcall_method() {}
3429 };
3430
3431 void callup(DirectorBase *director) {
3432   director-&gt;upcall_method();
3433 }
3434 </pre>
3435 </div>
3436
3437 <p>
3438 The following <code>DirectorDerived</code> Java class is derived from the Java proxy class <code>DirectorBase</code> and overrides <code>upcall_method()</code>.
3439 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.
3440 Naturally, the SWIG generated C++ code and the generated Java intermediate class marshal and convert arguments between C++ and Java when needed.
3441 </p>
3442
3443 <div class="code">
3444 <pre>
3445 public class DirectorDerived extends DirectorBase {
3446   public DirectorDerived() {
3447   }
3448
3449   public void upcall_method() {
3450     System.out.println("DirectorDerived::upcall_method() invoked.");
3451   }
3452 }
3453 </pre>
3454 </div>
3455
3456 <p>
3457 Running the following Java code
3458 </p>
3459
3460 <div class="code">
3461 <pre>
3462 DirectorDerived director = new DirectorDerived();
3463 example.callup(director);
3464 </pre>
3465 </div>
3466
3467 <p>
3468 will result in the following being output:
3469 </p>
3470
3471 <div class="code">
3472 <pre>
3473 DirectorDerived::upcall_method() invoked.
3474 </pre>
3475 </div>
3476
3477 <H3><a name="java_directors_threading"></a>21.5.5 Director threading issues</H3>
3478
3479
3480 <p>
3481 Depending on your operating system and version of Java and how you are using threads, you might find the JVM hangs on exit.
3482 There are a couple of solutions to try out. The preferred solution requires jdk-1.4 and later and uses <tt>AttachCurrentThreadAsDaemon</tt> instead of <tt>AttachCurrentThread</tt> whenever a call into the JVM is required. This can be enabled by defining the SWIG_JAVA_ATTACH_CURRENT_THREAD_AS_DAEMON macro when compiling the C++ wrapper code. For older JVMs define SWIG_JAVA_NO_DETACH_CURRENT_THREAD instead, to avoid the <tt>DetachCurrentThread</tt> call but this will result in a memory leak instead. For further details inspect the source code in the java/director.swg library file.
3483 </p>
3484
3485 <p>
3486 Macros can be defined on the commandline when compiling your C++ code, or alternatively added to the C++ wrapper file as shown below:
3487 </p>
3488
3489 <div class="code">
3490 <pre>
3491 %insert("runtime") %{
3492 #define SWIG_JAVA_NO_DETACH_CURRENT_THREAD
3493 %}
3494 </pre>
3495 </div>
3496
3497 <H2><a name="java_allprotected"></a>21.6 Accessing protected members</H2>
3498
3499
3500 <p>
3501 When using directors, the protected virtual methods are also wrapped. 
3502 These methods are wrapped with a protected Java proxy method, so the only way that Java code can access these is from within a Java class derived from the director class.
3503 </p>
3504
3505 <p>
3506 Members which are protected and non-virtual can also be accessed when using the 'allprotected' mode.
3507 The allprotected mode requires directors and is turned on by setting the <tt>allprotected</tt> option in addition to the <tt>directors</tt> option in the %module directive, like this:
3508 </p>
3509
3510 <div class="code">
3511 <pre>
3512 %module(directors="1", allprotected="1") modulename
3513 </pre>
3514 </div>
3515
3516 <p>
3517 Protected member variables and methods (both static and non-static) will then be wrapped with protected access in the Java proxy class.
3518 </p>
3519
3520 <p>
3521 <b>Note:</b> Neither the directors option nor the allprotected mode support types defined with protected scope.
3522 This includes any enums or typedefs declared in the protected section of the C++ class.
3523 </p>
3524
3525 <p>
3526 The following simple example is a class with numerous protected members, including the constructor and destructor:
3527 </p>
3528
3529 <div class="code">
3530 <pre>
3531 %module(directors="1", allprotected="1") example
3532
3533 %feature("director") ProtectedBase;
3534
3535 // Ignore use of unsupported types (those defined in the protected section)
3536 %ignore ProtectedBase::typedefs;
3537
3538 %inline %{
3539
3540 class ProtectedBase {
3541 protected:
3542   ProtectedBase() {}
3543   virtual ~ProtectedBase() {}
3544   virtual void virtualMethod() const {}
3545   void nonStaticMethod(double d) const {}
3546   static void staticMethod(int i) {}
3547   int instanceMemberVariable;
3548   static int staticMemberVariable;
3549
3550   // unsupported: types defined with protected access and the methods/variables which use them
3551   typedef int IntegerType;
3552   IntegerType typedefs(IntegerType it) { return it; }
3553 };
3554 int ProtectedBase::staticMemberVariable = 10;
3555
3556 %}
3557
3558 </pre>
3559 </div>
3560
3561 <p>
3562 Note that the <tt>IntegerType</tt> has protected scope and the members which use this type must be ignored as they cannot be wrapped.
3563 </p>
3564
3565 <p>
3566 The proxy methods are protected, so the only way the protected members can be accessed is within a class that derives from the director class, such as the following:
3567 </p>
3568
3569 <div class="code">
3570 <pre>
3571 class MyProtectedBase extends ProtectedBase
3572 {
3573   public MyProtectedBase() {
3574   }
3575
3576   public void accessProtected() {
3577     virtualMethod();
3578     nonStaticMethod(1.2);
3579     staticMethod(99);
3580
3581     setInstanceMemberVariable(5);
3582     int i = getInstanceMemberVariable();
3583
3584     setStaticMemberVariable(10);
3585     i = getStaticMemberVariable();
3586   }
3587 }
3588 </pre>
3589 </div>
3590
3591
3592
3593 <H2><a name="common_customization"></a>21.7 Common customization features</H2>
3594
3595
3596 <p>
3597 An earlier section presented the absolute basics of C/C++ wrapping. If you do nothing
3598 but feed SWIG a header file, you will get an interface that mimics the behavior
3599 described.  However, sometimes this isn't enough to produce a nice module.  Certain
3600 types of functionality might be missing or the interface to certain functions might
3601 be awkward.  This section describes some common SWIG features that are used
3602 to improve the interface to existing C/C++ code.
3603 </p>
3604
3605 <H3><a name="helper_functions"></a>21.7.1 C/C++ helper functions</H3>
3606
3607
3608 <p>
3609 Sometimes when you create a module, it is missing certain bits of functionality. For
3610 example, if you had a function like this
3611 </p>
3612
3613 <div class="code">
3614 <pre>
3615 typedef struct Image {...};
3616 void set_transform(Image *im, double m[4][4]);
3617 </pre>
3618 </div>
3619
3620 <p>
3621 it would be accessible from Java, but there may be no easy way to call it.
3622 The problem here is that a type wrapper class is generated for the two dimensional array parameter so
3623 there is no easy way to construct and manipulate a suitable
3624 <tt>double [4][4]</tt> value.   To fix this, you can write some extra C helper
3625 functions.  Just use the <tt>%inline</tt> directive. For example:
3626 </p>
3627
3628 <div class="code">
3629 <pre>
3630 %inline %{
3631 /* Note: double[4][4] is equivalent to a pointer to an array double (*)[4] */
3632 double (*new_mat44())[4] {
3633    return (double (*)[4]) malloc(16*sizeof(double));
3634 }
3635 void free_mat44(double (*x)[4]) {
3636    free(x);
3637 }
3638 void mat44_set(double x[4][4], int i, int j, double v) {
3639    x[i][j] = v;
3640 }
3641 double mat44_get(double x[4][4], int i, int j) {
3642    return x[i][j];
3643 }
3644 %}
3645 </pre>
3646 </div>
3647
3648 <p>
3649 From Java, you could then write code like this:
3650 </p>
3651
3652 <div class="code">
3653 <pre>
3654 Image im = new Image();
3655 SWIGTYPE_p_a_4__double a = example.new_mat44();
3656 example.mat44_set(a,0,0,1.0);
3657 example.mat44_set(a,1,1,1.0);
3658 example.mat44_set(a,2,2,1.0);
3659 ...
3660 example.set_transform(im,a);
3661 example.free_mat44(a);
3662 </pre>
3663 </div>
3664
3665 <p>
3666 Admittedly, this is not the most elegant looking approach.  However, it works and it wasn't too
3667 hard to implement.  It is possible to improve on this using Java code, typemaps, and other
3668 customization features as covered in later sections, but sometimes helper functions are a quick and easy solution to difficult cases.  
3669 </p>
3670
3671 <H3><a name="class_extension"></a>21.7.2 Class extension with %extend</H3>
3672
3673
3674 <p>
3675 One of the more interesting features of SWIG is that it can extend
3676 structures and classes with new methods or constructors.
3677 Here is a simple example:
3678 </p>
3679
3680 <div class="code">
3681 <pre>
3682 %module example
3683 %{
3684 #include "someheader.h"
3685 %}
3686
3687 struct Vector {
3688    double x,y,z;
3689 };
3690
3691 %extend Vector {
3692    char *toString() {
3693        static char tmp[1024];
3694        sprintf(tmp,"Vector(%g,%g,%g)", $self-&gt;x,$self-&gt;y,$self-&gt;z);
3695        return tmp;
3696    }
3697    Vector(double x, double y, double z) {
3698        Vector *v = (Vector *) malloc(sizeof(Vector));
3699        v-&gt;x = x;
3700        v-&gt;y = y;
3701        v-&gt;z = z;
3702        return v;
3703    }
3704 };
3705 </pre>
3706 </div>
3707
3708 <p>
3709 Now, in Java
3710 </p>
3711
3712 <div class="code">
3713 <pre>
3714 Vector v = new Vector(2,3,4);
3715 System.out.println(v);
3716 </pre>
3717 </div>
3718
3719 <p>
3720 will display
3721 </p>
3722
3723 <div class="code">
3724 <pre>
3725 Vector(2,3,4)
3726 </pre>
3727 </div>
3728
3729 <p>
3730 <tt>%extend</tt> works with both C and C++ code.  It does not modify the underlying object
3731 in any way---the extensions only show up in the Java interface.
3732 </p>
3733
3734 <H3><a name="exception_handling"></a>21.7.3 Exception handling with %exception and %javaexception</H3>
3735
3736
3737 <p>
3738 If a C or C++ function throws an error, you may want to convert that error into a Java
3739 exception. To do this, you can use the <tt>%exception</tt> directive.  The <tt>%exception</tt> directive
3740 simply lets you rewrite part of the generated wrapper code to include an error check.
3741 It is detailed in full in the <a href="Customization.html#exception">Exception handling with %exception</a> section.
3742 </p>
3743
3744 <p>
3745 In C, a function often indicates an error by returning a status code (a negative number
3746 or a NULL pointer perhaps).  Here is a simple example of how you might handle that:
3747 </p>
3748
3749 <div class="code">
3750 <pre>
3751 %exception malloc {
3752   $action
3753   if (!result) {
3754     jclass clazz = (*jenv)-&gt;FindClass(jenv, "java/lang/OutOfMemoryError");
3755     (*jenv)-&gt;ThrowNew(jenv, clazz, "Not enough memory");
3756     return $null;
3757   }
3758 }
3759 void *malloc(size_t nbytes);
3760 </pre>
3761 </div>
3762
3763 <p>
3764 In Java,
3765 </p>
3766
3767 <div class="code">
3768 <pre>
3769 SWIGTYPE_p_void a = example.malloc(2000000000);
3770 </pre>
3771 </div>
3772
3773 <p>
3774 will produce a familiar looking Java exception:
3775 </p>
3776
3777 <div class="code">
3778 <pre>
3779 Exception in thread "main" java.lang.OutOfMemoryError: Not enough memory
3780         at exampleJNI.malloc(Native Method)
3781         at example.malloc(example.java:16)
3782         at runme.main(runme.java:112)
3783 </pre>
3784 </div>
3785
3786 <p>
3787 If a library provides some kind of general error handling framework, you can also use
3788 that.  For example:
3789 </p>
3790
3791 <div class="code">
3792 <pre>
3793 %exception malloc {
3794   $action
3795   if (err_occurred()) {
3796     jclass clazz = (*jenv)-&gt;FindClass(jenv, "java/lang/OutOfMemoryError");
3797     (*jenv)-&gt;ThrowNew(jenv, clazz, "Not enough memory");
3798     return $null;
3799   }
3800 }
3801 void *malloc(size_t nbytes);
3802 </pre>
3803 </div>
3804
3805 <p>
3806 If no declaration name is given to <tt>%exception</tt>, it is applied to all wrapper functions.
3807 The <tt> $action </tt> is a SWIG special variable and is replaced by the C/C++ function call being wrapped.
3808 The <tt> return $null; </tt> handles all native method return types, namely those that have a void return and those that do not. 
3809 This is useful for typemaps that will be used in native method returning all return types. 
3810 See the section on
3811 <a href="#special_variables">Java special variables</a> for further explanation.
3812 </p>
3813
3814 <p>
3815 C++ exceptions are also easy to handle.  
3816 We can catch the C++ exception and rethrow it as a Java exception like this:</p>
3817
3818 <div class="code">
3819 <pre>
3820 %exception getitem {
3821   try {
3822      $action
3823   } catch (std::out_of_range &amp;e) {
3824     jclass clazz = jenv-&gt;FindClass("java/lang/Exception");
3825     jenv-&gt;ThrowNew(clazz, "Range error");
3826     return $null;
3827    }
3828 }
3829
3830 class FooClass {
3831 public:
3832      FooClass *getitem(int index);      // Might throw std::out_of_range exception
3833      ...
3834 };
3835 </pre>
3836 </div>
3837
3838 <p>
3839 In the example above, <tt>java.lang.Exception</tt> is a checked exception class and so ought to be declared in the throws clause of <tt>getitem</tt>.
3840 Classes can be specified for adding to the throws clause using <tt>%javaexception(classes)</tt> instead of <tt>%exception</tt>,
3841 where <tt>classes</tt> is a string containing one or more comma separated Java classes.
3842 The <tt>%clearjavaexception</tt> feature is the equivalent to <tt>%clearexception</tt> and clears previously declared exception handlers. 
3843 The <tt>%nojavaexception</tt> feature is the equivalent to <tt>%noexception</tt> and disables the exception handler.
3844 See <a href="Customization.html#Customization_clearing_features">Clearing features</a> for the difference on disabling and clearing features.
3845 </p>
3846
3847 <div class="code">
3848 <pre>
3849 %javaexception("java.lang.Exception") getitem {
3850   try {
3851      $action
3852   } catch (std::out_of_range &amp;e) {
3853     jclass clazz = jenv-&gt;FindClass("java/lang/Exception");
3854     jenv-&gt;ThrowNew(clazz, "Range error");
3855     return $null;
3856    }
3857 }
3858
3859 class FooClass {
3860 public:
3861      FooClass *getitem(int index);      // Might throw std::out_of_range exception
3862      ...
3863 };
3864 </pre>
3865 </div>
3866
3867 <p>
3868 The generated proxy method now generates a throws clause containing <tt>java.lang.Exception</tt>:
3869 </p>
3870
3871 <div class="code">
3872 <pre>
3873 public class FooClass {
3874   ...
3875   public FooClass getitem(int index) throws java.lang.Exception { ... }
3876   ...
3877 }
3878 </pre>
3879 </div>
3880
3881
3882 <p>
3883 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 vice versa.
3884 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. 
3885 </p>
3886
3887 <p>
3888 The language-independent <tt>exception.i</tt> library file can also be used
3889 to raise exceptions.  See the <a href="Library.html#Library">SWIG Library</a> chapter.
3890 The typemap example <a href="#exception_typemap">Handling C++ exception specifications as Java exceptions</a> provides further exception handling capabilities.
3891 </p>
3892
3893 <H3><a name="method_access"></a>21.7.4 Method access with %javamethodmodifiers</H3>
3894
3895
3896 <p>
3897 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:
3898 </p>
3899
3900 <div class="code">
3901 <pre>
3902 %javamethodmodifiers protect_me() "protected";
3903 void protect_me();
3904 </pre>
3905 </div>
3906
3907 <p>
3908 Will produce the method in the module class with protected access.
3909 </p>
3910
3911 <div class="code">
3912 <pre>
3913 protected static void protect_me() {
3914   exampleJNI.protect_me();
3915 }
3916 </pre>
3917 </div>
3918
3919 <H2><a name="tips_techniques"></a>21.8 Tips and techniques</H2>
3920
3921
3922 <p>
3923 Although SWIG is largely automatic, there are certain types of wrapping problems that
3924 require additional user input.    Examples include dealing with output parameters,
3925 strings and arrays.   This chapter discusses the common techniques for
3926 solving these problems.
3927 </p>
3928
3929 <H3><a name="input_output_parameters"></a>21.8.1 Input and output parameters using primitive pointers and references</H3>
3930
3931
3932 <p>
3933 A common problem in some C programs is handling parameters passed as simple pointers or references.  For
3934 example:
3935 </p>
3936
3937 <div class="code">
3938 <pre>
3939 void add(int x, int y, int *result) {
3940    *result = x + y;
3941 }
3942 </pre>
3943 </div>
3944
3945 <p>
3946 or perhaps
3947 </p>
3948
3949 <div class="code">
3950 <pre>
3951 int sub(int *x, int *y) {
3952    return *x-*y;
3953 }
3954 </pre>
3955 </div>
3956
3957 <p>
3958 The <tt>typemaps.i</tt> library file will help in these situations.  For example:
3959 </p>
3960
3961 <div class="code">
3962 <pre>
3963 %module example
3964 %include "typemaps.i"
3965
3966 void add(int, int, int *OUTPUT);
3967 int  sub(int *INPUT, int *INPUT);
3968 </pre>
3969 </div>
3970
3971 <p>
3972 In Java, this allows you to pass simple values.  For example:
3973 </p>
3974
3975 <div class="code">
3976 <pre>
3977 int result = example.sub(7,4);
3978 System.out.println("7 - 4 = " + result);
3979 int[] sum = {0};
3980 example.add(3,4,sum);
3981 System.out.println("3 + 4 = " + sum[0]);
3982 </pre>
3983 </div>
3984
3985 <p>
3986 Which will display:
3987 </p>
3988
3989 <div class="code"> <pre>
3990 7 - 4 = 3
3991 3 + 4 = 7
3992 </pre></div>
3993
3994 <p>
3995 Notice how the <tt>INPUT</tt> parameters allow integer values to be passed instead of pointers
3996 and how the <tt>OUTPUT</tt> parameter will return the result in the first element of the integer array.
3997 </p>
3998
3999 <p>
4000 If you don't want to use the names <tt>INPUT</tt> or <tt>OUTPUT</tt>, use the <tt>%apply</tt>
4001 directive.  For example:
4002 </p>
4003
4004 <div class="code">
4005 <pre>
4006 %module example
4007 %include "typemaps.i"
4008
4009 %apply int *OUTPUT { int *result };
4010 %apply int *INPUT  { int *x, int *y};
4011
4012 void add(int x, int y, int *result);
4013 int  sub(int *x, int *y);
4014 </pre>
4015 </div>
4016
4017 <p>
4018 If a function mutates one of its parameters like this,
4019 </p>
4020
4021 <div class="code">
4022 <pre>
4023 void negate(int *x) {
4024    *x = -(*x);
4025 }
4026 </pre>
4027 </div>
4028
4029 <p>
4030 you can use <tt>INOUT</tt> like this:
4031 </p>
4032
4033 <div class="code">
4034 <pre>
4035 %include "typemaps.i"
4036 ...
4037 void negate(int *INOUT);
4038 </pre>
4039 </div>
4040
4041 <p>
4042 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:
4043 </p>
4044
4045 <div class="code">
4046 <pre>
4047 int[] neg = {3};
4048 example.negate(neg);
4049 System.out.println("Negative of 3 = " + neg[0]);
4050 </pre>
4051 </div>
4052
4053 <p>
4054 And no prizes for guessing the output:
4055 </p>
4056
4057 <div class="code"><pre>
4058 Negative of 3 = -3
4059 </pre></div>
4060
4061 <p>
4062 These typemaps can also be applied to C++ references. 
4063 The above examples would work the same if they had been defined using references instead of pointers.
4064 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: 
4065 </p>
4066
4067 <div class="code">
4068 <pre>
4069 void negate(int *INOUT);
4070 </pre>
4071 </div>
4072
4073 <p>
4074 or using a reference:
4075 </p>
4076
4077 <div class="code">
4078 <pre>
4079 void negate(int &amp;INOUT);
4080 </pre>
4081 </div>
4082
4083 <p>
4084 Note: Since most Java primitive types are immutable and are passed by value, it is not possible to
4085 perform in-place modification of a type passed as a parameter.
4086 </p>
4087
4088 <p>
4089 Be aware that the primary purpose of the <tt>typemaps.i</tt> file is to support primitive datatypes.
4090 Writing a function like this
4091 </p>
4092
4093 <div class="code">
4094 <pre>
4095 void foo(Bar *OUTPUT);
4096 </pre>
4097 </div>
4098
4099 <p>
4100 will not have the intended effect since <tt>typemaps.i</tt> does not define an OUTPUT rule for <tt>Bar</tt>.
4101 </p>
4102
4103 <H3><a name="simple_pointers"></a>21.8.2 Simple pointers</H3>
4104
4105
4106 <p>
4107 If you must work with simple pointers such as <tt>int *</tt> or <tt>double *</tt> another approach to using 
4108 <tt>typemaps.i</tt> is to use the <tt>cpointer.i</tt> pointer library file.    For example:
4109 </p>
4110
4111 <div class="code">
4112 <pre>
4113 %module example
4114 %include "cpointer.i"
4115
4116 %inline %{
4117 extern void add(int x, int y, int *result);
4118 %}
4119
4120 %pointer_functions(int, intp);
4121 </pre>
4122 </div>
4123
4124 <p>
4125 The <tt>%pointer_functions(type,name)</tt> macro generates five helper functions that can be used to create,
4126 destroy, copy, assign, and dereference a pointer.  In this case, the functions are as follows:
4127 </p>
4128
4129 <div class="code">
4130 <pre>
4131 int  *new_intp();
4132 int  *copy_intp(int *x);
4133 void  delete_intp(int *x);
4134 void  intp_assign(int *x, int value);
4135 int   intp_value(int *x);
4136 </pre>
4137 </div>
4138
4139 <p>
4140 In Java, you would use the functions like this:
4141 </p>
4142
4143 <div class="code">
4144 <pre>
4145 SWIGTYPE_p_int intPtr = example.new_intp();
4146 example.add(3,4,intPtr);
4147 int result = example.intp_value(intPtr);
4148 System.out.println("3 + 4 = " + result);
4149 </pre>
4150 </div>
4151
4152 <p>
4153 If you replace <tt>%pointer_functions(int,intp)</tt> by <tt>%pointer_class(int,intp)</tt>, the interface is more class-like.
4154 </p>
4155
4156 <div class="code">
4157 <pre>
4158 intp intPtr = new intp();
4159 example.add(3,4,intPtr.cast());
4160 int result = intPtr.value();
4161 System.out.println("3 + 4 = " + result);
4162 </pre>
4163 </div>
4164
4165 <p>
4166 See the <a href="Library.html#Library">SWIG Library</a> chapter for further details.
4167 </p>
4168
4169 <H3><a name="c_arrays"></a>21.8.3 Wrapping C arrays with Java arrays</H3>
4170
4171
4172 <p>
4173 SWIG can wrap arrays in a more natural Java manner than the default by using the <tt>arrays_java.i</tt> library file. 
4174 Let's consider an example:
4175 </p>
4176
4177 <div class="code">
4178 <pre>
4179 %include "arrays_java.i";
4180 int array[4];
4181 void populate(int x[]) {
4182     int i;
4183     for (i=0; i&lt;4; i++)
4184         x[i] = 100 + i;
4185 }
4186 </pre>
4187 </div>
4188
4189 <p>
4190 These one dimensional arrays can then be used as if they were Java arrays:
4191 </p>
4192
4193 <div class="code">
4194 <pre>
4195 int[] array = new int[4];
4196 example.populate(array);
4197
4198 System.out.print("array: ");
4199 for (int i=0; i&lt;array.length; i++)
4200     System.out.print(array[i] + " ");
4201
4202 example.setArray(array);
4203
4204 int[] global_array = example.getArray();
4205
4206 System.out.print("\nglobal_array: ");
4207 for (int i=0; i&lt;array.length; i++)
4208     System.out.print(global_array[i] + " ");
4209 </pre>
4210 </div>
4211
4212 <p>
4213 Java arrays are always passed by reference, so any changes a function makes to the array will be seen by the calling function. 
4214 Here is the output after running this code:
4215 </p>
4216
4217 <div class="code">
4218 <pre>
4219 array: 100 101 102 103
4220 global_array: 100 101 102 103
4221 </pre>
4222 </div>
4223
4224 <p>
4225 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.
4226 Only the number of elements in the C array will be used.
4227 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.
4228 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.
4229 </p>
4230
4231 <p>
4232 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.
4233 There is an alternative approach using the SWIG array library and this is covered in the next section.
4234 </p>
4235
4236 <H3><a name="unbounded_c_arrays"></a>21.8.4 Unbounded C Arrays</H3>
4237
4238
4239 <p>
4240 Sometimes a C function expects an array to be passed as a pointer.  For example,
4241 </p>
4242
4243 <div class="code">
4244 <pre>
4245 int sumitems(int *first, int nitems) {
4246     int i, sum = 0;
4247     for (i = 0; i &lt; nitems; i++) {
4248         sum += first[i];
4249     }
4250     return sum;
4251 }
4252 </pre>
4253 </div>
4254
4255 <p>
4256 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:
4257 </p>
4258
4259 <div class="code">
4260 <pre>
4261 %include "arrays_java.i"
4262 %apply int[] {int *};
4263 </pre>
4264 </div>
4265
4266 <p>
4267 The <tt>ANY</tt> size will ensure the typemap is applied to arrays of all sizes.
4268 You could narrow the typemap matching rules by specifying a particular array size.
4269 Now you can use a pure Java array and pass it to the C code:
4270 </p>
4271
4272 <div class="code">
4273 <pre>
4274 int[] array = new int[10000000];          // Array of 10-million integers
4275 for (int i=0; i&lt;array.length; i++) {      // Set some values
4276   array[i] = i;
4277 }
4278 int sum = example.sumitems(array,10000);
4279 System.out.println("Sum = " + sum);
4280 </pre>
4281 </div>
4282
4283 <p>
4284 and the sum would be displayed:
4285 </p>
4286
4287 <div class="code">
4288 <pre>
4289 Sum = 49995000
4290 </pre>
4291 </div>
4292
4293 <p>
4294 This approach is probably the most natural way to use arrays.
4295 However, it suffers from performance problems when using large arrays as a lot of copying
4296 of the elements occurs in transferring the array from the Java world to the C++ world.
4297 An alternative approach to using Java arrays for C arrays is to use an alternative SWIG library file <tt>carrays.i</tt>.
4298 This approach can be more efficient for large arrays as the array is accessed one element at a time.
4299 For example:
4300 </p>
4301
4302 <div class="code">
4303 <pre>
4304 %include "carrays.i"
4305 %array_functions(int, intArray);
4306 </pre>
4307 </div>
4308
4309 <p>
4310 The <tt>%array_functions(type,name)</tt> macro generates four helper functions that can be used to create and
4311 destroy arrays and operate on elements.  In this case, the functions are as follows:
4312 </p>
4313
4314 <div class="code">
4315 <pre>
4316 int *new_intArray(int nelements);
4317 void delete_intArray(int *x);
4318 int intArray_getitem(int *x, int index);
4319 void intArray_setitem(int *x, int index, int value);
4320 </pre>
4321 </div>
4322
4323 <p>
4324 In Java, you would use the functions like this:
4325 </p>
4326
4327 <div class="code">
4328 <pre>
4329 SWIGTYPE_p_int array = example.new_intArray(10000000);  // Array of 10-million integers
4330 for (int i=0; i&lt;10000; i++) {                           // Set some values
4331     example.intArray_setitem(array,i,i);
4332 }
4333 int sum = example.sumitems(array,10000);
4334 System.out.println("Sum = " + sum);
4335 </pre>
4336 </div>
4337
4338 <p>
4339 If you replace <tt>%array_functions(int,intp)</tt> by <tt>%array_class(int,intp)</tt>, the interface is more class-like
4340 and a couple more helper functions are available for casting between the array and the type wrapper class.
4341 </p>
4342
4343 <div class="code">
4344 <pre>
4345 %include "carrays.i"
4346 %array_class(int, intArray);
4347 </pre>
4348 </div>
4349
4350 <p>
4351 The <tt>%array_class(type, name)</tt> macro creates wrappers for an unbounded array object that
4352 can be passed around as a simple pointer like <tt>int *</tt> or <tt>double *</tt>.
4353 For instance, you will be able to do this in Java:
4354 </p>
4355
4356 <div class="code">
4357 <pre>
4358 intArray array = new intArray(10000000);  // Array of 10-million integers
4359 for (int i=0; i&lt;10000; i++) {             // Set some values
4360     array.setitem(i,i);
4361 }
4362 int sum = example.sumitems(array.cast(),10000);
4363 System.out.println("Sum = " + sum);
4364 </pre>
4365 </div>
4366
4367 <p>
4368 The array "object" created by <tt>%array_class()</tt> does not
4369 encapsulate pointers inside a special array object.  In fact, there is
4370 no bounds checking or safety of any kind (just like in C).  Because of
4371 this, the arrays created by this library are extremely low-level
4372 indeed.  You can't iterate over them nor can you even query their
4373 length.  In fact, any valid memory address can be accessed if you want
4374 (negative indices, indices beyond the end of the array, etc.).
4375 Needless to say, this approach is not going to suit all applications.
4376 On the other hand, this low-level approach is extremely efficient and
4377 well suited for applications in which you need to create buffers,
4378 package binary data, etc.
4379 </p>
4380
4381 <H3><a name="java_heap_allocations"></a>21.8.5 Overriding new and delete to allocate from Java heap</H3>
4382
4383
4384 <p>
4385 Unlike some languages supported by SWIG, Java has a true garbage collection
4386 subsystem.  Other languages will free SWIG wrapped objects when their reference
4387 count reaches zero.  Java only schedules these objects for finalization, which
4388 may not occur for some time.  Because SWIG objects are allocated on the C
4389 heap, Java users may find the JVM memory use 
4390 quickly exceeds the assigned limits, as memory fills with unfinalized proxy
4391 objects.  Forcing garbage collection is clearly an undesirable solution.
4392 </p>
4393
4394 <p>
4395 An elegant fix for C++ users is to override new and delete using the following
4396 code (here shown included in a SWIG interface file)
4397 </p>
4398
4399 <div class="code">
4400 <pre>
4401 /* File: java_heap.i */
4402 %module test
4403 %{
4404 #include &lt;stdexcept&gt;
4405 #include "jni.h"
4406
4407 /**
4408  *  A stash area embedded in each allocation to hold java handles
4409  */
4410 struct Jalloc {
4411   jbyteArray jba;
4412   jobject ref;
4413 };
4414
4415 static JavaVM *cached_jvm = 0;
4416
4417 JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *jvm, void *reserved) {
4418   cached_jvm = jvm;
4419   return JNI_VERSION_1_2;
4420 }
4421
4422 static JNIEnv * JNU_GetEnv() {
4423   JNIEnv *env;
4424   jint rc = cached_jvm-&gt;GetEnv((void **)&amp;env, JNI_VERSION_1_2);
4425   if (rc == JNI_EDETACHED)
4426     throw std::runtime_error("current thread not attached");
4427   if (rc == JNI_EVERSION)
4428     throw std::runtime_error("jni version not supported");
4429   return env;
4430 }
4431
4432 void * operator new(size_t t) {
4433   if (cached_jvm != 0) {
4434     JNIEnv *env = JNU_GetEnv();
4435     jbyteArray jba = env-&gt;NewByteArray((int) t + sizeof(Jalloc));
4436     if (env-&gt;ExceptionOccurred())
4437       throw bad_alloc();
4438     void *jbuffer = static_cast&lt;void *&gt;(env-&gt;GetByteArrayElements(jba, 0));
4439     if (env-&gt;ExceptionOccurred())
4440       throw bad_alloc();
4441     Jalloc *pJalloc = static_cast&lt;Jalloc *&gt;(jbuffer);
4442     pJalloc-&gt;jba = jba;
4443     /* Assign a global reference so byte array will persist until delete'ed */
4444     pJalloc-&gt;ref = env-&gt;NewGlobalRef(jba);
4445     if (env-&gt;ExceptionOccurred())
4446       throw bad_alloc();
4447     return static_cast&lt;void *&gt;(static_cast&lt;char *&gt;(jbuffer) + sizeof(Jalloc));
4448   }
4449   else { /* JNI_OnLoad not called, use malloc and mark as special */
4450     Jalloc *pJalloc = static_cast&lt;Jalloc *&gt;(malloc((int) t + sizeof(Jalloc)));
4451     if (!pJalloc)
4452       throw bad_alloc();
4453     pJalloc-&gt;ref = 0;
4454     return static_cast&lt;void *&gt;(
4455         static_cast&lt;char *&gt;(static_cast&lt;void *&gt;(pJalloc)) + sizeof(Jalloc));
4456   }
4457 }
4458
4459 void operator delete(void *v) {
4460   if (v != 0) {
4461     void *buffer = static_cast&lt;void *&gt;( static_cast&lt;char *&gt;(v) - sizeof(Jalloc));
4462     Jalloc *pJalloc = static_cast&lt;Jalloc *&gt;(buffer);
4463     if (pJalloc-&gt;ref) {
4464       JNIEnv *env = JNU_GetEnv();
4465       env-&gt;DeleteGlobalRef(pJalloc-&gt;ref);
4466       env-&gt;ReleaseByteArrayElements(pJalloc-&gt;jba, static_cast&lt;jbyte *&gt;(buffer), 0);
4467     }
4468     else {
4469       free(buffer);
4470     }
4471   }
4472 }
4473 %}
4474 ...
4475 </pre>
4476 </div>
4477
4478 <p>
4479 This code caches the Java environment during initialization,
4480 and when new is called, a Java ByteArray is allocated to provide the
4481 SWIG objects with space in the Java heap.  This has the combined
4482 effect of re-asserting the Java virtual machine's limit on memory allocation,
4483 and puts additional pressure on the garbage collection system to run more
4484 frequently.
4485 This code is made slightly more complicated because allowances must be made
4486 if new is called before the JNI_OnLoad is executed.  This can happen during
4487 static class initialization, for example.  
4488 </p>
4489
4490 <p>
4491 Unfortunately, because most Java implementations call malloc and free, this
4492 solution will not work for C wrapped structures.  However, you are free to
4493 make functions that allocate and free memory from the Java heap using this
4494 model and use these functions in place of malloc and free in your own
4495 code.
4496 </p>
4497
4498 <H2><a name="java_typemaps"></a>21.9 Java typemaps</H2>
4499
4500
4501 <p>
4502 This section describes how you can modify SWIG's default wrapping behavior
4503 for various C/C++ datatypes using the <tt>%typemap</tt> directive.   
4504 You are advised to be familiar with the the material in the "<a href="Typemaps.html#Typemaps">Typemaps</a>" chapter.
4505 While not absolutely essential knowledge, this section assumes some familiarity with the Java Native Interface (JNI). 
4506 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. 
4507 The following two books are recommended:</p>
4508
4509 <ul>
4510 <li> Title: 'Essential JNI: Java Native Interface.' Author: Rob Gordon. Publisher: Prentice Hall. ISBN: 0-13-679895-0.  </li>
4511 <li> Title: 'The Java Native Interface: Programmer's Guide and Specification.' Author: Sheng Liang. Publisher: Addison-Wesley. ISBN: 0-201-32577-2.  Also available <a href="http://java.sun.com/docs/books/jni">online</a> at the Sun Developer Network.</li>
4512 </ul>
4513
4514 <p>
4515 Before proceeding, it should be stressed that typemaps are not a required 
4516 part of using SWIG---the default wrapping behavior is enough in most cases.
4517 Typemaps are only used if you want to change some aspect of the generated code.
4518
4519 <H3><a name="default_primitive_type_mappings"></a>21.9.1 Default primitive type mappings</H3>
4520
4521
4522 <p>
4523 The following table lists the default type mapping from Java to C/C++.</p>
4524
4525 <table BORDER summary="Default primitive type mappings">
4526 <tr>
4527 <td><b>C/C++ type</b></td>
4528 <td><b>Java type</b></td>
4529 <td><b>JNI type</b></td>
4530 </tr>
4531
4532 <tr>
4533 <td>bool<br> const bool &amp; </td>
4534 <td>boolean</td>
4535 <td>jboolean</td>
4536 </tr>
4537
4538 <tr>
4539 <td>char<br>const char &amp;</td>
4540 <td>char</td>
4541 <td>jchar</td>
4542 </tr>
4543
4544 <tr>
4545 <td>signed char<br>const signed char &amp;</td>
4546 <td>byte</td>
4547 <td>jbyte</td>
4548 </tr>
4549
4550 <tr>
4551 <td>unsigned char<br>const unsigned char &amp;</td>
4552 <td>short</td>
4553 <td>jshort</td>
4554 </tr>
4555
4556 <tr>
4557 <td>short<br>const short &amp;</td>
4558 <td>short</td>
4559 <td>jshort</td>
4560 </tr>
4561
4562 <tr>
4563 <td>unsigned short<br> const unsigned short &amp;</td>
4564 <td>int</td>
4565 <td>jint</td>
4566 </tr>
4567
4568 <tr>
4569 <td>int<br> const int &amp;</td>
4570 <td>int</td>
4571 <td>jint</td>
4572 </tr>
4573
4574 <tr>
4575 <td>unsigned int<br> const unsigned int &amp;</td>
4576 <td>long</td>
4577 <td>jlong</td>
4578 </tr>
4579
4580 <tr>
4581 <td>long<br>const long &amp;</td>
4582 <td>int</td>
4583 <td>jint</td>
4584 </tr>
4585
4586 <tr>
4587 <td>unsigned long<br>const unsigned long &amp;</td>
4588 <td>long</td>
4589 <td>jlong</td>
4590 </tr>
4591
4592 <tr>
4593 <td>long long<br> const long long &amp;</td>
4594 <td>long</td>
4595 <td>jlong</td>
4596 </tr>
4597
4598 <tr>
4599 <td>unsigned long long<br>const unsigned long long &amp;</td>
4600 <td>java.math.BigInteger</td>
4601 <td>jobject</td>
4602 </tr>
4603
4604 <tr>
4605 <td>float<br>const float &amp;</td>
4606 <td>float</td>
4607 <td>jfloat</td>
4608 </tr>
4609
4610 <tr>
4611 <td>double<br> const double &amp;</td>
4612 <td>double</td>
4613 <td>jdouble</td>
4614 </tr>
4615
4616 <tr>
4617 <td>char *<br>char []</td>
4618 <td>String</td>
4619 <td>jstring</td>
4620 </tr>
4621
4622 </table>
4623
4624 <p>
4625 Note that SWIG wraps the C <tt>char</tt> type as a character. Pointers and arrays of this type are wrapped as strings. 
4626 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.
4627 Also note that all const references to primitive types are treated as if they are passed by value.
4628 </p>
4629
4630 <p>
4631 Given the following C function:
4632 </p>
4633
4634 <div class="code"> <pre>
4635 void func(unsigned short a, char *b, const long &amp;c, unsigned long long d);
4636 </pre> </div>
4637
4638 <p>
4639 The module class method would be:
4640 </p>
4641
4642 <div class="code"> <pre>
4643 public static void func(int a, String b, int c, java.math.BigInteger d) {...}
4644 </pre> </div>
4645
4646 <p>
4647 The intermediary JNI class would use the same types:
4648 </p>
4649
4650 <div class="code"> <pre>
4651 public final static native void func(int jarg1, String jarg2, int jarg3,
4652                                      java.math.BigInteger jarg4);
4653 </pre> </div>
4654
4655 <p>
4656 and the JNI function would look like this:
4657 </p>
4658
4659 <div class="code"> <pre>
4660 SWIGEXPORT void JNICALL Java_exampleJNI_func(JNIEnv *jenv, jclass jcls,
4661                 jint jarg1, jstring jarg2, jint jarg3, jobject jarg4) {...}
4662 </pre> </div>
4663
4664 <p>
4665 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. 
4666 There is no perfect mapping between Java and C as Java doesn't support all the unsigned C data types. 
4667 However, the mappings allow the full range of values for each C type from Java. 
4668 </p>
4669
4670
4671 <H3><a name="Java_default_non_primitive_typemaps"></a>21.9.2 Default typemaps for non-primitive types</H3>
4672
4673
4674 <p>
4675 The previous section covered the primitive type mappings.
4676 Non-primitive types such as classes and structs are mapped using pointers on the C/C++ side and storing the pointer into a Java <tt>long</tt> variable which is held by
4677 the proxy class or type wrapper class. This applies whether the type is marshalled as a pointer, by reference or by value.
4678 It also applies for any unknown/incomplete types which use type wrapper classes.
4679 </p>
4680
4681 <p>
4682 So in summary, the C/C++ pointer to non-primitive types is cast into the 64 bit Java <tt>long</tt> type and therefore the JNI type is a <tt>jlong</tt>.
4683 The Java type is either the proxy class or type wrapper class.
4684 </p>
4685
4686 <H3><a name="jvm64"></a>21.9.3 Sixty four bit JVMs</H3>
4687
4688
4689 <p>
4690 If you are using a 64 bit JVM you may have to override the C long, but probably not C int default mappings. 
4691 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 
4692 Microsoft 64 bit Windows which will be using a P64 IL32 (pointer 64 bits and int, long 32 bits) model. 
4693 This may be automated in a future version of SWIG. 
4694 Note that the Java write once run anywhere philosophy holds true for all pure Java code when moving to a 64 bit JVM. 
4695 Unfortunately it won't of course hold true for JNI code.
4696 </p>
4697
4698
4699 <H3><a name="what_is_typemap"></a>21.9.4 What is a typemap?</H3>
4700
4701
4702 <p>
4703 A typemap is nothing more than a code generation rule that is attached to 
4704 a specific C datatype.   For example, to convert integers from Java to C,
4705 you might define a typemap like this:
4706 </p>
4707
4708 <div class="code"><pre>
4709 %module example
4710
4711 %typemap(in) int {
4712   $1 = $input;
4713   printf("Received an integer : %d\n",  $1);
4714 }
4715 %inline %{
4716 extern int fact(int nonnegative);
4717 %}
4718 </pre></div>
4719
4720 <p>
4721 Typemaps are always associated with some specific aspect of code generation.
4722 In this case, the "in" method refers to the conversion of input arguments
4723 to C/C++.  The datatype <tt>int</tt> is the datatype to which the typemap
4724 will be applied.  The supplied C code is used to convert values.  In this
4725 code a number of special variables prefaced by a <tt>$</tt> are used.  The
4726 <tt>$1</tt> variable is a placeholder for a local variable of type <tt>int</tt>.
4727 The <tt>$input</tt> variable contains the Java data, the JNI <tt>jint</tt> in this case.
4728 </p>
4729
4730 <p>
4731 When this example is compiled into a Java module, it can be used as follows:
4732 </p>
4733
4734 <div class="code"><pre>
4735 System.out.println(example.fact(6));
4736 </pre></div>
4737
4738 <p>
4739 and the output will be:
4740 </p>
4741
4742 <div class="code"><pre>
4743 Received an integer : 6
4744 720
4745 </pre></div>
4746
4747 <p>
4748 In this example, the typemap is applied to all occurrences of the <tt>int</tt> datatype.
4749 You can refine this by supplying an optional parameter name.  For example:
4750 </p>
4751
4752 <div class="code"><pre>
4753 %module example
4754
4755 %typemap(in) int nonnegative {
4756   $1 = $input;
4757   printf("Received an integer : %d\n",  $1);
4758 }
4759
4760 %inline %{
4761 extern int fact(int nonnegative);
4762 %}
4763 </pre></div>
4764
4765 <p>
4766 In this case, the typemap code is only attached to arguments that exactly match <tt>int nonnegative</tt>.
4767 </p>
4768
4769 <p>
4770 The application of a typemap to specific datatypes and argument names involves
4771 more than simple text-matching--typemaps are fully integrated into the
4772 SWIG C++ type-system.   When you define a typemap for <tt>int</tt>, that typemap
4773 applies to <tt>int</tt> and qualified variations such as <tt>const int</tt>.  In addition,
4774 the typemap system follows <tt>typedef</tt> declarations.  For example:
4775 </p>
4776
4777 <div class="code">
4778 <pre>
4779 %typemap(in) int nonnegative {
4780   $1 = $input;
4781   printf("Received an integer : %d\n",  $1);
4782 }
4783 %inline %{
4784 typedef int Integer;
4785 extern int fact(Integer nonnegative);    // Above typemap is applied
4786 %}
4787 </pre>
4788 </div>
4789
4790 <p>
4791 However, the matching of <tt>typedef</tt> only occurs in one direction.  If you
4792 defined a typemap for <tt>Integer</tt>, it is not applied to arguments of
4793 type <tt>int</tt>.
4794 </p>
4795
4796 <p>
4797 Typemaps can also be defined for groups of consecutive arguments.  For example:
4798 </p>
4799
4800 <div class="code">
4801 <pre>
4802 %typemap(in) (char *str, int len) {
4803 ...
4804 };
4805
4806 int count(char c, char *str, int len);
4807 </pre>
4808 </div>
4809
4810 <p>
4811 When a multi-argument typemap is defined, the arguments are always handled as a single
4812 Java parameter.  This allows the function to be used like this (notice how the length
4813 parameter is omitted):
4814 </p>
4815
4816 <div class="code">
4817 <pre>
4818 int c = example.count('e',"Hello World");
4819 </pre>
4820 </div>
4821
4822 <H3><a name="typemaps_c_to_java_types"></a>21.9.5 Typemaps for mapping C/C++ types to Java types</H3>
4823
4824
4825 <p>
4826 The typemaps available to the Java module include the common typemaps listed in the main typemaps section. 
4827 There are a number of additional typemaps which are necessary for using SWIG with Java.
4828 The most important of these implement the mapping of C/C++ types to Java types:
4829 </p>
4830
4831 <br>&nbsp;
4832 <table BORDER summary="Typemap mappings for C/C++ types to Java types">
4833 <tr>
4834 <td><b>Typemap</b></td>
4835
4836 <td><b>Description</b></td>
4837 </tr>
4838
4839 <tr>
4840 <td>jni</td>
4841 <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>
4842 </tr>
4843
4844 <tr>
4845 <td>jtype</td>
4846 <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>
4847 </tr>
4848
4849 <tr>
4850 <td>jstype</td>
4851 <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>
4852 </tr>
4853
4854 <tr>
4855 <td>javain</td>
4856 <td>Conversion from jstype to jtype. 
4857     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)
4858     to the type used in the Java intermediary JNI class (as specified in the "jtype" typemap).
4859     In other words the typemap provides the conversion to the native method call parameter types.</td>
4860 </tr>
4861
4862 <tr>
4863 <td>javaout</td>
4864 <td>Conversion from jtype to jstype.
4865     These are Java code typemaps which transform the type used in the Java intermediary JNI class (as specified in the "jtype" typemap) to 
4866     the Java type used in the Java module class, proxy classes and type wrapper classes (as specified in the "jstype" typemap).
4867     In other words the typemap provides the conversion from the native method call return type. </td>
4868 </tr>
4869
4870 <tr>
4871 <td>javadirectorin</td>
4872 <td>Conversion from jtype to jstype for director methods.
4873     These are Java code typemaps which transform the type used in the Java intermediary JNI class (as specified in the "jtype" typemap) to 
4874     the Java type used in the Java module class, proxy classes and type wrapper classes (as specified in the "jstype" typemap).
4875     This typemap provides the conversion for the parameters in the director methods when calling up from C++ to Java.
4876     See <a href="#java_directors_typemaps">Director typemaps</a>.  </td>
4877 </tr>
4878
4879 <tr>
4880 <td>javadirectorout</td>
4881 <td>Conversion from jstype to jtype for director methods.
4882     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)
4883     to the type used in the Java intermediary JNI class (as specified in the "jtype" typemap).
4884     This typemap provides the conversion for the return type in the director methods when returning from the C++ to Java upcall.
4885     See <a href="#java_directors_typemaps">Director typemaps</a>.  </td>
4886 </tr>
4887
4888 <tr>
4889 <td>directorin</td>
4890 <td>Conversion from C++ type to jni type for director methods.
4891   These are C++ typemaps which convert the parameters used in the C++ director method to the appropriate JNI intermediary type.
4892   The conversion is done in JNI code prior to calling the Java function from the JNI code.
4893   See <a href="#java_directors_typemaps">Director typemaps</a>. </td>
4894 </tr>
4895
4896 <tr>
4897 <td>directorout</td>
4898 <td>Conversion from jni type to C++ type for director methods.
4899   These are C++ typemaps which convert the JNI return type used in the C++ director method to the appropriate C++ return type.
4900   The conversion is done in JNI code after calling the Java function from the JNI code.
4901   See <a href="#java_directors_typemaps">Director typemaps</a>. </td>
4902 </tr>
4903
4904 </table>
4905
4906 <p>
4907 If you are writing your own typemaps to handle a particular type, you will normally have to write a collection of them. 
4908 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.
4909 </p>
4910
4911 <p>
4912 The "jni", "jtype" and "jstype" typemaps are usually defined together to handle the Java to C/C++ type mapping.
4913 An "in" typemap should be accompanied by a "javain" typemap and likewise an "out" typemap by a "javaout" typemap.
4914 If an "in" typemap is written, a "freearg" and "argout" typemap may also need to be written
4915 as some types have a default "freearg" and/or "argout" typemap which may need overriding. 
4916 The "freearg" typemap sometimes releases memory allocated by the "in" typemap. 
4917 The "argout" typemap sometimes sets values in function parameters which are passed by reference in Java. 
4918 </p>
4919
4920 <p>
4921 Note that the "in" typemap marshals the JNI type held in the "jni" typemap to the real C/C++ type and for the opposite direction,
4922 the "out" typemap marshals the real C/C++ type to the JNI type held in the "jni" typemap.
4923 For <a href="#Java_default_non_primitive_typemaps">non-primitive types</a> 
4924 the "in" and "out" typemaps are responsible for casting between the C/C++ pointer and the 64 bit <tt>jlong</tt> type.
4925 There is no portable way to cast a pointer into a 64 bit integer type and the approach taken by SWIG is mostly portable, but breaks C/C++ aliasing rules.
4926 In summary, these rules state that a pointer to any type must never be dereferenced by a pointer to any other incompatible type.
4927 The following code snippet might aid in understand aliasing rules better:
4928 </p>
4929
4930 <div class="code"><pre>
4931     short a;
4932     short* pa = 0;
4933     int i = 0x1234;
4934
4935     a = (short)i;    /* okay */
4936     a = *(short*)&amp;i; /* breaks aliasing rules */
4937 </pre></div>
4938
4939 <p>
4940 An email posting, <a href="http://mail-index.netbsd.org/tech-kern/2003/08/11/0001.html">Aliasing, pointer casts and gcc 3.3</a> elaborates further on the subject.
4941 In SWIG, the "in" and "out" typemaps for pointers are typically
4942 </p>
4943
4944 <div class="code"><pre>
4945     %typemap(in) struct Foo * %{
4946       $1 = *(struct Foo **)&amp;$input; /* cast jlong into C ptr */
4947     %}
4948     %typemap(out) struct Bar * %{
4949       *(struct Bar **)&amp;$result = $1; /* cast C ptr into jlong */
4950     %} 
4951     struct Bar {...};
4952     struct Foo {...};
4953     struct Bar * FooBar(struct Foo *f);
4954 </pre></div>
4955
4956 <p>
4957 resulting in the following code which breaks the aliasing rules:
4958 </p>
4959
4960 <div class="code"><pre>
4961 SWIGEXPORT jlong JNICALL Java_exampleJNI_FooBar(JNIEnv *jenv, jclass jcls,
4962                                                 jlong jarg1, jobject jarg1_) {
4963   jlong jresult = 0 ;
4964   struct Foo *arg1 = (struct Foo *) 0 ;
4965   struct Bar *result = 0 ;
4966   
4967   (void)jenv;
4968   (void)jcls;
4969   (void)jarg1_;
4970   arg1 = *(struct Foo **)&amp;jarg1; 
4971   result = (struct Bar *)FooBar(arg1);
4972   *(struct Bar **)&amp;jresult = result; 
4973   return jresult;
4974 }
4975 </pre></div>
4976
4977 <p>
4978 If you are using gcc as your C compiler, you might get a "dereferencing type-punned pointer will break strict-aliasing rules" warning about this.
4979 Please see <a href="#compiling_dynamic">Compiling a dynamic module</a> to avoid runtime problems with these strict aliasing rules.
4980 </p>
4981
4982 <p>
4983 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 
4984 <a href="#default_primitive_type_mappings">Default primitive type mappings</a> and 
4985 <a href="#Java_default_non_primitive_typemaps">Default typemaps for non-primitive types</a> covered earlier.
4986 There are other type mapping typemaps in the Java library. 
4987 These are listed below:
4988 </p>
4989
4990 <br>&nbsp;
4991 <table BORDER summary="Java library typemap mappings">
4992 <tr VALIGN=TOP>
4993 <td><b>C Type</b></td>
4994 <td><b>Typemap</b></td>
4995 <td><b>File</b></td>
4996 <td><b>Kind</b></td>
4997 <td><b>Java Type</b></td>
4998 <td><b>Function</b></td>
4999 </tr>
5000
5001 <tr>
5002 <td>primitive pointers and references</td>
5003 <td>INPUT</td>
5004 <td>typemaps.i</td>
5005 <td>input</td>
5006 <td>Java basic types</td>
5007 <td>Allows values to be used for C functions taking pointers for data input.
5008
5009 <tr>
5010 <td>primitive pointers and references</td>
5011 <td>OUTPUT</td>
5012 <td>typemaps.i</td>
5013 <td>output</td>
5014 <td>Java basic type arrays</td>
5015 <td>Allows values held within an array to be used for C functions taking pointers for data output.
5016
5017 <tr>
5018 <td>primitive pointers and references</td>
5019 <td>INOUT</td>
5020 <td>typemaps.i</td>
5021 <td>input<br>output</td>
5022 <td>Java basic type arrays</td>
5023 <td>Allows values held within an array to be used for C functions taking pointers for data input and output.
5024
5025 <tr>
5026 <td>string <br>wstring</td>
5027 <td>[unnamed]</td>
5028 <td>std_string.i</td>
5029 <td>input<br> output</td>
5030 <td>String</td>
5031 <td>Use for std::string mapping to Java String.</td>
5032 </tr>
5033
5034 <tr>
5035 <td>arrays of primitive types</td>
5036 <td>[unnamed]</td>
5037 <td>arrays_java.i</td>
5038 <td>input<br> output</td>
5039 <td>arrays of primitive Java types</td>
5040 <td>Use for mapping C arrays to Java arrays.</td>
5041 </tr>
5042
5043 <tr>
5044 <td>arrays of classes/structs/unions</td>
5045 <td>JAVA_ARRAYSOFCLASSES macro</td>
5046 <td>arrays_java.i</td>
5047 <td>input<br> output</td>
5048 <td>arrays of proxy classes</td>
5049 <td>Use for mapping C arrays to Java arrays.</td>
5050 </tr>
5051
5052 <tr>
5053 <td>arrays of enums</td>
5054 <td>ARRAYSOFENUMS</td>
5055 <td>arrays_java.i</td>
5056 <td>input<br> output</td>
5057 <td>int[]</td>
5058 <td>Use for mapping C arrays to Java arrays (typeunsafe and simple enum wrapping approaches only).</td>
5059 </tr>
5060
5061 <tr VALIGN=TOP>
5062 <td>char *</td>
5063 <td>BYTE</td>
5064 <td>various.i</td>
5065 <td>input</td>
5066 <td>byte[]</td>
5067
5068 <td VALIGN=TOP>Java byte array is converted to char array</td>
5069 </tr>
5070
5071 <tr>
5072 <td>char **</td>
5073 <td>STRING_ARRAY</td>
5074 <td>various.i</td>
5075 <td>input<br> output</td>
5076 <td>String[]</td>
5077 <td>Use for mapping NULL terminated arrays of C strings to Java String arrays</td>
5078 </tr>
5079
5080 </table>
5081
5082 <H3><a name="typemap_attributes"></a>21.9.6 Java typemap attributes</H3>
5083
5084
5085 <p>
5086 There are a few additional typemap attributes that the Java module supports.
5087 </p>
5088
5089 <p>
5090 The first of these is the 'throws' attribute.
5091 The throws attribute is optional and specified after the typemap name and contains one or more comma separated classes for adding to the throws clause for any methods that use that typemap.
5092 It is analogous to the <a href="#exception_handling">%javaexception</a> feature's throws attribute.
5093 </p>
5094
5095 <div class="code">
5096 <pre>
5097 %typemap(typemapname, throws="ExceptionClass1, ExceptionClass2") type { ... }
5098 </pre>
5099 </div>
5100
5101 <p>
5102 The attribute is necessary for supporting Java checked exceptions and can be added to just about any typemap.
5103 The list of typemaps include all the C/C++ (JNI) typemaps in the "<a href="Typemaps.html#Typemaps">Typemaps</a>" chapter and the
5104 Java specific typemaps listed in <a href="#typemaps_c_to_java_types">the previous section</a>, barring
5105 the "jni", "jtype" and "jstype" typemaps as they could never contain code to throw an exception.
5106 </p>
5107
5108 <p>
5109 The throws clause is generated for the proxy method as well as the JNI method in the JNI intermediary class.
5110 If a method uses more than one typemap and each of those typemaps have classes specified in the throws clause,
5111 the union of the exception classes is added to the throws clause ensuring there are no duplicate classes.
5112 See the <a href="#nan_exception_typemap">NaN exception example</a> for further usage.
5113 </p>
5114
5115 <p>
5116 The "jtype" typemap has the optional 'nopgcpp' attribute which can be used to suppress the generation of the <a href="java_pgcpp">premature garbage collection prevention parameter</a>.
5117 </p>
5118
5119 <p>
5120 The "javain" typemap has the optional 'pre', 'post' and 'pgcppname' attributes. These are used for generating code before and after the JNI call in the proxy class or module class. The 'pre' attribute contains code that is generated before the JNI call and the 'post' attribute contains code generated after the JNI call. The 'pgcppname' attribute is used to change the <a href="java_pgcpp">premature garbage collection prevention parameter</a> name passed to the JNI function. This is sometimes needed when the 'pre' typemap creates a temporary variable which is then passed to the JNI function.
5121 </p>
5122
5123 <p>
5124 <a name="java_constructor_helper_function"></a>
5125 Note that when the 'pre' or 'post' attributes are specified and the associated type is used in a constructor, a constructor helper function is generated. This is necessary as the Java proxy constructor wrapper makes a call to a support constructor using a <i>this</i> call. In Java the <i>this</i> call must be the first statement in the constructor body. The constructor body thus calls the helper function and the helper function instead makes the JNI call, ensuring the 'pre' code is called before the JNI call is made. There is a <a href="#java_date_marshalling">Date marshalling</a> example showing 'pre', 'post' and 'pgcppname' attributes in action.
5126 </p>
5127
5128 <H3><a name="special_variables"></a>21.9.7 Java special variables</H3>
5129
5130
5131 <p>
5132 The standard SWIG special variables are available for use within typemaps as described in the <a href="Typemaps.html#Typemaps">Typemaps documentation</a>, for example <tt>$1</tt>, <tt>$input</tt>,<tt>$result</tt> etc.
5133 </p>
5134
5135 <p>
5136 The Java module uses a few additional special variables:
5137 </p>
5138
5139 <p>
5140 <b><tt>$javaclassname</tt></b><br>
5141 This special variable works like the other <a href="Typemaps.html#Typemaps_special_variables">special variables</a>
5142 and <tt>$javaclassname</tt> is similar to <tt>$1_type</tt>. It expands to the class name for use in Java given a pointer. 
5143 SWIG wraps unions, structs and classes using pointers and in this case it expands to the Java proxy class name.
5144 For example, <tt>$javaclassname</tt> is replaced by the proxy classname <tt>Foo</tt> when wrapping a <tt>Foo *</tt> and 
5145 <tt>$&amp;javaclassname</tt> expands to the proxy classname when wrapping the C/C++ type <tt>Foo</tt> and <tt>$*javaclassname</tt>
5146 expands to the proxy classname when wrapping <tt>Foo *&amp;</tt>.
5147 If the type does not have an associated proxy class, it expands to the type wrapper class name, for example,
5148 <tt>SWIGTYPE_p_unsigned_short</tt> is generated when wrapping <tt>unsigned short *</tt>.
5149 </p>
5150
5151 <p>
5152 <b><tt>$null </tt></b><br>
5153 Used in input typemaps to return early from JNI functions that have either void or a non-void return type. Example:
5154 </p>
5155
5156 <div class="code"><pre>
5157 %typemap(check) int * %{ 
5158   if (error) {
5159     SWIG_JavaThrowException(jenv, SWIG_JavaIndexOutOfBoundsException, "Array element error");
5160     return $null;
5161   }
5162 %}
5163 </pre></div>
5164
5165 <p>
5166 If the typemap gets put into a function with void as return, $null will expand to nothing:
5167 </p>
5168
5169 <div class="code"><pre>
5170 SWIGEXPORT void JNICALL Java_jnifn(...) {
5171     if (error) {
5172       SWIG_JavaThrowException(jenv, SWIG_JavaIndexOutOfBoundsException, "Array element error");
5173       return ;
5174     }
5175   ...
5176 }
5177 </pre></div>
5178
5179 <p>
5180 otherwise $null expands to <i>NULL</i>
5181 </p>
5182
5183 <div class="code"><pre>
5184 SWIGEXPORT jobject JNICALL Java_jnifn(...) {
5185     if (error) {
5186       SWIG_JavaThrowException(jenv, SWIG_JavaIndexOutOfBoundsException, "Array element error");
5187       return NULL;
5188     }
5189   ...
5190 }
5191 </pre></div>
5192
5193 <p>
5194 <b><tt>$javainput, $jnicall and $owner</tt></b><br>
5195 The $javainput special variable is used in "javain" typemaps and $jnicall and $owner are used in "javaout" typemaps.
5196 $jnicall is analogous to $action in %exception. It is replaced by the call to the native method in the intermediary JNI class.
5197 $owner is replaced by either <tt>true</tt> if %newobject has been used, otherwise <tt>false</tt>.
5198 $javainput is analogous to the $input special variable. It is replaced by the parameter name.
5199 </p>
5200
5201 <p>
5202 Here is an example:
5203 </p>
5204
5205 <div class="code"><pre>
5206 %typemap(javain) Class "Class.getCPtr($javainput)"
5207 %typemap(javain) unsigned short "$javainput"
5208 %typemap(javaout) Class * {
5209     return new Class($jnicall, $owner);
5210   }
5211
5212 %inline %{
5213     class Class {...};
5214     Class * bar(Class cls, unsigned short ush) { return new Class(); };
5215 %}
5216 </pre></div>
5217
5218 <p>
5219 The generated proxy code is then:
5220 </p>
5221
5222 <div class="code"><pre>
5223 public static Class bar(Class cls, int ush) {
5224   return new Class(exampleJNI.bar(Class.getCPtr(cls), cls, ush), false);
5225 }
5226 </pre></div>
5227
5228 <p>
5229 Here $javainput has been replaced by <tt>cls</tt> and <tt>ush</tt>. $jnicall has been replaced by 
5230 the native method call, <tt>exampleJNI.bar(...)</tt> and $owner has been replaced by <tt>false</tt>.
5231 If %newobject is used by adding the following at the beginning of our example:
5232 </p>
5233
5234 <div class="code"><pre>
5235 %newobject bar(Class cls, unsigned short ush);
5236 </pre></div>
5237
5238 <p>
5239 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>:
5240 </p>
5241
5242 <div class="code"><pre>
5243 public static Class bar(Class cls, int ush) {
5244   return new Class(exampleJNI.bar(Class.getCPtr(cls), cls, ush), true);
5245 }
5246 </pre></div>
5247
5248 <p>
5249 <b><tt>$static</tt></b><br>
5250 This special variable expands to either <i>static</i> or nothing depending on whether the class is an inner Java class or not.
5251 It is used in the "javaclassmodifiers" typemap so that global classes can be wrapped as Java proxy classes and nested C++ classes/enums
5252 can be wrapped with the Java equivalent, that is, static inner proxy classes.
5253 </p>
5254
5255 <p>
5256 <b><tt>$jniinput, $javacall and $packagepath</tt></b><br>
5257 These special variables are used in the directors typemaps. See <a href="#java_directors_typemaps">Director specific typemaps</a> for details.
5258 </p>
5259
5260 <p>
5261 <b><tt>$module</tt></b><br>
5262 This special variable expands to the module name, as specified by <tt>%module</tt> or the <tt>-module</tt> commandline option.
5263 </p>
5264
5265 <p>
5266 <b><tt>$imclassname</tt></b><br>
5267 This special variable expands to the intermediary class name. Usually this is the same as '$moduleJNI',
5268 unless the jniclassname attribute is specified in the <a href="Java.html#java_module_directive">%module directive</a>.
5269 </p>
5270
5271 <H3><a name="typemaps_for_c_and_cpp"></a>21.9.8 Typemaps for both C and C++ compilation</H3>
5272
5273
5274 <p>
5275 JNI calls must be written differently depending on whether the code is being compiled as C or C++. 
5276 For example C compilation requires the pointer to a function pointer struct member syntax like
5277 </p>
5278
5279 <div class="code"><pre>
5280 const jclass clazz = (*jenv)-&gt;FindClass(jenv, "java/lang/String");
5281 </pre></div>
5282
5283 <p>
5284 whereas C++ code compilation of the same function call is a member function call using a class pointer like
5285 </p>
5286
5287 <div class="code"><pre>
5288 const jclass clazz = jenv-&gt;FindClass("java/lang/String");
5289 </pre></div>
5290
5291 <p>
5292 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, 
5293 where x is the number of arguments in the C++ version of the JNI call. 
5294 The above JNI calls would be written in a typemap like this
5295 </p>
5296
5297 <div class="code"><pre>
5298 const jclass clazz = JCALL1(FindClass, jenv, "java/lang/String");
5299 </pre></div>
5300
5301 <p>
5302 Note that the SWIG preprocessor expands these into the appropriate C or C++ JNI calling convention. 
5303 The C calling convention is emitted by default and the C++ calling convention is emitted when using the -c++ SWIG commandline option. 
5304 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.
5305 </p>
5306
5307
5308 <H3><a name="java_code_typemaps"></a>21.9.9 Java code typemaps</H3>
5309
5310
5311 <p>
5312 Most of SWIG's typemaps are used for the generation of C/C++ code. 
5313 The typemaps in this section are used solely for the generation of Java code. 
5314 Elements of proxy classes and type wrapper classes come from the following typemaps (the defaults).
5315 </p>
5316
5317 <p><tt>%typemap(javabase)</tt></p>
5318 <div class="indent">
5319 base (extends) for Java class: empty default
5320 <br>
5321 Note that this typemap accepts a <tt>replace</tt> attribute as an optional flag. When set to "1", it will replace/override any C++ base classes
5322 that might have been parsed. If this flag is not specified and there are C++ base classes, then a multiple inheritance warning
5323 is issued and the code in the typemap is ignored.
5324 The typemap also accepts a <tt>notderived</tt> attribute as an optional flag. When set to "1", it will not apply to classes that
5325 are derived from a C++ base. 
5326 When used with the SWIGTYPE type, it is useful for giving a common base for all proxy classes, that is, providing a base class that sits in between all proxy classes and the Java base class <tt>Object</tt> for example: <tt>%typemap(javabase, notderived="1") SWIGTYPE "CommonBase"</tt>.
5327 </div>
5328
5329 <p><tt>%typemap(javabody)</tt></p>
5330 <div class="indent">
5331   the essential support body for proxy classes (proxy base classes only), typewrapper classes and enum classes.
5332   Default contains extra constructors, memory ownership control member variables (<tt>swigCMemOwn</tt>, <tt>swigCPtr</tt>), the <tt>getCPtr</tt> method etc.
5333 </div>
5334
5335 <p><tt>%typemap(javabody_derived)</tt></p>
5336 <div class="indent">
5337   the essential support body for proxy classes (derived classes only).
5338   Same as "javabody" typemap, but only used for proxy derived classes.
5339 </div>
5340
5341 <p><tt>%typemap(javaclassmodifiers)</tt></p>
5342 <div class="indent">
5343 class modifiers for the Java class: default is "public class"
5344 </div>
5345
5346 <p><tt>%typemap(javacode)</tt></p>
5347 <div class="indent">
5348 Java code is copied verbatim to the Java class: empty default
5349 </div>
5350
5351 <p><tt>%typemap(javadestruct, methodname="delete", methodmodifiers="public synchronized")</tt> <br></p>
5352 <div class="indent">
5353 destructor wrapper - the <tt>delete()</tt> method (proxy classes only),
5354 used for all proxy classes except those which have a base class
5355 : default calls C++ destructor (or frees C memory) and resets <tt>swigCPtr</tt> and <tt>swigCMemOwn</tt> flags
5356 <br>
5357 <br>
5358 Note that the <tt>delete()</tt> method name is configurable and is specified by the <tt>methodname</tt> attribute.
5359 The method modifiers are also configurable via the <tt>methodmodifiers</tt> attribute.
5360 </div>
5361
5362 <p><tt>%typemap(javadestruct_derived, methodname="delete", methodmodifiers="public synchronized")</tt></p>
5363 <div class="indent">
5364 destructor wrapper - the <tt>delete()</tt> method (proxy classes only),
5365 same as "javadestruct" but only used for derived proxy classes
5366 : default calls C++ destructor (or frees C memory) and resets <tt>swigCPtr</tt> and <tt>swigCMemOwn</tt> flags
5367 <br>
5368 <br>
5369 Note that the <tt>delete()</tt> method name is configurable and is specified by the <tt>methodname</tt> attribute.
5370 The method modifiers are also configurable via the <tt>methodmodifiers</tt> attribute.
5371 </div>
5372
5373 <p><tt>%typemap(javaimports)</tt></p>
5374 <div class="indent">
5375 import statements for Java class: empty default
5376 </div>
5377
5378 <p><tt>%typemap(javainterfaces)</tt></p>
5379 <div class="indent">
5380 interfaces (extends) for Java class: empty default
5381 </div>
5382
5383 <p><tt>%typemap(javafinalize)</tt></p>
5384 <div class="indent">
5385 the <tt>finalize()</tt> method (proxy classes only): default calls the <tt>delete()</tt> method
5386 </div>
5387
5388 <p>
5389 <b>Compatibility Note:</b> In SWIG-1.3.21 and earlier releases, typemaps called "javagetcptr" and "javaptrconstructormodifiers" were available.
5390 These are deprecated and the "javabody" typemap can be used instead.
5391 </p>
5392
5393 <p>
5394 In summary the contents of the typemaps make up a proxy class like this:
5395 </p>
5396
5397 <div class="code">
5398 <pre>
5399 [ javaimports typemap ]
5400 [ javaclassmodifiers typemap ] javaclassname extends [ javabase typemap ]
5401                                              implements [ javainterfaces typemap ] {
5402 [ javabody or javabody_derived typemap ]
5403 [ javafinalize typemap ]
5404 public synchronized void <i>delete</i>() [ javadestruct OR javadestruct_derived typemap ]
5405 [ javacode typemap ]
5406 ... proxy functions ...
5407 }
5408 </pre>
5409 </div>
5410
5411 <p>
5412 Note the <tt><i>delete</i>()</tt> methodname and method modifiers are configurable, see "javadestruct" and "javadestruct_derived" typemaps above.
5413 </p>
5414
5415 <p>
5416 The type wrapper class is similar in construction:
5417 </p>
5418
5419 <div class="code">
5420 <pre>
5421 [ javaimports typemap ]
5422 [ javaclassmodifiers typemap ] javaclassname extends [ javabase typemap ]
5423                                              implements [ javainterfaces typemap ] {
5424 [ javabody typemap ]
5425 [ javacode typemap ]
5426 }
5427 </pre>
5428 </div>
5429
5430 <p>The enum class is also similar in construction:</p>
5431 <div class="code">
5432 <pre>
5433 [ javaimports typemap ]
5434 [ javaclassmodifiers typemap ] javaclassname extends [ javabase typemap ]
5435                                              implements [ javainterfaces typemap ] {
5436 ... Enum values ...
5437 [ javabody typemap ]
5438 [ javacode typemap ]
5439 }
5440 </pre>
5441 </div>
5442
5443 <p>
5444 The "javaimports" typemap is ignored if the enum class is wrapped by an inner Java class, that is when wrapping an enum declared within a C++ class.
5445 </p>
5446
5447 <p>
5448 The defaults can be overridden to tailor these classes.
5449 Here is an example which will change the <tt>getCPtr</tt> method and constructor from the default protected access to public access. 
5450 This has a practical application if you are invoking SWIG more than once and generating the wrapped classes into different packages in each invocation.
5451 If the classes in one package are using the classes in another package, then these methods need to be public.
5452 </p>
5453
5454 <div class="code">
5455 <pre>
5456 %typemap(javabody) SWIGTYPE %{
5457   private long swigCPtr;
5458   protected boolean swigCMemOwn;
5459
5460   public $javaclassname(long cPtr, boolean cMemoryOwn) {
5461     swigCMemOwn = cMemoryOwn;
5462     swigCPtr = cPtr;
5463   }
5464
5465   public static long getCPtr($javaclassname obj) {
5466     return (obj == null) ? 0 : obj.swigCPtr;
5467   }
5468 %}
5469 </pre>
5470 </div>
5471
5472 <p>
5473 The typemap code is the same that is in "<tt>java.swg</tt>", barring the two method modifiers.
5474 Note that <tt>SWIGTYPE</tt> will target all proxy classes, but not the type wrapper classes.
5475 Also the above typemap is only used for proxy classes that are potential base classes.
5476 To target proxy classes that are derived from a wrapped class as well, the "javabody_derived" typemap should also be overridden.
5477 </p>
5478
5479 <p>
5480 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:
5481 </p>
5482
5483 <div class="code">
5484 <pre>
5485 %typemap(javabody) SWIGTYPE *, SWIGTYPE &amp;, SWIGTYPE [], SWIGTYPE (CLASS::*) %{
5486   private long swigCPtr;
5487
5488   public $javaclassname(long cPtr, boolean bFutureUse) {
5489     swigCPtr = cPtr;
5490   }
5491
5492   protected $javaclassname() {
5493     swigCPtr = 0;
5494   }
5495
5496   public static long getCPtr($javaclassname obj) {
5497     return (obj == null) ? 0 : obj.swigCPtr;
5498   }
5499 %}
5500 </pre>
5501 </div>
5502
5503 <p>
5504 Again this is the same that is in "<tt>java.swg</tt>", barring the method modifier for <tt>getCPtr</tt>.
5505 </p>
5506
5507 <H3><a name="java_directors_typemaps"></a>21.9.10 Director specific typemaps</H3>
5508
5509
5510 <p>
5511 The Java directors feature requires the "javadirectorin", "javadirectorout", "directorin" and the "directorout" typemaps in order to work properly.
5512 The "javapackage" typemap is an optional typemap used to identify the Java package path for individual SWIG generated proxy classes.
5513 </p>
5514
5515 <p><tt>%typemap(directorin)</tt></p>
5516 <div class="indent">
5517
5518 <p>
5519 The "directorin" typemap is used for converting arguments in the C++ director class to the appropriate JNI type before the upcall to Java.
5520 This typemap also specifies the JNI field descriptor for the type in the "descriptor" attribute.
5521 For example, integers are converted as follows:
5522 </p>
5523
5524 <div class="code">
5525 <pre>
5526 %typemap(directorin,descriptor="I") int "$input = (jint) $1;"
5527 </pre>
5528 </div>
5529
5530 <p>
5531 <code>$input</code> is the SWIG name of the JNI temporary variable passed to Java in the upcall.
5532 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++.
5533 For more about JNI field descriptors and their importance, refer to the <a href="#java_typemaps">JNI documentation mentioned earlier</a>.
5534 A typemap for C character strings is:
5535 </p>
5536
5537 <div class="code">
5538 <pre>
5539 %typemap(directorin,descriptor="Ljava/lang/String;") char *
5540   %{ $input = jenv-&gt;NewStringUTF($1); %}
5541 </pre>
5542 </div>
5543
5544
5545 <p>
5546 User-defined types have the default "descriptor" attribute "<code>L$packagepath/$javaclassname;</code>" where <code>$packagepath</code> 
5547 is the package name passed from the SWIG command line and <code>$javaclassname</code> is the Java proxy class' name.
5548 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.
5549 <b>Do not forget the terminating ';' for JNI field descriptors starting with 'L'.</b>
5550 If the ';' is left out, Java will generate a "method not found" runtime error.
5551 </p>
5552 </div>
5553
5554
5555 <p><tt>%typemap(directorout)</tt></p>
5556 <div class="indent">
5557
5558 <p>
5559 The "directorout" typemap is used for converting the JNI return type in the C++ director class to the appropriate C++ type after the upcall to Java.
5560 For example, integers are converted as follows:
5561 </p>
5562
5563 <div class="code">
5564 <pre>
5565 %typemap(directorout) int %{ $result = (int)$input; %}
5566 </pre>
5567 </div>
5568
5569 <p>
5570 <code>$input</code> is the SWIG name of the JNI temporary variable returned from Java after the upcall.
5571 <code>$result</code> is the resulting output.
5572 A typemap for C character strings is:
5573 </p>
5574
5575 <div class="code">
5576 <pre>
5577 %typemap(directorout) char * {
5578   $1 = 0;
5579   if ($input) {
5580     $result = (char *)jenv-&gt;GetStringUTFChars($input, 0);
5581     if (!$1) return $null;
5582   }
5583 }
5584 </pre>
5585 </div>
5586
5587 </div>
5588
5589
5590 <p><tt>%typemap(javadirectorin)</tt></p>
5591 <div class="indent">
5592
5593 <p>
5594 Conversion from jtype to jstype for director methods.
5595 These are Java code typemaps which transform the type used in the Java intermediary JNI class (as specified in the "jtype" typemap) to 
5596 the Java type used in the Java module class, proxy classes and type wrapper classes (as specified in the "jstype" typemap).
5597 This typemap provides the conversion for the parameters in the director methods when calling up from C++ to Java.
5598 </p>
5599
5600 <p>
5601 For primitive types, this typemap is usually specified as:
5602 </p>
5603
5604 <div class="code">
5605 <pre>
5606 %typemap(javadirectorin) int "$jniinput"
5607 </pre>
5608 </div>
5609
5610 <p>
5611 The <code>$jniinput</code> special variable is analogous to <code>$javainput</code> special variable.
5612 It is replaced by the input parameter name.
5613 </p>
5614
5615 </div>
5616
5617
5618 <p><tt>%typemap(javadirectorout)</tt></p>
5619 <div class="indent">
5620
5621 <p>
5622 Conversion from jstype to jtype for director methods.
5623 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)
5624 to the type used in the Java intermediary JNI class (as specified in the "jtype" typemap).
5625 This typemap provides the conversion for the return type in the director methods when returning from the C++ to Java upcall.
5626 </p>
5627
5628 <p>
5629 For primitive types, this typemap is usually specified as:
5630 </p>
5631
5632 <div class="code">
5633 <pre>
5634 %typemap(javadirectorout) int "$javacall"
5635 </pre>
5636 </div>
5637
5638 <p>
5639 The <code>$javacall</code> special variable is analogous to the <code>$jnicall</code> special variable.
5640 It is replaced by the call to the target Java method.
5641 The target method is the method in the Java proxy class which overrides the virtual C++ method in the C++ base class.
5642 </p>
5643
5644 </div>
5645
5646 <p><tt>%typemap(javapackage)</tt></p>
5647 <div class="indent">
5648
5649
5650 <p>
5651 The "javapackage" typemap is optional; it serves to identify a class's Java package.
5652 This typemap should be used in conjunction with classes that are defined outside of the current SWIG interface file.
5653 For example:
5654 </p>
5655
5656 <div class="code">
5657 <pre>
5658 // class Foo is handled in a different interface file:
5659 %import "Foo.i"
5660
5661 %feature("director") Example;
5662
5663 %inline {
5664   class Bar { };
5665
5666   class Example {
5667   public:
5668     virtual ~Example();
5669     void     ping(Foo *arg1, Bar *arg2);
5670   };
5671 }
5672 </pre>
5673 </div>
5674
5675 <p>
5676 Assume that the Foo class is part of the Java package <i>com.wombat.foo</i> but the above interface file is part of the Java package <i>com.wombat.example</i>.
5677 Without the "javapackage" typemap, SWIG will assume that the Foo class belongs to <i>com.wombat.example</i> class.
5678 The corrected interface file looks like:
5679 </p>
5680
5681 <div class="code">
5682 <pre>
5683 // class Foo is handled in a different interface file:
5684 %import "Foo.i"
5685 %typemap("javapackage") Foo, Foo *, Foo &amp; "com.wombat.foo";
5686 %feature("director") Example;
5687
5688 %inline {
5689   class Bar { };
5690
5691   class Example {
5692   public:
5693     virtual ~Example();
5694     void     ping(Foo *arg1, Bar *arg2);
5695   };
5696 }
5697 </pre>
5698 </div>
5699
5700 <p>
5701 SWIG looks up the package based on the <b>actual</b> type (plain Foo, Foo pointer and Foo reference), so it is important to associate all three types with the desired package.
5702 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.
5703 Note the helper macros below, <code>OTHER_PACKAGE_SPEC</code> and <code>ANOTHER_PACKAGE_SPEC</code>, which reduce the amount of extra typing.
5704 "<code>TYPE...</code>" is useful when passing templated types to the macro, since multiargument template types appear to the SWIG preprocessor as multiple macro arguments.
5705 </p>
5706
5707 <div class="code">
5708 <pre>
5709 %typemap("javapackage") SWIGTYPE, SWIGTYPE *, SWIGTYPE &amp;
5710                                             "package.for.most.classes";
5711
5712 %define OTHER_PACKAGE_SPEC(TYPE...)
5713 %typemap("javapackage") TYPE, TYPE *, TYPE &amp; "package.for.other.classes";
5714 %enddef
5715
5716 %define ANOTHER_PACKAGE_SPEC(TYPE...)
5717 %typemap("javapackage") TYPE, TYPE *, TYPE &amp; "package.for.another.set";
5718 %enddef
5719
5720 OTHER_PACKAGE_SPEC(Package_2_class_one)
5721 ANOTHER_PACKAGE_SPEC(Package_3_class_two)
5722 /* etc */
5723 </pre>
5724 </div>
5725
5726 <p>
5727 The basic strategy here is to provide a default package typemap for the majority of the classes, only providing "javapackage" typemaps for the exceptions.
5728 </p>
5729
5730 </div>
5731
5732 <H2><a name="typemap_examples"></a>21.10 Typemap Examples</H2>
5733
5734
5735 <p>
5736 This section includes a few examples of typemaps.  For more examples, you
5737 might look at the files "<tt>java.swg</tt>" and "<tt>typemaps.i</tt>" in
5738 the SWIG library.
5739 </p>
5740
5741
5742 <H3><a name="simpler_enum_classes"></a>21.10.1 Simpler Java enums for enums without initializers</H3>
5743
5744
5745 <p>
5746 The default <a href="#proper_enums_classes">Proper Java enums</a> approach to wrapping enums is somewhat verbose.
5747 This is to handle all possible C/C++ enums, in particular enums with initializers.
5748 The generated code can be simplified if the enum being wrapped does not have any initializers.
5749 </p>
5750
5751 <p>
5752 The following shows how to remove the support methods that are generated by default and instead use the methods in the Java
5753 enum base class <tt>java.lang.Enum</tt> and <tt>java.lang.Class</tt> for marshalling enums between C/C++ and Java.
5754 The type used for the typemaps below is <tt>enum SWIGTYPE</tt> which is the default type used for all enums.
5755 The "enums.swg" file should be examined in order to see the original overridden versions of the typemaps.
5756 </p>
5757
5758 <div class="code">
5759 <pre>
5760 %include "enums.swg"
5761
5762 %typemap(javain) enum SWIGTYPE "$javainput.ordinal()"
5763 %typemap(javaout) enum SWIGTYPE {
5764     return $javaclassname.class.getEnumConstants()[$jnicall];
5765   }
5766 %typemap(javabody) enum SWIGTYPE ""
5767
5768 %inline %{
5769   enum HairType { blonde, ginger, brunette };
5770   void setHair(HairType h);
5771   HairType getHair();
5772 %}
5773 </pre>
5774 </div>
5775
5776 <p>
5777 SWIG will generate the following Java enum, which is somewhat simpler than the default:
5778 </p>
5779
5780 <div class="code">
5781 <pre>
5782 public enum HairType {
5783   blonde,
5784   ginger,
5785   brunette;
5786 }
5787 </pre>
5788 </div>
5789
5790 <p>
5791 and the two Java proxy methods will be:
5792 </p>
5793
5794 <div class="code">
5795 <pre>
5796 public static void setHair(HairType h) {
5797   exampleJNI.setHair(h.ordinal());
5798 }
5799
5800 public static HairType getHair() {
5801   return HairType.class.getEnumConstants()[exampleJNI.getHair()];
5802 }
5803 </pre>
5804 </div>
5805
5806 <p>
5807 For marshalling Java enums to C/C++ enums, the <tt>ordinal</tt> method is used to convert the
5808 Java enum into an integer value for passing to the JNI layer, see the "javain" typemap.
5809 For marshalling C/C++ enums to Java enums, the C/C++ enum value is cast to an integer in the C/C++ typemaps (not shown).
5810 This integer value is then used to index into the array of enum constants that the Java language provides.
5811 See the <tt>getEnumConstants</tt> method in the "javaout" typemap.
5812 </p>
5813
5814 <p>
5815 These typemaps can often be used as the default for wrapping enums as in many cases there won't be any enum initializers.
5816 In fact a good strategy is to always use these typemaps and to specifically handle enums with initializers using %apply.
5817 This would be done by using the original versions of these typemaps in "enums.swg" under another typemap name for applying using %apply.
5818 </p>
5819
5820
5821 <H3><a name="exception_typemap"></a>21.10.2 Handling C++ exception specifications as Java exceptions</H3>
5822
5823
5824 <p>
5825 This example demonstrates various ways in which C++ exceptions can be tailored and converted into Java exceptions.
5826 Let's consider a simple file class <tt>SimpleFile</tt> and an exception class <tt>FileException</tt> which it may throw on error:
5827 </p>
5828
5829 <div class="code">
5830 <pre>
5831 %include "std_string.i" // for std::string typemaps
5832 #include &lt;string&gt;
5833
5834 class FileException {
5835   std::string message;
5836 public:
5837   FileException(const std::string&amp; msg) : message(msg) {}
5838   std::string what() {
5839     return message;
5840   }
5841 };
5842
5843 class SimpleFile {
5844   std::string filename;
5845 public:
5846   SimpleFile(const std::string&amp; filename) : filename(filename) {}
5847   void open() throw(FileException) {
5848   ...
5849   }
5850 };
5851 </pre>
5852 </div>
5853
5854 <p>
5855 As the <tt>open</tt> method has a C++ exception specification, SWIG will parse this and know that the method can throw an exception.
5856 The <a href="Typemaps.html#throws_typemap">"throws" typemap</a> is then used when SWIG encounters an exception specification.
5857 The default generic "throws" typemap looks like this:
5858 </p>
5859
5860 <div class="code">
5861 <pre>
5862 %typemap(throws) SWIGTYPE, SWIGTYPE &amp;, SWIGTYPE *, SWIGTYPE [ANY] %{
5863   SWIG_JavaThrowException(jenv, SWIG_JavaRuntimeException,
5864                           "C++ $1_type exception thrown");
5865   return $null;
5866 %}
5867 </pre>
5868 </div>
5869
5870 <p>
5871 Basically SWIG will generate a C++ try catch block and the body of the "throws" typemap constitutes the catch block.
5872 The above typemap calls a SWIG supplied method which throws a <tt>java.lang.RuntimeException</tt>.
5873 This exception class is a runtime exception and therefore not a checked exception.
5874 If, however, we wanted to throw a checked exception, say <tt>java.io.IOException</tt>, then we could use the following typemap:
5875 </p>
5876
5877 <div class="code">
5878 <pre>
5879 %typemap(throws, throws="java.io.IOException") FileException {
5880   jclass excep = jenv-&gt;FindClass("java/io/IOException");
5881   if (excep)
5882     jenv-&gt;ThrowNew(excep, $1.what().c_str());
5883   return $null;
5884 }
5885 </pre>
5886 </div>
5887
5888 <p>
5889 Note that this typemap uses the 'throws' <a href="#typemap_attributes">typemap attribute</a> to ensure a throws clause is generated.
5890 The generated proxy method then specifies the checked exception by containing <tt>java.io.IOException</tt> in the throws clause:
5891 </p>
5892
5893 <div class="code">
5894 <pre>
5895 public class SimpleFile {
5896   ...
5897   public void open() throws java.io.IOException { ... }
5898 }
5899 </pre>
5900 </div>
5901
5902 <p>
5903 Lastly, if you don't want to map your C++ exception into one of the standard Java exceptions, the C++ class can be wrapped and turned into a custom Java exception class.
5904 If we go back to our example, the first thing we must do is get SWIG to wrap <tt>FileException</tt> and ensure that it derives from <tt>java.lang.Exception</tt>.
5905 Additionally, we might want to override the <tt>java.lang.Exception.getMessage()</tt> method.
5906 The typemaps to use then are as follows:
5907 </p>
5908
5909 <div class="code">
5910 <pre>
5911 %typemap(javabase) FileException "java.lang.Exception";
5912 %typemap(javacode) FileException %{
5913   public String getMessage() {
5914     return what();
5915   }
5916 %}
5917 </pre>
5918 </div>
5919
5920 <p>
5921 This generates:
5922 </p>
5923
5924 <div class="code">
5925 <pre>
5926 public class FileException extends java.lang.Exception {
5927   ...
5928   public String getMessage() {
5929     return what();
5930   }
5931
5932   public FileException(String msg) { ... }
5933
5934   public String what() {
5935     return exampleJNI.FileException_what(swigCPtr, this);
5936   }
5937 }
5938 </pre>
5939 </div>
5940
5941 <p>
5942 We could alternatively have used <tt>%rename</tt> to rename <tt>what()</tt> into <tt>getMessage()</tt>.
5943 </p>
5944
5945
5946 <H3><a name="nan_exception_typemap"></a>21.10.3 NaN Exception - exception handling for a particular type</H3>
5947
5948
5949 <p>
5950 A Java exception can be thrown from any Java or JNI code.
5951 Therefore, as most typemaps contain either Java or JNI code, just about any typemap could throw an exception.
5952 The following example demonstrates exception handling on a type by type basis by checking for 'Not a number' (NaN) whenever a parameter of type <tt>float</tt> is wrapped.
5953 </p>
5954
5955 <p>
5956 Consider the following C++ code:
5957 </p>
5958
5959 <div class="code">
5960 <pre>
5961 bool calculate(float first, float second);
5962 </pre>
5963 </div>
5964
5965 <p>
5966 To validate every <tt>float</tt> being passed to C++, we could precede the code being wrapped by the following typemap which throws a runtime exception whenever the <tt>float</tt> is 'Not a Number':
5967 </p>
5968
5969 <div class="code">
5970 <pre>
5971 %module example
5972 %typemap(javain) float "$module.CheckForNaN($javainput)"
5973 %pragma(java) modulecode=%{
5974   /** Simply returns the input value unless it is not a number,
5975       whereupon an exception is thrown. */
5976   static protected float CheckForNaN(float num) {
5977     if (Float.isNaN(num))
5978       throw new RuntimeException("Not a number");
5979     return num;
5980   }
5981 %}
5982 </pre>
5983 </div>
5984
5985 <p>
5986 Note that the <tt>CheckForNaN</tt> support method has been added to the module class using the <tt>modulecode</tt> pragma.
5987 The following shows the generated code of interest:
5988 </p>
5989
5990 <div class="code">
5991 <pre>
5992 public class example {
5993   ...
5994
5995   /** Simply returns the input value unless it is not a number,
5996       whereupon an exception is thrown. */
5997   static protected float CheckForNaN(float num) {
5998     if (Float.isNaN(num))
5999       throw new RuntimeException("Not a number");
6000     return num;
6001   }
6002
6003   public static boolean calculate(float first, float second) {
6004     return exampleJNI.calculate(example.CheckForNaN(first), example.CheckForNaN(second));
6005   }
6006 }
6007 </pre>
6008 </div>
6009
6010 <p>
6011 Note that the "javain" typemap is used for every occurrence of a <tt>float</tt> being used as an input.
6012 Of course, we could have targeted the typemap at a particular parameter by using <tt>float first</tt>, say, instead of just <tt>float</tt>.
6013 </p>
6014
6015 <p>
6016 The exception checking could alternatively have been placed into the 'pre' attribute that the "javain" typemap supports.
6017 The "javain" typemap above could be replaced with the following:
6018 </p>
6019
6020 <div class="code">
6021 <pre>
6022 %typemap(javain, pre="    $module.CheckForNaN($javainput);") float "$javainput"
6023 </pre>
6024 </div>
6025
6026 <p>
6027 which would modify the <tt>calculate</tt> function to instead be generated as:
6028 </p>
6029
6030 <div class="code">
6031 <pre>
6032 public class example {
6033   ...
6034   public static boolean calculate(float first, float second) {
6035     example.CheckForNaN(first);
6036     example.CheckForNaN(second);
6037     {
6038       return exampleJNI.calculate(first, second);
6039     }
6040   }
6041 }
6042 </pre>
6043 </div>
6044
6045 <p>
6046 See the <a href="#java_date_marshalling">Date marshalling example</a> for an example using further "javain" typemap attributes.
6047 </p>
6048
6049 <p>
6050 If we decide that what we actually want is a checked exception instead of a runtime exception, we can change this easily enough.
6051 The proxy method that uses <tt>float</tt> as an input, must then add the exception class to the throws clause.
6052 SWIG can handle this as it supports the 'throws' <a href="#typemap_attributes">typemap attribute</a> for specifying classes for the throws clause.
6053 Thus we can modify the pragma and the typemap for the throws clause:
6054 </p>
6055
6056 <div class="code">
6057 <pre>
6058 %typemap(javain, throws="java.lang.Exception") float "$module.CheckForNaN($javainput)"
6059 %pragma(java) modulecode=%{
6060   /** Simply returns the input value unless it is not a number,
6061       whereupon an exception is thrown. */
6062   static protected float CheckForNaN(float num) throws java.lang.Exception {
6063     if (Float.isNaN(num))
6064       throw new RuntimeException("Not a number");
6065     return num;
6066   }
6067 %}
6068 </pre>
6069 </div>
6070
6071 <p>
6072 The <tt>calculate</tt> method now has a throws clause and even though the typemap is used twice for both <tt>float first</tt> and <tt>float second</tt>,
6073 the throws clause contains a single instance of <tt>java.lang.Exception</tt>:
6074 </p>
6075
6076 <div class="code">
6077 <pre>
6078 public class example {
6079   ...
6080
6081   /** Simply returns the input value unless it is not a number,
6082       whereupon an exception is thrown. */
6083   static protected float CheckForNaN(float num) throws java.lang.Exception {
6084     if (Float.isNaN(num))
6085       throw new RuntimeException("Not a number");
6086     return num;
6087   }
6088
6089   public static boolean calculate(float first, float second) throws java.lang.Exception {
6090     return exampleJNI.calculate(example.CheckForNaN(first), example.CheckForNaN(second));
6091   }
6092 }
6093 </pre>
6094 </div>
6095
6096 <p>
6097 If we were a martyr to the JNI cause, we could replace the succinct code within the "javain" typemap with a few pages of JNI code.
6098 If we had, we would have put it in the "in" typemap which, like all JNI and Java typemaps, also supports the 'throws' attribute.
6099 </p>
6100
6101 <H3><a name="converting_java_string_arrays"></a>21.10.4 Converting Java String arrays to char ** </H3>
6102
6103
6104 <p>
6105 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.   
6106 The following SWIG interface file allows a Java String array to be used as a <tt>char **</tt> object.
6107 </p>
6108
6109 <div class="code"><pre>
6110 %module example
6111
6112 /* This tells SWIG to treat char ** as a special case when used as a parameter
6113    in a function call */
6114 %typemap(in) char ** (jint size) {
6115     int i = 0;
6116     size = (*jenv)-&gt;GetArrayLength(jenv, $input);
6117     $1 = (char **) malloc((size+1)*sizeof(char *));
6118     /* make a copy of each string */
6119     for (i = 0; i&lt;size; i++) {
6120         jstring j_string = (jstring)(*jenv)-&gt;GetObjectArrayElement(jenv, $input, i);
6121         const char * c_string = (*jenv)-&gt;GetStringUTFChars(jenv, j_string, 0);
6122         $1[i] = malloc((strlen(c_string)+1)*sizeof(char));
6123         strcpy($1[i], c_string);
6124         (*jenv)-&gt;ReleaseStringUTFChars(jenv, j_string, c_string);
6125         (*jenv)-&gt;DeleteLocalRef(jenv, j_string);
6126     }
6127     $1[i] = 0;
6128 }
6129
6130 /* This cleans up the memory we malloc'd before the function call */
6131 %typemap(freearg) char ** {
6132     int i;
6133     for (i=0; i&lt;size$argnum-1; i++)
6134       free($1[i]);
6135     free($1);
6136 }
6137
6138 /* This allows a C function to return a char ** as a Java String array */
6139 %typemap(out) char ** {
6140     int i;
6141     int len=0;
6142     jstring temp_string;
6143     const jclass clazz = (*jenv)-&gt;FindClass(jenv, "java/lang/String");
6144
6145     while ($1[len]) len++;    
6146     jresult = (*jenv)-&gt;NewObjectArray(jenv, len, clazz, NULL);
6147     /* exception checking omitted */
6148
6149     for (i=0; i&lt;len; i++) {
6150       temp_string = (*jenv)-&gt;NewStringUTF(jenv, *result++);
6151       (*jenv)-&gt;SetObjectArrayElement(jenv, jresult, i, temp_string);
6152       (*jenv)-&gt;DeleteLocalRef(jenv, temp_string);
6153     }
6154 }
6155
6156 /* These 3 typemaps tell SWIG what JNI and Java types to use */
6157 %typemap(jni) char ** "jobjectArray"
6158 %typemap(jtype) char ** "String[]"
6159 %typemap(jstype) char ** "String[]"
6160
6161 /* These 2 typemaps handle the conversion of the jtype to jstype typemap type
6162    and vice versa */
6163 %typemap(javain) char ** "$javainput"
6164 %typemap(javaout) char ** {
6165     return $jnicall;
6166   }
6167
6168 /* Now a few test functions */
6169 %inline %{
6170
6171 int print_args(char **argv) {
6172     int i = 0;
6173     while (argv[i]) {
6174          printf("argv[%d] = %s\n", i, argv[i]);
6175          i++;
6176     }
6177     return i;
6178 }
6179
6180 char **get_args() {
6181   static char *values[] = { "Dave", "Mike", "Susan", "John", "Michelle", 0};
6182   return &amp;values[0];
6183 }
6184
6185 %}
6186 </pre></div>
6187
6188 <p>
6189 Note that the 'C' JNI calling convention is used. 
6190 Checking for any thrown exceptions after JNI function calls has been omitted. 
6191 When this module is compiled, our wrapped C functions can be used by the following Java program:
6192 </p>
6193
6194 <div class="code"><pre>
6195 // File runme.java
6196
6197 public class runme {
6198
6199   static {
6200     try {
6201      System.loadLibrary("example");
6202     } catch (UnsatisfiedLinkError e) {
6203       System.err.println("Native code library failed to load. " + e);
6204       System.exit(1);
6205     }
6206   }
6207
6208   public static void main(String argv[]) {
6209     String animals[] = {"Cat","Dog","Cow","Goat"};
6210     example.print_args(animals);
6211     String args[] = example.get_args();
6212     for (int i=0; i&lt;args.length; i++)
6213         System.out.println(i + ":" + args[i]);
6214   }
6215 }
6216 </pre></div>
6217
6218 <p>
6219 When compiled and run we get:
6220 </p>
6221
6222 <div class="code"><pre>
6223 $ java runme
6224 argv[0] = Cat
6225 argv[1] = Dog
6226 argv[2] = Cow
6227 argv[3] = Goat
6228 0:Dave
6229 1:Mike
6230 2:Susan
6231 3:John
6232 4:Michelle
6233 </pre></div>
6234
6235 <p>
6236 In the example, a few different typemaps are used.  The "in" typemap is
6237 used to receive an input argument and convert it to a C array.  Since dynamic
6238 memory allocation is used to allocate memory for the array, the
6239 "freearg" typemap is used to later release this memory after the execution of
6240 the C function. The "out" typemap is used for function return values.
6241 Lastly the "jni", "jtype" and "jstype" typemaps are also required to specify
6242 what Java types to use.
6243 </p>
6244
6245 <H3><a name="expanding_java_object"></a>21.10.5 Expanding a Java object to multiple arguments</H3>
6246
6247
6248 <p>
6249 Suppose that you had a collection of C functions with arguments
6250 such as the following:
6251 </p>
6252
6253 <div class="code">
6254 <pre>
6255 int foo(int argc, char **argv);
6256 </pre>
6257 </div>
6258
6259 <p>
6260 In the previous example, a typemap was written to pass a Java String array as the <tt>char **argv</tt>.  This
6261 allows the function to be used from Java as follows:
6262 </p>
6263
6264 <div class="code">
6265 <pre>
6266 example.foo(4, new String[]{"red", "green", "blue", "white"});
6267 </pre>
6268 </div>
6269
6270 <p>
6271 Although this works, it's a little awkward to specify the argument count.  To fix this, a multi-argument
6272 typemap can be defined.  This is not very difficult--you only have to make slight modifications to the
6273 previous example's typemaps:
6274 </p>
6275
6276 <div class="code">
6277 <pre>
6278 %typemap(in) (int argc, char **argv) {
6279     int i = 0;
6280     $1 = (*jenv)-&gt;GetArrayLength(jenv, $input);
6281     $2 = (char **) malloc(($1+1)*sizeof(char *));
6282     /* make a copy of each string */
6283     for (i = 0; i&lt;$1; i++) {
6284         jstring j_string = (jstring)(*jenv)-&gt;GetObjectArrayElement(jenv, $input, i);
6285         const char * c_string = (*jenv)-&gt;GetStringUTFChars(jenv, j_string, 0);
6286         $2[i] = malloc((strlen(c_string)+1)*sizeof(char));
6287         strcpy($2[i], c_string);
6288         (*jenv)-&gt;ReleaseStringUTFChars(jenv, j_string, c_string);
6289         (*jenv)-&gt;DeleteLocalRef(jenv, j_string);
6290     }
6291     $2[i] = 0;
6292 }
6293
6294 %typemap(freearg) (int argc, char **argv) {
6295     int i;
6296     for (i=0; i&lt;$1-1; i++)
6297       free($2[i]);
6298     free($2);
6299 }
6300
6301 %typemap(jni) (int argc, char **argv) "jobjectArray"
6302 %typemap(jtype) (int argc, char **argv) "String[]"
6303 %typemap(jstype) (int argc, char **argv) "String[]"
6304
6305 %typemap(javain) (int argc, char **argv) "$javainput"
6306 </pre>
6307 </div>
6308
6309 <p>
6310 When writing a multiple-argument typemap, each of the types is referenced by a variable such 
6311 as <tt>$1</tt> or <tt>$2</tt>.   The typemap code simply fills in the appropriate values from
6312 the supplied Java parameter.
6313 </p>
6314
6315 <p>
6316 With the above typemap in place, you will find it no longer necessary
6317 to supply the argument count.  This is automatically set by the typemap code.  For example:
6318 </p>
6319
6320 <div class="code">
6321 <pre>
6322 example.foo(new String[]{"red", "green", "blue", "white"});
6323 </pre>
6324 </div>
6325
6326
6327 <H3><a name="using_typemaps_return_arguments"></a>21.10.6 Using typemaps to return arguments</H3>
6328
6329
6330 <p>
6331 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. 
6332 The <tt>typemaps.i</tt> file defines INPUT, OUTPUT and INOUT typemaps which can be used to solve some instances of this problem. 
6333 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.
6334 </p>
6335  
6336 <p>
6337 Now we are going to outline an alternative approach to using arrays for C pointers. 
6338 The INOUT typemap uses a <tt>double[]</tt> array for receiving and returning the <tt>double*</tt> parameters. 
6339 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.
6340 </p>
6341
6342 <p>
6343 Here is our example function:
6344 </p>
6345
6346 <div class="code"><pre>
6347 /* Returns a status value and two values in out1 and out2 */
6348 int spam(double a, double b, double *out1, double *out2);
6349 </pre></div>
6350
6351 <p>
6352 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:
6353 </p>
6354
6355 <div class="code"><pre>
6356 %module example
6357
6358 /* Define a new structure to use instead of double * */
6359 %inline %{
6360 typedef struct {
6361     double value;
6362 } MyDouble;
6363 %}
6364
6365
6366 %{
6367 /* Returns a status value and two values in out1 and out2 */
6368 int spam(double a, double b, double *out1, double *out2) {
6369   int status = 1;
6370   *out1 = a*10.0;
6371   *out2 = b*100.0;
6372   return status;
6373 };
6374 %}
6375
6376 /* 
6377 This typemap will make any double * function parameters with name <tt>OUTVALUE</tt> take an
6378 argument of MyDouble instead of double *. This will 
6379 allow the calling function to read the double * value after returning from the function.
6380 */
6381 %typemap(in) double *OUTVALUE {
6382     jclass clazz = jenv-&gt;FindClass("MyDouble");
6383     jfieldID fid = jenv-&gt;GetFieldID(clazz, "swigCPtr", "J");
6384     jlong cPtr = jenv-&gt;GetLongField($input, fid);
6385     MyDouble *pMyDouble = NULL;
6386     *(MyDouble **)&amp;pMyDouble = *(MyDouble **)&amp;cPtr;
6387     $1 = &amp;pMyDouble-&gt;value;
6388 }
6389
6390 %typemap(jtype) double *OUTVALUE "MyDouble"
6391 %typemap(jstype) double *OUTVALUE "MyDouble"
6392 %typemap(jni) double *OUTVALUE "jobject"
6393
6394 %typemap(javain) double *OUTVALUE "$javainput"
6395
6396 /* Now we apply the typemap to the named variables */
6397 %apply double *OUTVALUE { double *out1, double *out2 };
6398 int spam(double a, double b, double *out1, double *out2);
6399 </pre></div>
6400
6401 <p>
6402 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. 
6403 JNI error checking has been omitted for clarity.
6404 </p>
6405
6406 <p>
6407 What the typemaps do are make the named <tt>double*</tt> function parameters use our new <tt>MyDouble</tt> wrapper structure. 
6408 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. 
6409 In Java, when the function returns, we use the SWIG created <tt>getValue()</tt> function to get the output value. 
6410 The following Java program demonstrates this:
6411 </p>
6412
6413 <div class="code"><pre>
6414 // File: runme.java
6415
6416 public class runme {
6417
6418   static {
6419     try {
6420       System.loadLibrary("example");
6421     } catch (UnsatisfiedLinkError e) {
6422       System.err.println("Native code library failed to load. " + e);
6423       System.exit(1);
6424     }
6425   }
6426
6427   public static void main(String argv[]) {
6428     MyDouble out1 = new MyDouble();
6429     MyDouble out2 = new MyDouble();
6430     int ret = example.spam(1.2, 3.4, out1, out2);
6431     System.out.println(ret + "  " + out1.getValue() + "  " + out2.getValue());
6432   }
6433 }
6434 </pre></div>
6435
6436 <p>
6437 When compiled and run we get:
6438 </p>
6439
6440 <div class="code"><pre>
6441 $ java runme
6442 1 12.0  340.0
6443 </pre></div>
6444
6445 <H3><a name="adding_downcasts"></a>21.10.7 Adding Java downcasts to polymorphic return types</H3>
6446
6447
6448 <p>
6449 SWIG support for polymorphism works in that the appropriate virtual function is called. However, the default generated code does not allow for downcasting. 
6450 Let's examine this with the following code:
6451 </p>
6452
6453 <div class="code"><pre>
6454 %include "std_string.i"
6455
6456 #include &lt;iostream&gt;
6457 using namespace std;
6458 class Vehicle {
6459 public:
6460     virtual void start() = 0;
6461 ...
6462 };
6463
6464 class Ambulance : public Vehicle {
6465     string vol;
6466 public:
6467     Ambulance(string volume) : vol(volume) {}
6468     virtual void start() {
6469         cout &lt;&lt; "Ambulance started" &lt;&lt; endl;
6470     }
6471     void sound_siren() {
6472         cout &lt;&lt; vol &lt;&lt; " siren sounded!" &lt;&lt; endl;
6473     }
6474 ...
6475 };
6476
6477 Vehicle *vehicle_factory() {
6478     return new Ambulance("Very loud");
6479 }
6480 </pre></div>
6481
6482 <p>
6483 If we execute the following Java code:
6484 </p>
6485
6486 <div class="code"><pre>
6487 Vehicle vehicle = example.vehicle_factory();
6488 vehicle.start();
6489
6490 Ambulance ambulance = (Ambulance)vehicle;
6491 ambulance.sound_siren();
6492 </pre></div>
6493
6494 <p>
6495 We get:
6496 </p>
6497
6498 <div class="code"><pre>
6499 Ambulance started
6500 java.lang.ClassCastException
6501         at runme.main(runme.java:16)
6502 </pre></div>
6503
6504 <p>
6505 Even though we know from examination of the C++ code that <tt>vehicle_factory</tt> returns an object of type <tt>Ambulance</tt>, 
6506 we are not able to use this knowledge to perform the downcast in Java.
6507 This occurs because the runtime type information is not completely passed from C++ to Java when returning the type from <tt>vehicle_factory()</tt>.
6508 Usually this is not a problem as virtual functions do work by default, such as in the case of <tt>start()</tt>. 
6509 There are a few solutions to getting downcasts to work.
6510 </p>
6511
6512 <p>
6513 The first is not to use a Java cast but a call to C++ to make the cast. Add this to your code:
6514 </p>
6515
6516 <div class="code"><pre>
6517 %exception Ambulance::dynamic_cast(Vehicle *vehicle) {
6518     $action
6519     if (!result) {
6520         jclass excep = jenv-&gt;FindClass("java/lang/ClassCastException");
6521         if (excep) {
6522             jenv-&gt;ThrowNew(excep, "dynamic_cast exception");
6523         }
6524     }
6525 }
6526 %extend Ambulance {
6527     static Ambulance *dynamic_cast(Vehicle *vehicle) {
6528         return dynamic_cast&lt;Ambulance *&gt;(vehicle);
6529     }
6530 };
6531 </pre></div>
6532
6533 <p>
6534 It would then be used from Java like this
6535 </p>
6536
6537 <div class="code"><pre>
6538 Ambulance ambulance = Ambulance.dynamic_cast(vehicle);
6539 ambulance.sound_siren();
6540 </pre></div>
6541
6542 <p>
6543 Should <tt>vehicle</tt> not be of type <tt>ambulance</tt> then a Java <tt>ClassCastException</tt> is thrown.
6544 The next solution is a purer solution in that Java downcasts can be performed on the types.
6545 Add the following before the definition of <tt>vehicle_factory</tt>:
6546 </p>
6547
6548 <div class="code"><pre>
6549 %typemap(out) Vehicle * {
6550     Ambulance *downcast = dynamic_cast&lt;Ambulance *&gt;($1);
6551     *(Ambulance **)&amp;$result = downcast;
6552 }
6553
6554 %typemap(javaout) Vehicle * {
6555     return new Ambulance($jnicall, $owner);
6556   }
6557 </pre></div>
6558
6559 <p>
6560 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>.
6561 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.
6562 Consider expanding our example with a new Vehicle type and a more flexible factory function:
6563 </p>
6564
6565 <div class="code"><pre>
6566 class FireEngine : public Vehicle {
6567 public:
6568     FireEngine() {}
6569     virtual void start() {
6570         cout &lt;&lt; "FireEngine started" &lt;&lt; endl;
6571     }
6572     void roll_out_hose() {
6573         cout &lt;&lt; "Hose rolled out" &lt;&lt; endl;
6574     }
6575  ...
6576 };
6577 Vehicle *vehicle_factory(int vehicle_number) {
6578     if (vehicle_number == 0)
6579         return new Ambulance("Very loud");
6580     else
6581         return new FireEngine();
6582 }
6583 </pre></div>
6584
6585 <p>
6586 To be able to downcast with this sort of Java code:
6587 </p>
6588
6589 <div class="code"><pre>
6590 FireEngine fireengine = (FireEngine)example.vehicle_factory(1);
6591 fireengine.roll_out_hose();
6592 Ambulance ambulance = (Ambulance)example.vehicle_factory(0);
6593 ambulance.sound_siren();
6594 </pre></div>
6595
6596 <p>
6597 the following typemaps targeted at the <tt>vehicle_factory</tt> function will achieve this. 
6598 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.
6599 </p>
6600
6601 <div class="code"><pre>
6602 %typemap(jni) Vehicle *vehicle_factory "jobject"
6603 %typemap(jtype) Vehicle *vehicle_factory "Vehicle"
6604 %typemap(jstype) Vehicle *vehicle_factory "Vehicle"
6605 %typemap(javaout) Vehicle *vehicle_factory {
6606     return $jnicall;
6607   }
6608
6609 %typemap(out) Vehicle *vehicle_factory {
6610     Ambulance *ambulance = dynamic_cast&lt;Ambulance *&gt;($1);
6611     FireEngine *fireengine = dynamic_cast&lt;FireEngine *&gt;($1);
6612     if (ambulance) {
6613         // call the Ambulance(long cPtr, boolean cMemoryOwn) constructor
6614         jclass clazz = jenv-&gt;FindClass("Ambulance");
6615         if (clazz) {
6616             jmethodID mid = jenv-&gt;GetMethodID(clazz, "&lt;init&gt;", "(JZ)V");
6617             if (mid) {
6618                 jlong cptr = 0;
6619                 *(Ambulance **)&amp;cptr = ambulance; 
6620                 $result = jenv-&gt;NewObject(clazz, mid, cptr, false);
6621             }
6622         }
6623     } else if (fireengine) {
6624         // call the FireEngine(long cPtr, boolean cMemoryOwn) constructor
6625         jclass clazz = jenv-&gt;FindClass("FireEngine");
6626         if (clazz) {
6627             jmethodID mid = jenv-&gt;GetMethodID(clazz, "&lt;init&gt;", "(JZ)V");
6628             if (mid) {
6629                 jlong cptr = 0;
6630                 *(FireEngine **)&amp;cptr = fireengine; 
6631                 $result = jenv-&gt;NewObject(clazz, mid, cptr, false);
6632             }
6633         }
6634     }
6635     else {
6636         cout &lt;&lt; "Unexpected type " &lt;&lt; endl;
6637     }
6638
6639     if (!$result)
6640         cout &lt;&lt; "Failed to create new java object" &lt;&lt; endl;
6641 }
6642 </pre></div>
6643
6644 <p>
6645 Better error handling would need to be added into this code. 
6646 There are other solutions to this problem, but this last example demonstrates some more involved JNI code.
6647 SWIG usually generates code which constructs the proxy classes using Java code as it is easier to handle error conditions and is faster. 
6648 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.
6649 </p>
6650
6651 <H3><a name="adding_equals_method"></a>21.10.8 Adding an equals method to the Java classes</H3>
6652
6653
6654 <p>
6655 When a pointer is returned from a JNI function, it is wrapped using a new Java proxy class or type wrapper class. 
6656 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.
6657 It is common in Java to use the <tt>equals()</tt> method to check whether two objects are equivalent.
6658 The <tt>equals()</tt> method is usually accompanied by a <tt>hashCode()</tt> method in order to fulfill
6659 the requirement that the hash code is equal for equal objects.
6660 Pure Java code methods like these can be easily added:
6661 </p>
6662
6663 <div class="code">
6664 <pre>
6665 %typemap(javacode) SWIGTYPE %{
6666   public boolean equals(Object obj) {
6667     boolean equal = false;
6668     if (obj instanceof $javaclassname)
6669       equal = ((($javaclassname)obj).swigCPtr == this.swigCPtr);
6670     return equal;
6671   }
6672   public int hashCode() {
6673      return (int)getPointer();
6674   }
6675 %}
6676
6677 class Foo { };
6678 Foo* returnFoo(Foo *foo) { return foo; }
6679 </pre>
6680 </div>
6681
6682 <p>
6683 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>.
6684 </p>
6685
6686 <div class="code">
6687 <pre>
6688 Foo foo1 = new Foo();
6689 Foo foo2 = example.returnFoo(foo1);
6690 System.out.println("foo1? " + foo1.equals(foo2));
6691 </pre>
6692 </div>
6693
6694
6695 <H3><a name="void_pointers"></a>21.10.9 Void pointers and a common Java base class</H3>
6696
6697
6698 <p>
6699 One might wonder why the common code that SWIG emits for the proxy and type wrapper classes is not pushed into a base class. 
6700 The reason is that although <tt>swigCPtr</tt> could be put into a common base class for all classes 
6701 wrapping C structures, it would not work for C++ classes involved in an inheritance chain.
6702 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.
6703 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.
6704 However, you may want to move some of the common code into a base class. 
6705 Here is an example which uses a common base class for all proxy classes and type wrapper classes:
6706 </p>
6707
6708 <div class="code">
6709 <pre>
6710 %typemap(javabase) SWIGTYPE, SWIGTYPE *, SWIGTYPE &amp;, SWIGTYPE [], 
6711                                                          SWIGTYPE (CLASS::*) "SWIG"
6712
6713 %typemap(javacode) SWIGTYPE, SWIGTYPE *, SWIGTYPE &amp;, SWIGTYPE [], 
6714                                                          SWIGTYPE (CLASS::*) %{
6715   protected long getPointer() {
6716     return swigCPtr;
6717   }
6718 %}
6719 </pre>
6720 </div>
6721
6722 <p>
6723 Define new base class called SWIG:
6724 </p>
6725
6726 <div class="code">
6727 <pre>
6728 public abstract class SWIG {
6729   protected abstract long getPointer();
6730
6731   public boolean equals(Object obj) {
6732     boolean equal = false;
6733     if (obj instanceof SWIG)
6734       equal = (((SWIG)obj).getPointer() == this.getPointer());
6735     return equal;
6736   }
6737   
6738   SWIGTYPE_p_void getVoidPointer() {
6739     return new SWIGTYPE_p_void(getPointer(), false);
6740   }
6741 }
6742 </pre>
6743 </div>
6744
6745 <p>
6746 This example contains some useful functionality which you may want in your code. 
6747 </p>
6748
6749 <ul>
6750     <li> It has an <tt>equals()</tt> method. Unlike the previous example, the method code isn't replicated in all classes.
6751     <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.
6752 </ul>
6753
6754 <H3><a name="struct_pointer_pointer"></a>21.10.10 Struct pointer to pointer</H3>
6755
6756
6757 <p>
6758 Pointers to pointers are often used as output parameters in C factory type functions.
6759 These are a bit more tricky to handle.
6760 Consider the following situation where a <tt>Butler</tt> can be hired and fired:
6761 </p>
6762
6763 <div class="code">
6764 <pre>
6765 typedef struct {
6766   int hoursAvailable;
6767   char *greeting;
6768 } Butler;
6769
6770 // Note: HireButler will allocate the memory 
6771 // The caller must free the memory by calling FireButler()!!
6772 extern int HireButler(Butler **ppButler);
6773 extern void FireButler(Butler *pButler);
6774 </pre>
6775 </div>
6776
6777 <p>
6778 C code implementation:
6779 </p>
6780
6781 <div class="code">
6782 <pre>
6783 int HireButler(Butler **ppButler) {
6784   Butler *pButler = (Butler *)malloc(sizeof(Butler));
6785   pButler-&gt;hoursAvailable = 24;
6786   pButler-&gt;greeting = (char *)malloc(32);
6787   strcpy(pButler-&gt;greeting, "At your service Sir");
6788   *ppButler = pButler;
6789   return 1;
6790 }
6791 void FireButler(Butler *pButler) {
6792   free(pButler-&gt;greeting);
6793   free(pButler);
6794 }
6795 </pre>
6796 </div>
6797
6798 <p>
6799 Let's take two approaches to wrapping this code.
6800 The first is to provide a functional interface, much like the original C interface.
6801 The following Java code shows how we intend the code to be used:
6802 </p>
6803
6804 <div class="code">
6805 <pre>
6806     Butler jeeves = new Butler();
6807     example.HireButler(jeeves);
6808     System.out.println("Greeting:     " + jeeves.getGreeting());
6809     System.out.println("Availability: " + jeeves.getHoursAvailable() + " hours per day");
6810     example.FireButler(jeeves);
6811 </pre>
6812 </div>
6813
6814 <p>
6815 Resulting in the following output when run:
6816 </p>
6817
6818 <div class="shell">
6819 <pre>
6820 Greeting:     At your service Sir
6821 Availability: 24 hours per day
6822 </pre>
6823 </div>
6824
6825 <p>
6826 Note the usage is very much like it would be used if we were writing C code, that is, explicit memory management is needed.
6827 No C memory is allocated in the construction of the <tt>Butler</tt> proxy class and 
6828 the proxy class will not destroy the underlying C memory when it is collected.
6829 A number of typemaps and features are needed to implement this approach. 
6830 The following interface file code should be placed before SWIG parses the above C code.
6831 </p>
6832
6833 <div class="code">
6834 <pre>
6835 %module example
6836
6837 // Do not generate the default proxy constructor or destructor
6838 %nodefaultctor Butler;
6839 %nodefaultdtor Butler;
6840
6841 // Add in pure Java code proxy constructor
6842 %typemap(javacode) Butler %{
6843   /** This constructor creates the proxy which initially does not create nor own any C memory */
6844   public Butler() {
6845     this(0, false);
6846   }
6847 %}
6848
6849 // Type typemaps for marshalling Butler **
6850 %typemap(jni) Butler ** "jobject"
6851 %typemap(jtype) Butler ** "Butler"
6852 %typemap(jstype) Butler ** "Butler"
6853
6854 // Typemaps for Butler ** as a parameter output type
6855 %typemap(in) Butler ** (Butler *ppButler = 0) %{
6856   $1 = &amp;ppButler;
6857 %}
6858 %typemap(argout) Butler ** {
6859   // Give Java proxy the C pointer (of newly created object)
6860   jclass clazz = (*jenv)-&gt;FindClass(jenv, "Butler");
6861   jfieldID fid = (*jenv)-&gt;GetFieldID(jenv, clazz, "swigCPtr", "J");
6862   jlong cPtr = 0;
6863   *(Butler **)&amp;cPtr = *$1;
6864   (*jenv)-&gt;SetLongField(jenv, $input, fid, cPtr);
6865 }
6866 %typemap(javain) Butler ** "$javainput"
6867 </pre>
6868 </div>
6869
6870 <p>
6871 Note that the JNI code sets the proxy's <tt>swigCPtr</tt> member variable to point to the newly created object.
6872 The <tt>swigCMemOwn</tt> remains unchanged (at false), so that the proxy does not own the memory.
6873 </p>
6874
6875 <p>
6876 Note: The old %nodefault directive disabled the default constructor
6877 and destructor at the same time. This is unsafe in most of the cases,
6878 and you can use the explicit %nodefaultctor and %nodefaultdtor
6879 directives to achieve the same result if needed.
6880 </p>
6881
6882 <p>
6883 The second approach offers a more object oriented interface to the Java user.
6884 We do this by making the Java proxy class's
6885 constructor call the <tt>HireButler()</tt> method to create the underlying C object.
6886 Additionally we get the proxy to take ownership of the memory so that the
6887 finalizer will call the <tt>FireButler()</tt> function.
6888 The proxy class will thus take ownership of the memory and clean it up when no longer needed.
6889 We will also prevent the user from being able to explicitly call the <tt>HireButler()</tt> and <tt>FireButler()</tt> functions.
6890 Usage from Java will simply be:
6891 </p>
6892
6893 <div class="code">
6894 <pre>
6895 Butler jeeves = new Butler();
6896 System.out.println("Greeting:     " + jeeves.getGreeting());
6897 System.out.println("Availability: " + jeeves.getHoursAvailable() + " hours per day");
6898 </pre>
6899 </div>
6900
6901 <p>
6902 Note that the Butler class is used just like any other Java class and no extra coding by the user needs to be written to 
6903 clear up the underlying C memory as the finalizer will be called by the garbage collector which in turn will call the <tt>FireButler()</tt> function.
6904 To implement this, we use the above interface file code but remove the <tt>javacode</tt> typemap and add the following:
6905 </p>
6906
6907 <div class="code">
6908 <pre>
6909 // Don't expose the memory allocation/de-allocation functions
6910 %ignore FireButler(Butler *pButler);
6911 %ignore HireButler(Butler **ppButler);
6912
6913 // Add in a custom proxy constructor and destructor
6914 %extend Butler {
6915   Butler() {
6916     Butler *pButler = 0;
6917     HireButler(&amp;pButler);
6918     return pButler;
6919   }
6920   ~Butler() {
6921      FireButler($self);
6922    }
6923 }
6924 </pre>
6925 </div>
6926
6927 <p>
6928 Note that the code in <tt>%extend</tt> is using a C++ type constructor and destructor, yet the generated code will still compile as C code,
6929 see <a href="SWIG.html#SWIG_adding_member_functions">Adding member functions to C structures</a>.
6930 The C functional interface has been completely morphed into an object-oriented interface and
6931 the Butler class would behave much like any pure Java class and feel more natural to Java users.
6932 </p>
6933
6934 <H3><a name="java_memory_management_member_variables"></a>21.10.11 Memory management when returning references to member variables</H3>
6935
6936
6937 <p>
6938 This example shows how to prevent premature garbage collection of objects when the underlying C++ class returns a pointer or reference to a member variable.
6939 </p>
6940
6941 <p>
6942 Consider the following C++ code:
6943 </p>
6944
6945 <div class="code">
6946 <pre>
6947 struct Wheel {
6948   int size;
6949   Wheel(int sz) : size(sz) {}
6950 };
6951
6952 class Bike {
6953   Wheel wheel;
6954 public:
6955   Bike(int val) : wheel(val) {}
6956   Wheel&amp; getWheel() { return wheel; }
6957 };
6958 </pre>
6959 </div>
6960
6961 <p>
6962 and the following usage from Java after running the code through SWIG:
6963 </p>
6964
6965
6966 <div class="code">
6967 <pre>
6968     Wheel wheel = new Bike(10).getWheel();
6969     System.out.println("wheel size: " + wheel.getSize());
6970     // Simulate a garbage collection
6971     System.gc();
6972     System.runFinalization();
6973     System.out.println("wheel size: " + wheel.getSize());
6974 </pre>
6975 </div>
6976
6977 <p>
6978 Don't be surprised that if the resulting output gives strange results such as...
6979 </p>
6980
6981 <div class="shell">
6982 <pre>
6983 wheel size: 10
6984 wheel size: 135019664
6985 </pre>
6986 </div>
6987
6988 <p>
6989 What has happened here is the garbage collector has collected the <tt>Bike</tt> instance as it doesn't think it is needed any more.
6990 The proxy instance, <tt>wheel</tt>, contains a reference to memory that was deleted when the <tt>Bike</tt> instance was collected.
6991 In order to prevent the garbage collector from collecting the <tt>Bike</tt> instance a reference to the <tt>Bike</tt> must
6992 be added to the <tt>wheel</tt> instance. You can do this by adding the reference when the <tt>getWheel()</tt> method
6993 is called using the following typemaps.
6994 </p>
6995
6996
6997 <div class="code">
6998 <pre>
6999 %typemap(javacode) Wheel %{
7000   // Ensure that the GC doesn't collect any Bike instance set from Java
7001   private Bike bikeReference;
7002   protected void addReference(Bike bike) {
7003     bikeReference = bike;
7004   }
7005 %}
7006
7007 // Add a Java reference to prevent premature garbage collection and resulting use
7008 // of dangling C++ pointer. Intended for methods that return pointers or
7009 // references to a member variable.
7010 %typemap(javaout) Wheel&amp; getWheel {
7011     long cPtr = $jnicall;
7012     $javaclassname ret = null;
7013     if (cPtr != 0) {
7014       ret = new $javaclassname(cPtr, $owner);
7015       ret.addReference(this);
7016     }
7017     return ret;
7018   }
7019 </pre>
7020 </div>
7021
7022 <p>
7023 The code in the first typemap gets added to the <tt>Wheel</tt> proxy class.
7024 The code in the second typemap constitutes the bulk of the code in the generated <tt>getWheel()</tt> function:
7025 </p>
7026
7027 <div class="code">
7028 <pre>
7029 public class Wheel {
7030   ...
7031   // Ensure that the GC doesn't collect any bike set from Java 
7032   private Bike bikeReference;
7033   protected void addReference(Bike bike) {
7034     bikeReference = bike;
7035   }
7036 }
7037
7038 public class Bike {
7039   ...
7040   public Wheel getWheel() {
7041     long cPtr = exampleJNI.Bike_getWheel(swigCPtr, this);
7042     Wheel ret = null;
7043     if (cPtr != 0) {
7044       ret = new Wheel(cPtr, false);
7045       ret.addReference(this);
7046     }
7047     return ret;
7048   }
7049 }
7050 </pre>
7051 </div>
7052
7053 <p>
7054 Note the <tt>addReference</tt> call.
7055 </p>
7056
7057 <H3><a name="java_memory_management_objects"></a>21.10.12 Memory management for objects passed to the C++ layer</H3>
7058
7059
7060 <p>
7061 Managing memory can be tricky when using C++ and Java proxy classes.
7062 The previous example shows one such case and this example looks at memory management for a class passed to a C++ method which expects the object to remain in scope
7063 after the function has returned. Consider the following two C++ classes:
7064 </p>
7065
7066 <div class="code">
7067 <pre>
7068 struct Element {
7069   int value;
7070   Element(int val) : value(val) {}
7071 };
7072 class Container {
7073   Element* element;
7074 public:
7075   Container() : element(0) {}
7076   void setElement(Element* e) { element = e; }
7077   Element* getElement() { return element; }
7078 };
7079 </pre>
7080 </div>
7081
7082 <p>
7083 and usage from C++
7084 </p>
7085
7086 <div class="code">
7087 <pre>
7088     Container container;
7089     Element element(20);
7090     container.setElement(&amp;element);
7091     cout &lt;&lt; "element.value: " &lt;&lt; container.getElement()-&gt;value &lt;&lt; endl;
7092 </pre>
7093 </div>
7094
7095 <p>
7096 and more or less equivalent usage from Java
7097 </p>
7098
7099 <div class="code">
7100 <pre>
7101     Container container = new Container();
7102     container.setElement(new Element(20));
7103     System.out.println("element value: " + container.getElement().getValue());
7104 </pre>
7105 </div>
7106
7107 <p>
7108 The C++ code will always print out 20, but the value printed out may not be this in the Java equivalent code.
7109 In order to understand why, consider a garbage collection occuring...
7110 </p>
7111
7112 <div class="code">
7113 <pre>
7114     Container container = new Container();
7115     container.setElement(new Element(20));
7116     // Simulate a garbage collection
7117     System.gc();
7118     System.runFinalization();
7119     System.out.println("element value: " + container.getElement().getValue());
7120 </pre>
7121 </div>
7122
7123 <p>
7124 The temporary element created with <tt>new Element(20)</tt> could get garbage collected
7125 which ultimately means the <tt>container</tt> variable is holding a dangling pointer, thereby printing out any old random value instead of the expected value of 20.
7126 One solution is to add in the appropriate references in the Java layer...
7127 </p>
7128
7129 <div class="code">
7130 <pre>
7131 public class Container {
7132
7133   ...
7134
7135   // Ensure that the GC doesn't collect any Element set from Java
7136   // as the underlying C++ class stores a shallow copy
7137   private Element elementReference;
7138   private long getCPtrAndAddReference(Element element) {
7139     elementReference = element;
7140     return Element.getCPtr(element);
7141   }
7142
7143   public void setElement(Element e) {
7144     exampleJNI.Container_setElement(swigCPtr, this, getCPtrAndAddReference(e), e);
7145   }
7146 }
7147 </pre>
7148 </div>
7149
7150 <p>
7151 The following typemaps will generate the desired code.
7152 The 'javain' typemap matches the input parameter type for the <tt>setElement</tt> method.
7153 The 'javacode' typemap simply adds in the specified code into the Java proxy class.
7154 </p>
7155
7156 <div class="code">
7157 <pre>
7158 %typemap(javain) Element *e "getCPtrAndAddReference($javainput)"
7159
7160 %typemap(javacode) Container %{
7161   // Ensure that the GC doesn't collect any element set from Java
7162   // as the underlying C++ class stores a shallow copy
7163   private Element elementReference;
7164   private long getCPtrAndAddReference(Element element) {
7165     elementReference = element;
7166     return Element.getCPtr(element);
7167   }
7168 %}
7169 </pre>
7170 </div>
7171
7172
7173 <H3><a name="java_date_marshalling"></a>21.10.13 Date marshalling using the javain typemap and associated attributes</H3>
7174
7175
7176 <p>
7177 The <a href="#nan_exception_typemap">NaN Exception example</a> is a simple example of the "javain" typemap and its 'pre' attribute.
7178 This example demonstrates how a C++ date class, say <tt>CDate</tt>, can be mapped onto the standard Java date class,
7179 <tt>java.util.GregorianCalendar</tt> by using the 'pre', 'post' and 'pgcppname' attributes of the "javain" typemap.
7180 The idea is that the <tt>GregorianCalendar</tt> is used wherever the C++ API uses a <tt>CDate</tt>.
7181 Let's assume the code being wrapped is as follows:
7182 </p>
7183
7184 <div class="code">
7185 <pre>
7186 class CDate {
7187 public:
7188   CDate(int year, int month, int day);
7189   int getYear();
7190   int getMonth();
7191   int getDay();
7192   ...
7193 };
7194 struct Action {
7195   static int doSomething(const CDate &amp;dateIn, CDate &amp;dateOut);
7196   Action(const CDate &amp;date, CDate &amp;dateOut);
7197 };
7198 </pre>
7199 </div>
7200
7201 <p>
7202 Note that <tt>dateIn</tt> is const and therefore read only and <tt>dateOut</tt> is a non-const output type.
7203 </p>
7204
7205 <p>
7206 First let's look at the code that is generated by default, where the Java proxy class <tt>CDate</tt> is used in the proxy interface:
7207 </p>
7208
7209 <div class="code">
7210 <pre>
7211 public class Action {
7212   ...
7213   public static int doSomething(CDate dateIn, CDate dateOut) {
7214     return exampleJNI.Action_doSomething(CDate.getCPtr(dateIn), dateIn, 
7215                                          CDate.getCPtr(dateOut), dateOut);
7216   }
7217
7218   public Action(CDate date, CDate dateOut) {
7219     this(exampleJNI.new_Action(CDate.getCPtr(date), date, 
7220                                CDate.getCPtr(dateOut), dateOut), true);
7221   }
7222 }
7223 </pre>
7224 </div>
7225
7226 <p>
7227 The <tt>CDate &amp;</tt> and <tt>const CDate &amp;</tt> Java code is generated from the following two default typemaps:
7228 </p>
7229
7230 <div class="code">
7231 <pre>
7232 %typemap(jstype) SWIGTYPE &amp; "$javaclassname"
7233 %typemap(javain) SWIGTYPE &amp; "$javaclassname.getCPtr($javainput)"
7234 </pre>
7235 </div>
7236
7237 <p>
7238 where '$javaclassname' is translated into the proxy class name, <tt>CDate</tt> and '$javainput' is translated into the name of the parameter, eg <tt>dateIn</tt>.
7239 From Java, the intention is then to call into a modifed API with something like:
7240 </p>
7241
7242 <div class="code">
7243 <pre>
7244 java.util.GregorianCalendar calendarIn = 
7245     new java.util.GregorianCalendar(2011, java.util.Calendar.APRIL, 13, 0, 0, 0);
7246 java.util.GregorianCalendar calendarOut = new java.util.GregorianCalendar();
7247
7248 // Note in calls below, calendarIn remains unchanged and calendarOut 
7249 // is set to a new value by the C++ call
7250 Action.doSomething(calendarIn, calendarOut);
7251 Action action = new Action(calendarIn, calendarOut);
7252 </pre>
7253 </div>
7254
7255 <p>
7256 To achieve this mapping, we need to alter the default code generation slightly so that at the Java layer, 
7257 a <tt>GregorianCalendar</tt> is converted into a <tt>CDate</tt>. 
7258 The JNI intermediary layer will still take a pointer to the underlying <tt>CDate</tt> class.
7259 The typemaps to achieve this are shown below.
7260 </p>
7261
7262 <div class="code">
7263 <pre>
7264 %typemap(jstype) const CDate&amp; "java.util.GregorianCalendar"
7265 %typemap(javain, 
7266          pre="    CDate temp$javainput = new CDate($javainput.get(java.util.Calendar.YEAR), "
7267              "$javainput.get(java.util.Calendar.MONTH), $javainput.get(java.util.Calendar.DATE));", 
7268          pgcppname="temp$javainput") const CDate &amp;
7269          "$javaclassname.getCPtr(temp$javainput)"
7270
7271 %typemap(jstype) CDate&amp; "java.util.Calendar"
7272 %typemap(javain, 
7273          pre="    CDate temp$javainput = new CDate($javainput.get(java.util.Calendar.YEAR), "
7274              "$javainput.get(java.util.Calendar.MONTH), $javainput.get(java.util.Calendar.DATE));", 
7275          post="      $javainput.set(temp$javainput.getYear(), temp$javainput.getMonth(), "
7276               "temp$javainput.getDay(), 0, 0, 0);", 
7277          pgcppname="temp$javainput") CDate &amp;
7278          "$javaclassname.getCPtr(temp$javainput)"
7279 </pre>
7280 </div>
7281
7282 <p>
7283 The resulting generated proxy code in the <tt>Action</tt> class follows:
7284  </p>
7285
7286 <div class="code">
7287 <pre>
7288 public class Action {
7289   ...
7290   public static int doSomething(java.util.GregorianCalendar dateIn, 
7291                                 java.util.Calendar dateOut) {
7292     CDate tempdateIn = new CDate(dateIn.get(java.util.Calendar.YEAR), 
7293                                  dateIn.get(java.util.Calendar.MONTH), 
7294                                  dateIn.get(java.util.Calendar.DATE));
7295     CDate tempdateOut = new CDate(dateOut.get(java.util.Calendar.YEAR), 
7296                                   dateOut.get(java.util.Calendar.MONTH), 
7297                                   dateOut.get(java.util.Calendar.DATE));
7298     try {
7299       return exampleJNI.Action_doSomething(CDate.getCPtr(tempdateIn), tempdateIn, 
7300                                            CDate.getCPtr(tempdateOut), tempdateOut);
7301     } finally {
7302       dateOut.set(tempdateOut.getYear(), tempdateOut.getMonth(), tempdateOut.getDay(), 0, 0, 0);
7303     }
7304   }
7305
7306   static private long SwigConstructAction(java.util.GregorianCalendar date, 
7307                                           java.util.Calendar dateOut) {
7308     CDate tempdate = new CDate(date.get(java.util.Calendar.YEAR), 
7309                                date.get(java.util.Calendar.MONTH), 
7310                                date.get(java.util.Calendar.DATE));
7311     CDate tempdateOut = new CDate(dateOut.get(java.util.Calendar.YEAR), 
7312                                   dateOut.get(java.util.Calendar.MONTH), 
7313                                   dateOut.get(java.util.Calendar.DATE));
7314     try {
7315       return exampleJNI.new_Action(CDate.getCPtr(tempdate), tempdate, 
7316                                    CDate.getCPtr(tempdateOut), tempdateOut);
7317     } finally {
7318       dateOut.set(tempdateOut.getYear(), tempdateOut.getMonth(), tempdateOut.getDay(), 0, 0, 0);
7319     }
7320   }
7321
7322   public Action(java.util.GregorianCalendar date, java.util.Calendar dateOut) {
7323     this(Action.SwigConstructAction(date, dateOut), true);
7324   }
7325 }
7326 </pre>
7327 </div>
7328
7329 <p>
7330 A few things to note:
7331 </p>
7332 <ul>
7333   <li> The "javatype" typemap has changed the parameter type to <tt>java.util.GregorianCalendar</tt> or <tt>java.util.Calendar</tt> instead of the default generated <tt>CDate</tt> proxy.
7334   <li> The code in the 'pre' attribute appears before the JNI call (<tt>exampleJNI.new_Action</tt> / <tt>exampleJNI.Action_doSomething</tt>).
7335   <li> The code in the 'post' attribute appears after the JNI call.
7336   <li> A try .. finally block is generated with the JNI call in the try block and 'post' code in the finally block.
7337   The alternative of just using a temporary variable for the return value from the JNI call and the 'post' code being generated before the
7338   return statement is not possible given that the JNI call is in one line and comes from the "javaout" typemap.
7339   <li> The temporary variables in the "javain" typemaps are called <tt>temp$javain</tt>, where "$javain" is replaced with the parameter name.
7340   "$javain" is used to mangle the variable name so that more than one <tt>CDate &amp;</tt> type can be used as a parameter in a method, otherwise two or 
7341   more local variables with the same name would be generated.
7342   <li> The use of the "javain" typemap causes a constructor helper function (<tt>SwigConstructAction</tt>) to be generated.
7343   This allows Java code to be called before the JNI call and is required as the Java compiler won't compile code inserted before the 'this' call.
7344   <li> The 'pgcppname' attribute is used to modify the object being passed as the <a href="#java_pgcpp">premature garbage collection prevention parameter</a> (the 2nd and 4th parameters in the JNI calls).
7345 </ul>
7346
7347
7348
7349
7350 <H2><a name="java_directors_faq"></a>21.11 Living with Java Directors</H2>
7351
7352
7353 <p>
7354   This section is intended to address frequently asked questions and frequently encountered problems when using Java directors.
7355 </p>
7356
7357 <ol>
7358   <li><i>When my program starts up, it complains that </i>method_foo<i> cannot
7359   be found in a Java method called </i>swig_module_init<i>. How do I fix
7360   this?</i>
7361
7362   <p>
7363   Open up the C++ wrapper source code file and look for <code>"method_foo"</code> (include the double quotes, they are important!)
7364   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.
7365   If the package name is incorrect, put a "javapackage" typemap in your SWIG interface file.
7366   </p>
7367   </li>
7368
7369   <li><i>I'm compiling my code and I'm using templates. I provided a
7370   javapackage typemap, but SWIG doesn't generate the right JNI field
7371   descriptor.</i>
7372   <p>
7373   Use the template's renamed name as the argument to the "javapackage" typemap:
7374   </p>
7375 <div class="code">
7376 <pre>
7377 %typemap(javapackage)  std::vector&lt;int&gt;  "your.package.here"
7378 %template(VectorOfInt) std::vector&lt;int&gt;;
7379 </pre>
7380 </div>
7381   </li>
7382
7383   <li><p><i>When I pass class pointers or references through a C++ upcall and I
7384   try to type cast them, Java complains with a ClassCastException. What am I
7385   doing wrong?</i></p>
7386   <p>
7387   Normally, a non-director generated Java proxy class creates temporary Java objects as follows:
7388   </p>
7389 <div class="code">
7390 <pre>
7391 public static void MyClass_method_upcall(MyClass self, long jarg1)
7392 {
7393   Foo darg1 = new Foo(jarg1, false);
7394
7395   self.method_upcall(darg1);
7396 }
7397 </pre>
7398 </div>
7399   <p>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.
7400   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.
7401   Thus, for director-enabled classes <b>and only for director-enabled classes</b>, the generated proxy Java code looks something like:
7402   </p>
7403
7404 <div class="code">
7405 <pre>
7406 public static void MyClass_method_upcall(MyClass self, long jarg1,
7407                                          Foo jarg1_object)
7408 {
7409   Foo darg1 = (jarg1_object != null ? jarg1_object : new Foo(jarg1, false));
7410
7411   self.method_upcall(darg1);
7412 }
7413 </pre>
7414 </div>
7415
7416   <p>
7417   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.
7418   This applies even when the class being wrapped isn't a director-enabled class but takes parameters that are director-enabled classes.
7419   </p>
7420
7421   <p>
7422   The current "type symmetry" design will work for simple C++ inheritance, but will most likely fail for anything more complicated such as tree or diamond C++ inheritance hierarchies.
7423   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>.
7424   </p>
7425   <p>
7426   If all else fails, you can use the downcastXXXXX() method to attempt to recover the director class's Java object pointer.
7427   For the Java Foo proxy class, the Foo director class's java object pointer can be accessed through the javaObjectFoo() method.
7428   The generated method's signature is:
7429   </p>
7430
7431 <div class="code">
7432 <pre>
7433   public static Foo javaObjectFoo(Foo obj);
7434 </pre>
7435 </div>
7436
7437 <p>
7438   From your code, this method is invoked as follows:
7439 </p>
7440
7441 <div class="code">
7442 <pre>
7443 public class MyClassDerived {
7444   public void method_upcall(Foo foo_object)
7445   {
7446     FooDerived    derived = (foo_object != null ?
7447                  (FooDerived) Foo.downcastFoo(foo_object) : null);
7448     /* rest of your code here */
7449   }
7450 }
7451 </pre>
7452 </div>
7453
7454 <p>
7455   An good approach for managing downcasting is placing a static method in each derived class that performs the downcast from the superclass, e.g.,
7456 </p>
7457
7458 <div class="code">
7459 <pre>
7460 public class FooDerived extends Foo {
7461   /* ... */
7462   public static FooDerived downcastFooDerived(Foo foo_object)
7463   {
7464     try {
7465      return (foo_object != null ? (FooDerived) Foo.downcastFoo(foo_object);
7466     }
7467
7468     catch (ClassCastException exc) {
7469       // Wasn't a FooDerived object, some other subclass of Foo
7470       return null;
7471     }
7472   }
7473 }
7474 </pre>
7475 </div>
7476
7477 <p>
7478   Then change the code in MyClassDerived as follows:
7479 </p>
7480
7481 <div class="code">
7482 <pre>
7483 public class MyClassDerived extends MyClass {
7484   /* ... */
7485   public void method_upcall(Foo foo_object)
7486   {
7487     FooDerived    derived = FooDerived.downcastFooDerived(foo_object);
7488     /* rest of your code here */
7489   }
7490 }
7491 </pre>
7492 </div>
7493   </li>
7494
7495   <li><p><i>Why isn't the proxy class declared abstract? Why aren't the director
7496   upcall methods in the proxy class declared abstract?</i></p>
7497
7498   <p>
7499   Declaring the proxy class and its methods abstract would break the JNI argument marshalling and SWIG's downcall functionality (going from Java to C++.)
7500   Create an abstract Java subclass that inherits from the director-enabled class instead.
7501   Using the previous Foo class example:
7502   </p>
7503
7504 <div class="code">
7505 <pre>
7506 public abstract class UserVisibleFoo extends Foo {
7507   /** Make sure user overrides this method, it's where the upcall
7508    * happens.
7509    */
7510   public abstract void method_upcall(Foo foo_object);
7511
7512   /// Downcast from Foo to UserVisibleFoo
7513   public static UserVisibleFoo downcastUserVisibleFoo(Foo foo_object)
7514   {
7515     try {
7516      return (foo_object != null ? (FooDerived) Foo.downcastFoo(foo_object) : null);
7517     }
7518
7519     catch (ClassCastException exc) {
7520       // Wasn't a FooDerived object, some other subclass of Foo
7521       return null;
7522     }
7523   }
7524 }
7525 </pre>
7526 </div>
7527   <p>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.</p>
7528   </li>
7529 </ol>
7530
7531 <H2><a name="odds_ends"></a>21.12 Odds and ends</H2>
7532
7533
7534 <H3><a name="javadoc_comments"></a>21.12.1 JavaDoc comments</H3>
7535
7536
7537 <p>
7538 The SWIG documentation system is currently deprecated. 
7539 When it is resurrected JavaDoc comments will be fully supported. 
7540 If you can't wait for the full documentation system a couple of workarounds are available. 
7541 The <tt>%javamethodmodifiers</tt> feature can be used for adding proxy class method comments and module class method comments. 
7542 The "javaimports" typemap can be hijacked for adding in proxy class JavaDoc comments. 
7543 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. 
7544 Here is an example adding in a proxy class and method comment:
7545 </p>
7546
7547 <div class="code">
7548 <pre>
7549 %javamethodmodifiers Barmy::lose_marbles() "
7550   /**
7551     * Calling this method will make you mad.
7552     * Use with &lt;b&gt;utmost&lt;/b&gt; caution. 
7553     */
7554   public";
7555
7556 %typemap(javaimports) Barmy "
7557 /** The crazy class. Use as a last resort. */"
7558
7559 class Barmy {
7560 public:
7561   void lose_marbles() {}
7562 };
7563 </pre>
7564 </div>
7565
7566 <p>
7567 Note the "public" added at the end of the <tt>%javamethodmodifiers</tt> as this is the default for this feature. 
7568 The generated proxy class with JavaDoc comments is then as follows:
7569 </p>
7570
7571 <div class="code">
7572 <pre>
7573 /** The crazy class. Use as a last resort. */
7574 public class Barmy {
7575 ...
7576   /**
7577     * Calling this method will make you mad.
7578     * Use with &lt;b&gt;utmost&lt;/b&gt; caution. 
7579     */
7580   public void lose_marbles() {
7581     ...
7582   }
7583 ...
7584 }
7585 </pre>
7586 </div>
7587
7588
7589
7590 <H3><a name="functional_interface"></a>21.12.2 Functional interface without proxy classes</H3>
7591
7592
7593 <p>
7594 It is possible to run SWIG in a mode that does not produce proxy classes by using the -noproxy commandline option.
7595 The interface is rather primitive when wrapping structures or classes and is accessed through function calls to the module class.
7596 All the functions in the module class are wrapped by functions with identical names as those in the intermediary JNI class.
7597 </p>
7598
7599 <p>
7600 Consider the example we looked at when examining proxy classes:
7601 </p>
7602
7603 <div class="code">
7604 <pre>
7605 class Foo {
7606 public:
7607      int x;
7608      int spam(int num, Foo* foo);
7609 };
7610 </pre>
7611 </div>
7612
7613 <p>
7614 When using <tt>-noproxy</tt>, type wrapper classes are generated instead of proxy classes.
7615 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.
7616 Here is what the module class looks like:
7617 </p>
7618
7619 <div class="code">
7620 <pre>
7621 public class example {
7622   public static void Foo_x_get(SWIGTYPE_p_Foo self, int x) {...}
7623   public static int Foo_x_get(SWIGTYPE_p_Foo self) {...}
7624   public static int Foo_spam(SWIGTYPE_p_Foo self, int num, SWIGTYPE_p_Foo foo) {...}
7625   public static SWIGTYPE_p_Foo new_Foo() {...}
7626   public static void delete_Foo(SWIGTYPE_p_Foo self) {...}
7627 }
7628 </pre>
7629 </div>
7630
7631 <p>
7632 This approach is not nearly as natural as using proxy classes as the functions need to be used like this:
7633 </p>
7634
7635 <div class="code">
7636 <pre>
7637 SWIGTYPE_p_Foo foo = example.new_Foo();
7638 example.Foo_x_set(foo, 10);
7639 int var = example.Foo_x_get(foo);
7640 example.Foo_spam(foo, 20, foo);
7641 example.delete_Foo(foo);
7642 </pre>
7643 </div>
7644
7645 <p>
7646 Unlike proxy classes, there is no attempt at tracking memory.
7647 All destructors have to be called manually for example the <tt>delete_Foo(foo)</tt> call above.
7648 </p>
7649
7650
7651 <H3><a name="using_own_jni_functions"></a>21.12.3 Using your own JNI functions</H3>
7652
7653
7654 <p>
7655 You may have some hand written JNI functions that you want to use in addition to the SWIG generated JNI functions.
7656 Adding these to your SWIG generated package is possible using the <tt>%native</tt> directive.
7657 If you don't want SWIG to wrap your JNI function then of course you can simply use the <tt>%ignore</tt> directive.
7658 However, if you want SWIG to generate just the Java code for a JNI function then use the <tt>%native</tt> directive.
7659 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.
7660 For example:
7661 </p>
7662
7663 <div class="code"><pre>
7664 %native (HandRolled) void HandRolled(int, char *);
7665 %{
7666 JNIEXPORT void JNICALL Java_packageName_moduleName_HandRolled(JNIEnv *, jclass,
7667                                                               jlong, jstring);
7668 %}
7669 </pre></div>
7670
7671 <p>
7672 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:
7673 </p>
7674
7675 <div class="code"><pre>
7676   public final static native void HandRolled(int jarg1, String jarg2);
7677 </pre></div>
7678
7679 <p>
7680 and as usual this function is wrapped by another which for a global C function would appear in the module class:
7681 </p>
7682
7683 <div class="code"><pre>
7684   public static void HandRolled(int arg0, String arg1) {
7685     exampleJNI.HandRolled(arg0, arg1);
7686   }
7687 </pre></div>
7688
7689 <p>
7690 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.
7691 You may have to add in some "jtype", "jstype", "javain" and "javaout" typemaps when wrapping some JNI types.
7692 Here the default typemaps work for <tt>int</tt> and <tt>char *</tt>.
7693 </p>
7694
7695 <p>
7696 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.
7697 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.
7698 </p>
7699
7700
7701 <H3><a name="performance"></a>21.12.4 Performance concerns and hints</H3>
7702
7703
7704 <p>
7705 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>.
7706 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.
7707 </p>
7708
7709 <p>
7710 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: 
7711 </p>
7712
7713 <div class="code"><pre>
7714 %typemap(javafinalize) SWIGTYPE ""
7715 </pre></div>
7716
7717 <p>
7718 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. 
7719 This method normally calls the C++ destructor or <tt>free()</tt> for C code.
7720 </p>
7721
7722 <H3><a name="java_debugging"></a>21.12.5 Debugging</H3>
7723
7724
7725 <p>
7726 The generated code can be debugged using both a Java debugger and a C++ debugger using the usual debugging techniques.
7727 Breakpoints can be set in either Java or C++ code and so both can be debugged simultaneously.
7728 Most debuggers do not understand both Java and C++, with one noteable exception of Sun Studio, 
7729 where it is possible to step from Java code into a JNI method within one environment.
7730 </p>
7731
7732 <p>
7733 Alternatively, debugging can involve placing debug printout statements in the JNI layer using the <tt>%exception</tt> directive.
7734 See the <a href="Customization.html#Customization_exception_special_variables">special variables for %exception</a> section.
7735 Many of the default typemaps can also be overidden and modified for adding in extra logging/debug display information.
7736 </p>
7737
7738 <p>
7739 The <tt>-Xcheck:jni</tt> and <tt>-Xcheck:nabounds</tt> Java executable options are useful for debugging to make sure the JNI code is behaving.
7740 The -verbose:jni and -verbose:gc are also useful options for monitoring code behaviour.
7741 </p>
7742
7743
7744 <H2><a name="java_examples"></a>21.13 Examples</H2>
7745
7746
7747 <p>
7748 The directory Examples/java has a number of further examples. 
7749 Take a look at these if you want to see some of the techniques described in action.
7750 The Examples/index.html file in the parent directory contains the SWIG Examples Documentation and is a useful starting point. 
7751 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.
7752 For the benefit of Windows users, there are also Visual C++ project files in a couple of the <a href="Windows.html#Windows_examples">Windows Examples</a>.
7753 There are also many regression tests in the Examples/test-suite directory.
7754 Many of these have runtime tests in the java subdirectory.
7755 </p>
7756
7757 </body>
7758 </html>
7759