summaryrefslogtreecommitdiff
path: root/Doc/Manual/Java.html
blob: dae6edc01caf4d0bbe7f09165f5f742d6e4db23c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>SWIG and Java</title>
<link rel="stylesheet" type="text/css" href="style.css">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body bgcolor="#FFFFFF">
<H1><a name="Java">25 SWIG and Java</a></H1>
<!-- INDEX -->
<div class="sectiontoc">
<ul>
<li><a href="#Java_overview">Overview</a>
<li><a href="#Java_preliminaries">Preliminaries</a>
<ul>
<li><a href="#Java_running_swig">Running SWIG</a>
<li><a href="#Java_commandline">Additional Commandline Options</a>
<li><a href="#Java_getting_right_headers">Getting the right header files</a>
<li><a href="#Java_compiling_dynamic">Compiling a dynamic module</a>
<li><a href="#Java_using_module">Using your module</a>
<li><a href="#Java_dynamic_linking_problems">Dynamic linking problems</a>
<li><a href="#Java_compilation_problems_cpp">Compilation problems and compiling with C++</a>
<li><a href="#Java_building_windows">Building on Windows</a>
<ul>
<li><a href="#Java_visual_studio">Running SWIG from Visual Studio</a>
<li><a href="#Java_nmake">Using NMAKE</a>
</ul>
</ul>
<li><a href="#Java_basic_tour">A tour of basic C/C++ wrapping</a>
<ul>
<li><a href="#Java_module_packages_classes">Modules, packages and generated Java classes</a>
<li><a href="#Java_functions">Functions</a>
<li><a href="#Java_global_variables">Global variables</a>
<li><a href="#Java_constants">Constants</a>
<li><a href="#Java_enumerations">Enumerations</a>
<ul>
<li><a href="#Java_anonymous_enums">Anonymous enums</a>
<li><a href="#Java_typesafe_enums">Typesafe enums</a>
<li><a href="#Java_proper_enums">Proper Java enums</a>
<li><a href="#Java_typeunsafe_enums">Type unsafe enums</a>
<li><a href="#Java_simple_enums">Simple enums</a>
</ul>
<li><a href="#Java_pointers">Pointers</a>
<li><a href="#Java_structures">Structures</a>
<li><a href="#Java_classes">C++ classes</a>
<li><a href="#Java_inheritance">C++ inheritance</a>
<li><a href="#Java_pointers_refs_arrays">Pointers, references, arrays and pass by value</a>
<ul>
<li><a href="#Java_null_pointers">Null pointers</a>
</ul>
<li><a href="#Java_overloaded_functions">C++ overloaded functions</a>
<li><a href="#Java_default_arguments">C++ default arguments</a>
<li><a href="#Java_namespaces">C++ namespaces</a>
<li><a href="#Java_templates">C++ templates</a>
<li><a href="#Java_smart_pointers">C++ Smart Pointers</a>
<ul>
<li><a href="#Java_smart_pointers_shared_ptr">The shared_ptr Smart Pointer</a>
<li><a href="#Java_smart_pointers_generic">Generic Smart Pointers</a>
</ul>
</ul>
<li><a href="#Java_further_details">Further details on the generated Java classes</a>
<ul>
<li><a href="#Java_imclass">The intermediary JNI class</a>
<ul>
<li><a href="#Java_imclass_pragmas">The intermediary JNI class pragmas</a>
</ul>
<li><a href="#Java_module_class">The Java module class</a>
<ul>
<li><a href="#Java_module_class_pragmas">The Java module class pragmas</a>
</ul>
<li><a href="#Java_proxy_classes">Java proxy classes</a>
<ul>
<li><a href="#Java_memory_management">Memory management</a>
<li><a href="#Java_inheritance_mirroring">Inheritance</a>
<li><a href="#Java_proxy_classes_gc">Proxy classes and garbage collection</a>
<li><a href="#Java_pgcpp">The premature garbage collection prevention parameter for proxy class marshalling</a>
<li><a href="#Java_multithread_libraries">Single threaded applications and thread safety</a>
</ul>
<li><a href="#Java_type_wrapper_classes">Type wrapper classes</a>
<li><a href="#Java_enum_classes">Enum classes</a>
<ul>
<li><a href="#Java_typesafe_enums_classes">Typesafe enum classes</a>
<li><a href="#Java_proper_enums_classes">Proper Java enum classes</a>
<li><a href="#Java_typeunsafe_enums_classes">Type unsafe enum classes</a>
</ul>
</ul>
<li><a href="#Java_directors">Cross language polymorphism using directors</a>
<ul>
<li><a href="#Java_enabling_directors">Enabling directors</a>
<li><a href="#Java_directors_classes">Director classes</a>
<li><a href="#Java_directors_overhead">Overhead and code bloat</a>
<li><a href="#Java_directors_example">Simple directors example</a>
<li><a href="#Java_directors_threading">Director threading issues</a>
<li><a href="#Java_directors_performance">Director performance tuning</a>
<li><a href="#Java_exceptions_from_directors">Java exceptions from directors</a>
</ul>
<li><a href="#Java_allprotected">Accessing protected members</a>
<li><a href="#Java_common_customization">Common customization features</a>
<ul>
<li><a href="#Java_helper_functions">C/C++ helper functions</a>
<li><a href="#Java_class_extension">Class extension with %extend</a>
<li><a href="#Java_exception_handling">Exception handling with %exception and %javaexception</a>
<li><a href="#Java_method_access">Method access with %javamethodmodifiers</a>
</ul>
<li><a href="#Java_tips_techniques">Tips and techniques</a>
<ul>
<li><a href="#Java_input_output_parameters">Input and output parameters using primitive pointers and references</a>
<li><a href="#Java_simple_pointers">Simple pointers</a>
<li><a href="#Java_c_arrays">Wrapping C arrays with Java arrays</a>
<li><a href="#Java_unbounded_c_arrays">Unbounded C Arrays</a>
<li><a href="#Java_binary_char">Binary data vs Strings</a>
<li><a href="#Java_heap_allocations">Overriding new and delete to allocate from Java heap</a>
</ul>
<li><a href="#Java_typemaps">Java typemaps</a>
<ul>
<li><a href="#Java_default_primitive_type_mappings">Default primitive type mappings</a>
<li><a href="#Java_default_non_primitive_typemaps">Default typemaps for non-primitive types</a>
<li><a href="#Java_jvm64">Sixty four bit JVMs</a>
<li><a href="#Java_what_is_typemap">What is a typemap?</a>
<li><a href="#Java_typemaps_c_to_java_types">Typemaps for mapping C/C++ types to Java types</a>
<li><a href="#Java_typemap_attributes">Java typemap attributes</a>
<li><a href="#Java_special_variables">Java special variables</a>
<li><a href="#Java_typemaps_for_c_and_cpp">Typemaps for both C and C++ compilation</a>
<li><a href="#Java_code_typemaps">Java code typemaps</a>
<li><a href="#Java_directors_typemaps">Director specific typemaps</a>
</ul>
<li><a href="#Java_typemap_examples">Typemap Examples</a>
<ul>
<li><a href="#Java_simpler_enum_classes">Simpler Java enums for enums without initializers</a>
<li><a href="#Java_exception_typemap">Handling C++ exception specifications as Java exceptions</a>
<li><a href="#Java_nan_exception_typemap">NaN Exception - exception handling for a particular type</a>
<li><a href="#Java_converting_java_string_arrays">Converting Java String arrays to char ** </a>
<li><a href="#Java_expanding_java_object">Expanding a Java object to multiple arguments</a>
<li><a href="#Java_using_typemaps_return_arguments">Using typemaps to return arguments</a>
<li><a href="#Java_adding_downcasts">Adding Java downcasts to polymorphic return types</a>
<li><a href="#Java_adding_equals_method">Adding an equals method to the Java classes</a>
<li><a href="#Java_void_pointers">Void pointers and a common Java base class</a>
<li><a href="#Java_struct_pointer_pointer">Struct pointer to pointer</a>
<li><a href="#Java_memory_management_member_variables">Memory management when returning references to member variables</a>
<li><a href="#Java_memory_management_objects">Memory management for objects passed to the C++ layer</a>
<li><a href="#Java_date_marshalling">Date marshalling using the javain typemap and associated attributes</a>
</ul>
<li><a href="#Java_directors_faq">Living with Java Directors</a>
<li><a href="#Java_odds_ends">Odds and ends</a>
<ul>
<li><a href="#Java_javadoc_comments">JavaDoc comments</a>
<li><a href="#Java_functional_interface">Functional interface without proxy classes</a>
<li><a href="#Java_using_own_jni_functions">Using your own JNI functions</a>
<li><a href="#Java_performance">Performance concerns and hints</a>
<li><a href="#Java_debugging">Debugging</a>
</ul>
<li><a href="#Java_examples">Java Examples</a>
</ul>
</div>
<!-- INDEX -->



<p>
This chapter describes SWIG's support of Java. 
It covers most SWIG features, but certain low-level details are covered in less depth than in earlier chapters. 
</p>


<H2><a name="Java_overview">25.1 Overview</a></H2>


<p>
The 100% Pure Java effort is a commendable concept, however in the real world programmers often either need to re-use their existing code or in some situations 
want to take advantage of Java but are forced into using some native (C/C++) code.
The Java extension to SWIG makes it very easy to plumb in existing C/C++ code for access from Java, as SWIG writes the Java Native Interface (JNI) code for you. 
It is different to using the 'javah' tool as SWIG will wrap existing C/C++ code, whereas javah takes 'native' Java function declarations and creates C/C++ function prototypes.
SWIG wraps C/C++ code using Java proxy classes and is very useful if you want to have access to large amounts of C/C++ code from Java.
If only one or two JNI functions are needed then using SWIG may be overkill.
SWIG enables a Java program to easily call into C/C++ code from Java.
Historically, SWIG was not able to generate any code to call into Java code from C++.
However, SWIG now supports full cross language polymorphism and code is generated to call up from C++ to Java when wrapping C++ virtual methods via the director feature.
</p>

<p>
Java is one of the few non-scripting language modules in SWIG.
As SWIG utilizes the type safety that the Java language offers, it takes a somewhat different approach to that used for scripting languages.
In particular runtime type checking and the runtime library are not used by Java.
This should be borne in mind when reading the rest of the SWIG documentation.
This chapter on Java is relatively self contained and will provide you with nearly everything you need for using SWIG and Java.
However, the "<a href="SWIG.html#SWIG">SWIG Basics</a>" chapter will be a useful read in conjunction with this one.
</p>

<p>
This chapter starts with a few practicalities on running SWIG and compiling the generated code.
If you are looking for the minimum amount to read, have a look at the sections up to and including the
<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.
Following this section are details of the C/C++ code and Java classes that SWIG generates.
Due to the complexities of C and C++ there are different ways in which C/C++ code could be wrapped and called from Java.
SWIG is a powerful tool and the rest of the chapter details how the default code wrapping can be tailored.
Various customisation tips and techniques using SWIG directives are covered.
The latter sections cover the advanced techniques of using typemaps for complete control of the wrapping process.
</p>

<H2><a name="Java_preliminaries">25.2 Preliminaries</a></H2>


<p>
SWIG 1.1 works with JDKs from JDK 1.1 to JDK1.4 (Java 2 SDK1.4) and should also work with any later versions.
Given the choice, you should probably use the latest version of Sun's JDK. 
The SWIG Java module is known to work using Sun's JVM on Solaris, Linux and the various flavours of Microsoft Windows including Cygwin. 
The Kaffe JVM is known to give a few problems and at the time of writing was not a fully fledged JVM with full JNI support. 
The generated code is also known to work on vxWorks using WindRiver's PJava 3.1. 
The best way to determine whether your combination of operating system and JDK will work is to test the examples and test-suite that comes with SWIG. 
Run <tt>make -k check</tt> from the SWIG root directory after installing SWIG on Unix systems. </p>

<p>
The Java module requires your system to support shared libraries and dynamic loading. 
This is the commonly used method to load JNI code so your system will more than likely support this.</p>

<p>
Android uses Java JNI and also works with SWIG. Please read the <a href="Android.html#Android">Android chapter</a> in conjunction with this one if you are targeting Android.
</p>

<H3><a name="Java_running_swig">25.2.1 Running SWIG</a></H3>


<p>
Suppose that you defined a SWIG module such as the following:
</p>

<div class="code">
<pre>
/* File: example.i */
%module test
%{
#include "stuff.h"
%}
int fact(int n);
</pre>
</div>


<p>
To build a Java module, run SWIG using the <tt>-java</tt> option :</p>

<div class="code"><pre>
%swig -java example.i
</pre></div>

<p>
If building C++, add the <tt>-c++</tt> option:
</p>

<div class="code"><pre>
$ swig -c++ -java example.i
</pre></div>

<p>
This creates two different files; a C/C++ source file <tt>example_wrap.c</tt> or
<tt>example_wrap.cxx</tt> and numerous Java files.   The generated
C/C++ source file contains the JNI wrapper code that needs to be compiled and linked with the
rest of your C/C++ application. 
</p>

<p>
The name of the wrapper file is derived from the name of the input file.  For example, if the
input file is <tt>example.i</tt>, the name of the wrapper file is <tt>example_wrap.c</tt>.
To change this, you can use the <tt>-o</tt> option. 
It is also possible to change the <a href="SWIG.html#SWIG_output">output directory </a> that the Java files are generated into using <tt>-outdir</tt>.
</p>

<p>
The module name, specified with <tt>%module</tt>, determines the name of various generated classes as discussed <a href="#Java_module_packages_classes">later</a>.
Note that the module name does not define a Java package and by default, the generated Java classes do not have a Java package.
The <tt>-package</tt> option described below can specify a Java package name to use.
</p>

<p>
The following sections have further practical examples and details on how you might go about
compiling and using the generated files.
</p>

<H3><a name="Java_commandline">25.2.2 Additional Commandline Options</a></H3>


<p>
The following table list the additional commandline options available for the Java module. They can also be seen by using: 
</p>

<div class="code"><pre>
swig -java -help 
</pre></div>

<table summary="Java specific options">
<tr>
<th>Java specific options</th>
</tr>

<tr>
<td>-nopgcpp</td>
<td>suppress the premature garbage collection prevention parameter</td>
</tr>

<tr>
<td>-noproxy</td>
<td>generate the low-level functional interface instead of proxy classes </td>
</tr>

<tr>
<td>-package &lt;name&gt;</td>
<td>set name of the Java package to &lt;name&gt;</td>
</tr>

</table>

<p>
Their use will become clearer by the time you have finished reading this section on SWIG and Java.
</p>

<H3><a name="Java_getting_right_headers">25.2.3 Getting the right header files</a></H3>


<p>
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. 
They are usually in directories like this:</p>

<div class="code"><pre>
/usr/java/include
/usr/java/include/&lt;operating_system&gt;
</pre></div>

<p>
The exact location may vary on your machine, but the above locations are typical. </p>

<H3><a name="Java_compiling_dynamic">25.2.4 Compiling a dynamic module</a></H3>


<p>
The JNI code exists in a dynamic module or shared library (DLL on Windows) and gets loaded by the JVM. 
Assuming you have code you need to link to in a file called <tt>example.c</tt>, in order to build a shared library file, you need to compile your module in a manner similar to the following (shown for Solaris):</p>

<div class="code"><pre>
$ swig -java example.i
$ gcc -fPIC -c example_wrap.c -I/usr/java/include -I/usr/java/include/solaris
$ gcc -fPIC -c example.c
$ ld -G example_wrap.o example.o -o libexample.so
</pre></div>

<p>
The exact commands for doing this vary from platform to platform. 
However, SWIG tries to guess the right options when it is installed.  Therefore, 
you may want to start with one of the examples in the <tt>Examples/java</tt> 
directory.   If that doesn't work, you will need to read the man-pages for
your compiler and linker to get the right set of options.  You might also
check the <a href="http://www.dabeaz.com/cgi-bin/wiki.pl">SWIG Wiki</a> for
additional information.
</p>

<p>
<b>Important</b> <br>
If you are going to use optimisations turned on with gcc (for example -O2), ensure you also compile with -fno-strict-aliasing. The GCC optimisations have become 
more aggressive from gcc-4.0 onwards and will result in code that fails with strict aliasing optimisations turned on. See the <a href="#Java_typemaps_c_to_java_types">C/C++ to Java typemaps</a> section for more details.
</p>

<p>
The name of the shared library output file is important. 
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="#Java_dynamic_linking_problems">Dynamic linking problems</a> for more information). 
The name of the module is specified using the <tt>%module</tt> directive or <tt>-module</tt> command line option.</p>

<H3><a name="Java_using_module">25.2.5 Using your module</a></H3>


<p>
To load your shared native library module in Java, simply use Java's <tt>System.loadLibrary</tt> method in a Java class:</p>

<div class="code"><pre>
// runme.java

public class runme {
  static {
    System.loadLibrary("example");
  }

  public static void main(String argv[]) {
    System.out.println(example.fact(4));
  }
}
</pre></div>

<p>
Compile all the Java files and run:
</p>

<div class="code"><pre>
$ javac *.java
$ java runme
24
$
</pre></div>

<p>
If it doesn't work have a look at the following section which discusses problems loading the shared library.
</p>

<H3><a name="Java_dynamic_linking_problems">25.2.6 Dynamic linking problems</a></H3>


<p>
As shown in the previous section the code to load a native library (shared library) is <tt>System.loadLibrary("name")</tt>. 
This can fail with an UnsatisfiedLinkError exception and can be due to a number of reasons.
</p>

<p>
You may get an exception similar to this:
</p>

<div class="code"><pre>
$ java runme
Exception in thread "main" java.lang.UnsatisfiedLinkError: no example in java.library.path
        at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1312)
        at java.lang.Runtime.loadLibrary0(Runtime.java:749)
        at java.lang.System.loadLibrary(System.java:820)
        at runme.&lt;clinit&gt;(runme.java:5)
</pre></div>

<p>
The most common cause for this is an incorrect naming of the native library for the name passed to the <tt>loadLibrary</tt> function. 
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>. 
The string must be <i>name</i> and not <i>libname</i> for all platforms. 
On Windows the native library must then be called <i>name.dll</i> and on most Unix systems it must be called <i>libname.so</i>. 
</p>

<p>
Another common reason for the native library not loading is because it is not in your path. 
On Windows make sure the <i>path</i> environment variable contains the path to the native library. 
On Unix make sure that your <i>LD_LIBRARY_PATH</i> contains the path to the native library. 
Adding paths to <i>LD_LIBRARY_PATH</i> can slow down other programs on your system so you may want to consider alternative approaches.
For example you could recompile your native library with extra path information using <tt>-rpath</tt> if you're using GNU, see the GNU linker documentation (<tt>ld</tt> man page).
You could use a command such as <tt>ldconfig</tt> (Linux) or
<tt>crle</tt> (Solaris) to add additional search paths to the default
system configuration (this requires root access and you will need to read the man pages).
</p>

<p>
The native library will also not load if there are any unresolved symbols in the compiled C/C++ code. 
The following exception is indicative of this:
</p>

<div class="code"><pre>
$ java runme
Exception in thread "main" java.lang.UnsatisfiedLinkError: libexample.so: undefined
symbol: fact
        at java.lang.ClassLoader$NativeLibrary.load(Native Method)
        at java.lang.ClassLoader.loadLibrary0(ClassLoader.java, Compiled Code)
        at java.lang.ClassLoader.loadLibrary(ClassLoader.java, Compiled Code)
        at java.lang.Runtime.loadLibrary0(Runtime.java, Compiled Code)
        at java.lang.System.loadLibrary(System.java, Compiled Code)
        at runme.&lt;clinit&gt;(runme.java:5)
$
</pre></div>

<p>
This error usually indicates that you forgot to include some object files or libraries in the linking of the native library file.  
Make sure you compile both the SWIG wrapper file and the code you are wrapping into the native library file.  
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:
</p>

<div class="code"><pre>
$ java runme
Exception in thread "main" java.lang.UnsatisfiedLinkError: exampleJNI.gcd(II)I
        at exampleJNI.gcd(Native Method)
        at example.gcd(example.java:12)
        at runme.main(runme.java:18)
</pre></div>

<p>
where <tt>gcd</tt> is the missing JNI function that SWIG generated into the wrapper file.
Also make sure you pass all of the required libraries to the linker.  
The <tt>java -verbose:jni</tt> commandline switch is also a great way to get more information on unresolved symbols.
One last piece of advice is to beware of the common faux pas of having more than one native library version in your path.
</p>

<p>
In summary, ensure that you are using the correct C/C++ compiler and linker combination and options for successful native library loading. 
If you are using the examples that ship with SWIG, then the Examples/Makefile must have these set up correctly for your system. 
The SWIG installation package makes a best attempt at getting these correct but does not get it right 100% of the time.
The <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.
The following section also contains some C++ specific linking problems and solutions.
</p>


<H3><a name="Java_compilation_problems_cpp">25.2.7 Compilation problems and compiling with C++</a></H3>


<p>
On most machines, shared library files should be linked using the C++
compiler.  For example:
</p>

<div class="code"><pre>
% swig -c++ -java example.i
% g++ -c -fpic example.cxx
% g++ -c -fpic example_wrap.cxx -I/usr/java/j2sdk1.4.1/include -I/usr/java/j2sdk1.4.1/include/linux
% g++ -shared example.o example_wrap.o -o libexample.so
</pre></div>

<p>
In addition to this, you may need to include additional library
files to make it work.  For example, if you are using the Sun C++ compiler on
Solaris, you often need to add an extra library <tt>-lCrun</tt> like this:
</p>

<div class="code"><pre>
% swig -c++ -java example.i
% CC -c example.cxx
% CC -c example_wrap.cxx -I/usr/java/include -I/usr/java/include/solaris
% CC -G example.o example_wrap.o -L/opt/SUNWspro/lib -o libexample.so -lCrun
</pre></div>

<p>
If you aren't entirely sure about the linking for C++, you
might look at an existing C++ program.  On many Unix machines, the
<tt>ldd</tt> command will list library dependencies.  This should give
you some clues about what you might have to include when you link your
shared library. For example:
</p>

<div class="code">
<pre>
$ ldd swig
        libstdc++-libc6.1-1.so.2 =&gt; /usr/lib/libstdc++-libc6.1-1.so.2 (0x40019000)
        libm.so.6 =&gt; /lib/libm.so.6 (0x4005b000)
        libc.so.6 =&gt; /lib/libc.so.6 (0x40077000)
        /lib/ld-linux.so.2 =&gt; /lib/ld-linux.so.2 (0x40000000)
$
</pre>
</div>

<p>
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.
</p>


<H3><a name="Java_building_windows">25.2.8 Building on Windows</a></H3>


<p>
Building on Windows is roughly similar to the process used with Unix.  
You will want to produce a DLL that can be loaded by the Java Virtual Machine.  
This section covers the process of using SWIG with Microsoft Visual C++ 6 although the procedure may be similar with other compilers.  
In order for everything to work, you will need to have a JDK installed on your machine in order to read the JNI header files.</p>

<H4><a name="Java_visual_studio">25.2.8.1 Running SWIG from Visual Studio</a></H4>


<p>
If you are developing your application within Microsoft Visual studio, SWIG can be invoked as a custom build option. 
The Examples\java directory has a few <a href="Windows.html#Windows_examples">Windows Examples</a> containing Visual Studio project (.dsp) files.
The process to re-create the project files for a C project are roughly:</p>

<ul>
<li>Open up a new workspace and use the AppWizard to select a DLL project.
<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>).   
Don't worry if the wrapper file doesn't exist yet--Visual Studio will keep a reference to it.
<li>Select the SWIG interface file and go to the settings menu. Under settings, select the "Custom Build" option.
<li>Enter "SWIG" in the description field.
<li>Enter "<tt>swig -java -o $(ProjDir)\$(InputName)_wrap.c $(InputPath)</tt>" in the "Build command(s) field"
<li>Enter "<tt>$(ProjDir)\$(InputName)_wrap.c</tt>" in the "Output files(s) field".
<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".
<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).
<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.
<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" 
<li>Build your project.
</ul>

<p>
Note: If using C++, choose a C++ suffix for the wrapper file, for example <tt>example_wrap.cxx</tt>.
Use <tt>_wrap.cxx</tt> instead of <tt>_wrap.c</tt> in the instructions above and add -c++ when invoking swig.
</p>

<p>
Now, assuming all went well, SWIG will be automatically invoked when you build your project.  
When doing a build, any changes made to the interface file will result in SWIG being automatically invoked to produce a new version of the wrapper file.
</p>

<p>
The Java classes that SWIG output should also be compiled into .class files. 
To run the native code in the DLL (example.dll), make sure that it is in your path then run your Java program which uses it, as described in the previous section. 
If the library fails to load have a look at <a href="#Java_dynamic_linking_problems">Dynamic linking problems</a>.
</p>

<H4><a name="Java_nmake">25.2.8.2 Using NMAKE</a></H4>


<p>
Alternatively, a Makefile for use by NMAKE can be written.   
Make sure the environment variables for MSVC++ are available and the MSVC++ tools are in your path.   
Now, just write a short Makefile like this :</p>

<div class="code"><pre>
# Makefile for using SWIG and Java for C code

SRCS          = example.c
IFILE         = example
INTERFACE     = $(IFILE).i
WRAPFILE      = $(IFILE)_wrap.c

# Location of the Visual C++ tools (32 bit assumed)

TOOLS         = c:\msdev
TARGET        = example.dll
CC            = $(TOOLS)\bin\cl.exe
LINK          = $(TOOLS)\bin\link.exe
INCLUDE32     = -I$(TOOLS)\include
MACHINE       = IX86

# C Library needed to build a DLL

DLLIBC        = msvcrt.lib oldnames.lib  

# Windows libraries that are apparently needed
WINLIB        = kernel32.lib advapi32.lib user32.lib gdi32.lib comdlg32.lib winspool.lib

# Libraries common to all DLLs
LIBS          = $(DLLIBC) $(WINLIB) 

# Linker options
LOPT      = -debug:full -debugtype:cv /NODEFAULTLIB /RELEASE /NOLOGO \
             /MACHINE:$(MACHINE) -entry:_DllMainCRTStartup@12 -dll

# C compiler flags

CFLAGS        = /Z7 /Od /c /nologo
JAVA_INCLUDE    = -ID:\jdk1.3\include -ID:\jdk1.3\include\win32

java::
        swig -java -o $(WRAPFILE) $(INTERFACE)
        $(CC) $(CFLAGS) $(JAVA_INCLUDE) $(SRCS) $(WRAPFILE)
        set LIB=$(TOOLS)\lib
        $(LINK) $(LOPT) -out:example.dll $(LIBS) example.obj example_wrap.obj
        javac *.java
</pre></div>

<p>
To build the DLL and compile the java code, run NMAKE (you may need to run <tt>vcvars32</tt> first). 
This is a pretty simplistic Makefile, but hopefully its enough to get you started.
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.
</p>


<H2><a name="Java_basic_tour">25.3 A tour of basic C/C++ wrapping</a></H2>


<p>
By default, SWIG attempts to build a natural Java interface
to your C/C++ code.  Functions are wrapped as functions, classes are wrapped as classes, 
variables are wrapped with JavaBean type getters and setters and so forth.
This section briefly covers the essential aspects of this wrapping.
</p>

<H3><a name="Java_module_packages_classes">25.3.1 Modules, packages and generated Java classes</a></H3>


<p>
The SWIG <tt>%module</tt> directive specifies the name of the Java
module. When you specify `<tt>%module example</tt>', the <i>module name</i>
determines the name of some of the generated files in the module.
The generated code consists of a <i>module class</i> file <tt>example.java</tt>, an
<i>intermediary JNI class</i> file, <tt>exampleJNI.java</tt> as well as numerous other Java <i>proxy class</i> files.
Each proxy class is named after the structs, unions and classes you are wrapping.
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>.
When choosing a module name, make sure you don't use the same name as one of the generated
proxy class files nor a Java keyword. Sometimes a C/C++ type cannot be wrapped by a proxy class, for 
example a pointer to a primitive type. In these situations a <i>type wrapper class</i> is generated.
Wrapping an enum generates an <i>enum class</i>, either a proper Java enum or a Java class that simulates the enums pattern.
Details of all these generated classes will unfold as you read this section.
</p>

<p>
The JNI (C/C++) code is generated into a file which also contains the module name, for example <tt>example_wrap.cxx</tt>
or <tt>example_wrap.c</tt>. These C or C++ files complete the contents of the module.
</p>

<p>
The generated Java classes can be placed into a Java package by using the <tt>-package</tt> commandline option.
This is often combined with the <tt>-outdir</tt> to specify a package directory for generating the Java files.
</p>

<div class="code"><pre>
swig -java -package com.bloggs.swig -outdir com/bloggs/swig example.i
</pre></div>

<p>
SWIG won't create the directory, so make sure it exists beforehand.
</p>

<H3><a name="Java_functions">25.3.2 Functions</a></H3>


<p>
There is no such thing as a global Java function so global C functions are wrapped as static methods in 
the module class. For example,
</p>

<div class="code"><pre>
%module example
int fact(int n);

</pre></div>

<p>
creates a static function that works exactly like you think it might:</p>

<div class="code"><pre>
public class example {
  public static int fact(int n) {
    // makes call using JNI to the C function
  }
}
</pre></div>


<p>
The Java class <tt>example</tt> is the <i>module class</i>. The function can be used as follows from Java:</p>

<div class="code"><pre>
System.out.println(example.fact(4));
</pre></div>


<H3><a name="Java_global_variables">25.3.3 Global variables</a></H3>


<p>
C/C++ global variables are fully supported by SWIG.  
Java does not allow the overriding of the dot operator so all variables are accessed through getters and setters. 
Again because there is no such thing as a
Java global variable, access to C/C++ global variables is done through static getter and setter functions in the module class.
</p>

<div class="code"><pre>
// SWIG interface file with global variables
%module example
...
%inline %{
extern int My_variable;
extern double density;
%}
...
</pre></div>

<p>
Now in Java :</p>

<div class="code"><pre>
// Print out value of a C global variable
System.out.println("My_variable = " + example.getMy_variable());
// Set the value of a C global variable
example.setDensity(0.8442);
</pre></div>

<p>
The value returned by the getter will always be up to date even if the value is changed in C. 
Note that the getters and setters produced follow the JavaBean property design pattern. 
That is the first letter of the variable name is capitalized and preceded with set or get.
If you have the misfortune of wrapping two variables that differ only in the capitalization of their first letters,
use %rename to change one of the variable names. For example:
</p>

<div class="code"><pre>
%rename Clash RenamedClash;
float Clash;
int clash;
</pre></div>

<p>
If a variable is declared as <tt>const</tt>, it is wrapped as a read-only variable.  
That is only a getter is produced.
</p>

<p>
To make ordinary variables read-only, you can use the <tt>%immutable</tt> directive. For example:
</p>

<div class="code">
<pre>
%{
extern char *path;
%}
%immutable;
extern char *path;
%mutable;
</pre>
</div>

<p>
The <tt>%immutable</tt> directive stays in effect until it is explicitly disabled or cleared using
<tt>%mutable</tt>.
See the <a href="SWIG.html#SWIG_readonly_variables">Creating read-only variables</a> section for further details.
</p>

<p>
If you just want to make a specific variable immutable, supply a declaration name.  For example:
</p>

<div class="code">
<pre>
%{
extern char *path;
%}
%immutable path;
...
extern char *path;      // Read-only (due to %immutable)
</pre>
</div>


<H3><a name="Java_constants">25.3.4 Constants</a></H3>


<p>
C/C++ constants are wrapped as Java static final variables.
To create a constant, use <tt>#define</tt> or the
<tt>%constant</tt> directive.  For example:
</p>

<div class="code">
<pre>
#define PI 3.14159
#define VERSION "1.0"
%constant int FOO = 42;
%constant const char *path = "/usr/local";
</pre>
</div>

<p>
By default the generated static final variables are initialized by making a JNI call to get their value.
The constants are generated into the constants interface and look like this:
</p>

<div class="code"><pre>
public interface exampleConstants {
  public final static double PI = exampleJNI.PI_get();
  public final static String VERSION = exampleJNI.VERSION_get();
  public final static int FOO = exampleJNI.FOO_get();
  public final static String path = exampleJNI.path_get();
}
</pre></div>

<p>
Note that SWIG has inferred the C type and used an appropriate Java type that will fit the range of all possible values for the C type.
By default SWIG generates <b>runtime constants</b>. They are not <b>compiler constants</b> that can, for example, be used 
in a switch statement. This can be changed by using the <tt>%javaconst(flag)</tt> directive. It works like all
the other <a href="Customization.html#Customization_features">%feature directives</a>. The default is <tt>%javaconst(0)</tt>. 
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.
Putting it at the top of your interface file would ensure this.
Here is an example:
</p>

<div class="code"><pre>
%javaconst(1);
%javaconst(0) BIG;
%javaconst(0) LARGE;

#define EXPRESSION (0x100+5)
#define BIG 1000LL
#define LARGE 2000ULL
</pre></div>

<p>
generates:
</p>

<div class="code"><pre>
public interface exampleConstants {
  public final static int EXPRESSION = (0x100+5);
  public final static long BIG = exampleJNI.BIG_get();
  public final static java.math.BigInteger LARGE = exampleJNI.LARGE_get();
}
</pre></div>

<p>
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
a Java <tt>long</tt> is the smallest sized Java type that will take all possible values for a C <tt>long long</tt>.
Similarly for <tt>LARGE</tt>.
</p>

<p>
Be careful using the <tt>%javaconst(1)</tt> directive as not all C code will compile as Java code. For example neither the 
<tt>1000LL</tt> value for <tt>BIG</tt> nor <tt>2000ULL</tt> for <tt>LARGE</tt> above would generate valid Java code. 
The example demonstrates how you can target particular constants (<tt>BIG</tt> and <tt>LARGE</tt>) with <tt>%javaconst</tt>.
SWIG doesn't use <tt>%javaconst(1)</tt> as the default as it tries to generate code that will always compile.
However, using a <tt>%javaconst(1)</tt> at the top of your interface file is strongly recommended as the preferred compile time constants
will be generated and most C constants will compile as Java code and in any case the odd constant that doesn't can be fixed using <tt>%javaconst(0)</tt>.
</p>

<p>
There is an alternative directive which can be used for these rare constant values that won't compile as Java code.
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.
This is useful if you do not want to use either the parsed C value nor a JNI call,
such as when the C parsed value will not compile as Java code and a compile time constant is required.
The same example demonstrates this:
</p>

<div class="code"><pre>
%javaconst(1);
%javaconstvalue("new java.math.BigInteger(\"2000\")") LARGE;
%javaconstvalue(1000) BIG;

#define EXPRESSION (0x100+5)
#define BIG 1000LL
#define LARGE 2000ULL
</pre></div>

<p>
Note the string quotes for <tt>"2000"</tt> are escaped. The following is then generated:
</p>

<div class="code"><pre>
public interface exampleConstants {
  public final static int EXPRESSION = (0x100+5);
  public final static long BIG = 1000;
  public final static java.math.BigInteger LARGE = new java.math.BigInteger("2000");
}
</pre></div>

<p>
Note:  declarations declared as <tt>const</tt> are wrapped as read-only variables and
will be accessed using a getter as described in the previous section.  They
are not wrapped as constants.
The exception to this rule are static const integral values defined within a class/struct, where they are wrapped as constants, eg:.
</p>

<div class="code"><pre>
struct Maths {
  static const int FIVE = 5;
};
</pre></div>


<p>
<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.
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):
</p>

<div class="code"><pre>
public class example implements exampleConstants {
}
</pre></div>

<p>
You thus have the choice of accessing these constants from either the module class or the constants interface, for example,
<tt>example.EXPRESSION</tt> or <tt>exampleConstants.EXPRESSION</tt>.
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>.
</p>


<H3><a name="Java_enumerations">25.3.5 Enumerations</a></H3>


<p>
SWIG handles both named and unnamed (anonymous) enumerations.
There is a choice of approaches to wrapping named C/C++ enums.
This is due to historical reasons as SWIG's initial support for enums was limited and Java did not originally have support for enums.
Each approach has advantages and disadvantages and it is important for the user to decide which is the most appropriate solution.
There are four approaches of which the first is the default approach based on the so called Java typesafe enum pattern.
The second generates proper Java enums.
The final two approaches use simple integers for each enum item.
Before looking at the various approaches for wrapping named C/C++ enums, anonymous enums are considered.
</p>

<H4><a name="Java_anonymous_enums">25.3.5.1 Anonymous enums</a></H4>


<p>
There is no name for anonymous enums and so they are handled like constants. For example:
</p>

<div class="code">
<pre>
enum { ALE, LAGER=10, STOUT, PILSNER, PILZ=PILSNER };
</pre>
</div>

<p>
is wrapped into the constants interface, in a similar manner as constants (see previous section):
</p>

<div class="code"><pre>
public interface exampleConstants {
  public final static int ALE = exampleJNI.ALE_get();
  public final static int LAGER = exampleJNI.LAGER_get();
  public final static int STOUT = exampleJNI.STOUT_get();
  public final static int PILSNER = exampleJNI.PILSNER_get();
  public final static int PILZ = exampleJNI.PILZ_get();
}
</pre></div>

<p>
The <tt>%javaconst(flag)</tt> and <tt>%javaconstvalue(value)</tt> directive introduced in the previous section on constants can also be used with enums.
As is the case for constants, the default is <tt>%javaconst(0)</tt> as not all C values will compile as Java code.
However, it is strongly recommended to add in a <tt>%javaconst(1)</tt> directive at the top of your 
interface file as it is only on very rare occasions that this will produce code that won't compile under Java.
Using <tt>%javaconst(1)</tt> will ensure compile time constants are generated, thereby allowing the enum values to be used in Java switch statements. 
Example usage:
</p>

<div class="code">
<pre>
%javaconst(1);
%javaconst(0) PILSNER;
enum { ALE, LAGER=10, STOUT, PILSNER, PILZ=PILSNER };
</pre>
</div>

<p>
generates:
</p>

<div class="code"><pre>
public interface exampleConstants {
  public final static int ALE = 0;
  public final static int LAGER = 10;
  public final static int STOUT = LAGER + 1;
  public final static int PILSNER = exampleJNI.PILSNER_get();
  public final static int PILZ = PILSNER;
}
</pre></div>

<p>
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>.
</p>


<H4><a name="Java_typesafe_enums">25.3.5.2 Typesafe enums</a></H4>


<p>
This is the default approach to wrapping named enums.
The typesafe enum pattern is a relatively well known construct to work around the lack of enums in versions of Java prior to JDK 1.5.
It basically defines a class for the enumeration and permits a limited number of final static instances of the class.
Each instance equates to an enum item within the enumeration.
The implementation is in the "enumtypesafe.swg" file.
Let's look at an example:
</p>

<div class="code">
<pre>
%include "enumtypesafe.swg" // optional as typesafe enums are the default
enum Beverage { ALE, LAGER=10, STOUT, PILSNER, PILZ=PILSNER };
</pre>
</div>

<p>will generate:</p>

<div class="code">
<pre>
public final class Beverage {
  public final static Beverage ALE = new Beverage("ALE");
  public final static Beverage LAGER = new Beverage("LAGER", exampleJNI.LAGER_get());
  public final static Beverage STOUT = new Beverage("STOUT");
  public final static Beverage PILSNER = new Beverage("PILSNER");
  public final static Beverage PILZ = new Beverage("PILZ", exampleJNI.PILZ_get());
  [... additional support methods omitted for brevity ...]
}
</pre>
</div>

<p>
See <a href="#Java_typesafe_enums_classes">Typesafe enum classes</a> to see the omitted support methods.
Note that the enum item with an initializer (LAGER) is initialized with the enum value obtained via a JNI call.
However, as with anonymous enums and constants, use of the <tt>%javaconst</tt> directive is strongly recommended to change this behaviour:
</p>

<div class="code">
<pre>
%include "enumtypesafe.swg" // optional as typesafe enums are the default
%javaconst(1);
enum Beverage { ALE, LAGER=10, STOUT, PILSNER, PILZ=PILSNER };
</pre>
</div>

<p>
will generate:
</p>

<div class="code">
<pre>
public final class Beverage {
  public final static Beverage ALE = new Beverage("ALE");
  public final static Beverage LAGER = new Beverage("LAGER", 10);
  public final static Beverage STOUT = new Beverage("STOUT");
  public final static Beverage PILSNER = new Beverage("PILSNER");
  public final static Beverage PILZ = new Beverage("PILZ", PILSNER);
  [... additional support methods omitted for brevity ...]
}
</pre>
</div>

<p>
The generated code is easier to read and more efficient as a true constant is used instead of a JNI call.
As is the case for constants, the default is <tt>%javaconst(0)</tt> as not all C values will compile as Java code.
However, it is recommended to add in a <tt>%javaconst(1)</tt> directive at the top of your 
interface file as it is only on very rare occasions that this will produce code that won't compile under Java.
The <tt>%javaconstvalue(value)</tt> directive can also be used for typesafe enums.
Note that global enums are generated into a Java class within whatever package you are using.
C++ enums defined within a C++ class are generated into a static final inner Java class within the Java proxy class.
</p>

<p>
Typesafe enums have their advantages over using plain integers in that they can be used in a typesafe manner.
However, there are limitations. For example, they cannot be used in switch statements and serialization is an issue.
Please look at the following references for further information: 

         http://java.sun.com/developer/Books/shiftintojava/page1.html#replaceenums
<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,
<a href="http://www.javaworld.com/javaworld/jw-07-1997/jw-07-enumerated.html">Create enumerated constants in Java</a> JavaWorld article,
<a href="http://www.javaworld.com/javaworld/javatips/jw-javatip133.html">Java Tip 133: More on typesafe enums</a> and
<a href="http://www.javaworld.com/javaworld/javatips/jw-javatip122.html">Java Tip 122: Beware of Java typesafe enumerations</a> JavaWorld tips.
</p>

<p>
Note that the syntax required for using typesafe enums is the same as that for proper Java enums.
This is useful during the period that a project has to support legacy versions of Java.
When upgrading to JDK 1.5 or later, proper Java enums could be used instead, without users having to change their code.
The following section details proper Java enum generation.
</p>

<H4><a name="Java_proper_enums">25.3.5.3 Proper Java enums</a></H4>


<p>
Proper Java enums were only introduced in JDK 1.5 so this approach is only compatible with more recent versions of Java.
Java enums have been designed to overcome all the limitations of both typesafe and type unsafe enums
and should be the choice solution, provided older versions of Java do not have to be supported.
In this approach, each named C/C++ enum is wrapped by a Java enum.
Java enums, by default, do not support enums with initializers.
Java enums are in many respects similar to Java classes in that they can be customised with additional methods.
SWIG takes advantage of this feature to facilitate wrapping C/C++ enums that have initializers.
In order to wrap all possible C/C++ enums using proper Java enums, the "enums.swg" file must be used.
Let's take a look at an example.
</p>

<div class="code">
<pre>
%include "enums.swg"
%javaconst(1);
enum Beverage { ALE, LAGER=10, STOUT, PILSNER, PILZ=PILSNER };
</pre>
</div>

<p>
will generate:
</p>

<div class="code">
<pre>
public enum Beverage {
  ALE,
  LAGER(10),
  STOUT,
  PILSNER,
  PILZ(PILSNER);
  [... additional support methods omitted for brevity ...]
}
</pre>
</div>

<p>
See <a href="#Java_proper_enums_classes">Proper Java enum classes</a> to see the omitted support methods.
The generated Java enum has numerous additional methods to support enums with initializers, such as <tt>LAGER</tt> above.
Note that as with the typesafe enum pattern, enum items with initializers are by default initialized with the enum value obtained via a JNI call.
However, this is not the case above as we have used the recommended <tt>%javaconst(1)</tt> to avoid the JNI call.
The <tt>%javaconstvalue(value)</tt> directive covered in the <a href="#Java_constants">Constants</a> section can also be used for proper Java enums.
</p>

<p>
The additional support methods need not be generated if none of the enum items have initializers and this is covered later in the 
<a href="#Java_simpler_enum_classes">Simpler Java enums for enums without initializers</a> section.
</p>

<H4><a name="Java_typeunsafe_enums">25.3.5.4 Type unsafe enums</a></H4>


<p>
In this approach each enum item in a named enumeration is wrapped as a static final integer in a class named after the C/C++ enum name.
This is a commonly used pattern in Java to simulate C/C++ enums, but it is not typesafe.
However, the main advantage over the typesafe enum pattern is enum items can be used in switch statements.
In order to use this approach, the "enumtypeunsafe.swg" file must be used.
Let's take a look at an example.
</p>

<div class="code">
<pre>
%include "enumtypeunsafe.swg"
%javaconst(1);
enum Beverage { ALE, LAGER=10, STOUT, PILSNER, PILZ=PILSNER };
</pre>
</div>

<p>
will generate:
</p>

<div class="code">
<pre>
public final class Beverage {
  public final static int ALE = 0;
  public final static int LAGER = 10;
  public final static int STOUT = LAGER + 1;
  public final static int PILSNER = STOUT + 1;
  public final static int PILZ = PILSNER;
}
</pre>
</div>

<p>
As is the case previously, the default is <tt>%javaconst(0)</tt> as not all C/C++ values will compile as Java code.
However, again it is recommended to add in a <tt>%javaconst(1)</tt> directive.
and the <tt>%javaconstvalue(value)</tt> directive covered in the <a href="#Java_constants">Constants</a> section can also be used for type unsafe enums.
Note that global enums are generated into a Java class within whatever package you are using.
C++ enums defined within a C++ class are generated into a static final inner Java class within the Java proxy class.
</p>

<p>
Note that unlike typesafe enums, this approach requires users to mostly use different syntax compared with proper Java enums.
Thus the upgrade path to proper enums provided in JDK 1.5 is more painful.
</p>

<H4><a name="Java_simple_enums">25.3.5.5 Simple enums</a></H4>


<p>
This approach is similar to the type unsafe approach.
Each enum item is also wrapped as a static final integer.
However, these integers are not generated into a class named after the C/C++ enum.
Instead, global enums are generated into the constants interface.
Also, enums defined in a C++ class have their enum items generated directly into the Java proxy class rather than an inner class within the Java proxy class.
In fact, this approach is effectively wrapping the enums as if they were anonymous enums and the resulting code is as per <a href="#Java_anonymous_enums">anonymous enums</a>.
The implementation is in the "enumsimple.swg" file.
</p>

<p>
<b>Compatibility Note:</b>
SWIG-1.3.21 and earlier versions wrapped all enums using this approach.
The type unsafe approach is preferable to this one and this simple approach is only included for backwards compatibility with these earlier versions of SWIG.
</p>

<H3><a name="Java_pointers">25.3.6 Pointers</a></H3>


<p>
C/C++ pointers are fully supported by SWIG.  Furthermore, SWIG has no problem working with
incomplete type information.  Here is a rather simple interface:
</p>

<div class="code">
<pre>
%module example

FILE *fopen(const char *filename, const char *mode);
int fputs(const char *, FILE *);
int fclose(FILE *);
</pre>
</div>

<p>
When wrapped, you will be able to use the functions in a natural way from Java. For example:
</p>

<div class="code">
<pre>
SWIGTYPE_p_FILE f = example.fopen("junk","w");
example.fputs("Hello World\n", f);
example.fclose(f);
</pre>
</div>

<p>
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.
Many other SWIG language modules use an encoding of the pointer in a string. 
These scripting languages use the SWIG runtime type checker for dynamic type checking as they do not support static type checking by a compiler.
In order to implement static type checking of pointers within Java, they are wrapped by a simple Java class. 
In the example above the <tt>FILE *</tt> pointer is wrapped with a <i>type wrapper class </i> 
called <tt>SWIGTYPE_p_FILE</tt>.
</p>

<p>
Once obtained, a type wrapper object can be freely passed around to different C functions that
expect to receive an object of that type.  The only thing you can't do is 
dereference the pointer from Java. Of course, that isn't much of a concern in this example.
</p>

<p>
As much as you might be inclined to modify a pointer value directly
from Java, don't.  The value is not necessarily the
same as the logical memory address of the underlying object.  The value will
vary depending on the native byte-ordering of the platform (i.e.,
big-endian vs. little-endian).  
Most JVMs are 32 bit applications so any JNI code must also be compiled as 32 bit. 
The net result is pointers in JNI code are also 32 bits and 
are stored in the high order 4 bytes on big-endian machines and in the low order 4 bytes on little-endian machines. 
By design it is also not possible to manually cast
a pointer to a new type by using Java casts as it is particularly dangerous especially when
casting C++ objects.  If you need to cast a pointer or
change its value, consider writing some helper functions instead.  For
example:
</p>

<div class="code">
<pre>
%inline %{
/* C-style cast */
Bar *FooToBar(Foo *f) {
   return (Bar *) f;
}

/* C++-style cast */
Foo *BarToFoo(Bar *b) {
   return dynamic_cast&lt;Foo*&gt;(b);
}

Foo *IncrFoo(Foo *f, int i) {
    return f+i;
}
%}
</pre>
</div>

<p>
Also, if working with C++, you should always try
to use the new C++ style casts.  For example, in the above code, the
C-style cast may return a bogus result whereas as the C++-style cast will return
a NULL pointer if the conversion can't be performed.
</p>

<H3><a name="Java_structures">25.3.7 Structures</a></H3>


<p>
If you wrap a C structure, it is wrapped by a Java class with getters and setters for access to the
member variables. For example,
</p>

<div class="code"><pre>
struct Vector {
  double x,y,z;
};

</pre></div>

<p>
is used as follows:
</p>

<div class="code"><pre>
Vector v = new Vector();
v.setX(3.5);
v.setY(7.2);
double x = v.getX();
double y = v.getY();
</pre></div>

<p>
The variable setters and getters are also based on the JavaBean design pattern already covered under the Global variables section.
Similar access is provided for unions and the public data members of C++ classes.</p>

<p>
This object is actually an instance of a Java class that has been wrapped around a pointer to the C structure.  
This instance doesn't actually do anything--it just serves as a proxy.
The pointer to the C object is held in the Java proxy class in much the same way as pointers are held by type wrapper classes.
Further details about Java proxy classes are covered a little later.
</p>

<p>
<tt>const</tt> members of a structure are read-only. Data members
can also be forced to be read-only using the <tt>%immutable</tt> directive. For example:
</p>

<div class="code">
<pre>
struct Foo {
   ...
   %immutable;
   int x;        /* Read-only members */
   char *name;
   %mutable;
   ...
};
</pre>
</div>

<p>
When <tt>char *</tt> members of a structure are wrapped, the contents are assumed to be
dynamically allocated using <tt>malloc</tt> or <tt>new</tt> (depending on whether or not
SWIG is run with the -c++ option).   When the structure member is set, the old contents will be 
released and a new value created.   If this is not the behavior you want, you will have to use
a typemap (described later).
</p>

<p>
If a structure contains arrays, access to those arrays is managed through pointers.  For
example, consider this:
</p>

<div class="code">
<pre>
struct Bar {
    int  x[16];
};
</pre>
</div>

<p>
If accessed in Java, you will see behavior like this:
</p>

<div class="code">
<pre>
Bar b = new Bar();
SWIGTYPE_p_int x = b.getX();
</pre>
</div>

<p>
This pointer can be passed around to functions that expect to receive
an <tt>int *</tt> (just like C).   You can also set the value of an array member using
another pointer.  For example:
</p>

<div class="code">
<pre>
Bar b = new Bar();
SWIGTYPE_p_int x = b.getX();
Bar c = new Bar();
c.setX(x);                    // Copy contents of b.x to c.x
</pre>
</div>

<p>
For array assignment (setters not getters), SWIG copies the entire contents of the array starting with the data pointed
to by <tt>b.x</tt>.   In this example, 16 integers would be copied.  Like C, SWIG makes
no assumptions about bounds checking---if you pass a bad pointer, you may get a segmentation
fault or access violation.
The default wrapping makes it hard to set or get just one element of the array and so array access from Java is somewhat limited.
This can be changed easily though by using the approach outlined later in the <a href="#Java_c_arrays">Wrapping C arrays with Java arrays</a> and
<a href="#Java_unbounded_c_arrays">Unbounded C Arrays</a> sections.
</p>

<p>
When a member of a structure is itself a structure, it is handled as a
pointer.  For example, suppose you have two structures like this:
</p>

<div class="code">
<pre>
struct Foo {
   int a;
};

struct Bar {
   Foo f;
};
</pre>
</div>

<p>
Now, suppose that you access the <tt>f</tt> member of <tt>Bar</tt> like this:
</p>

<div class="code">
<pre>
Bar b = new Bar();
Foo x = b.getF();
</pre>
</div>

<p>
In this case, <tt>x</tt> is a pointer that points to the <tt>Foo</tt> that is inside <tt>b</tt>.
This is the same value as generated by this C code:
</p>

<div class="code">
<pre>
Bar b;
Foo *x = &amp;b-&gt;f;       /* Points inside b */
</pre>
</div>

<p>
Because the pointer points inside the structure, you can modify the contents and 
everything works just like you would expect. For example:
</p>

<div class="code">
<pre>
Bar b = new Bar();
b.getF().setA(3);   // Modify b.f.a
Foo x = b.getF();                   
x.setA(3);          // Modify x.a - this is the same as b.f.a
</pre>
</div>


<H3><a name="Java_classes">25.3.8 C++ classes</a></H3>


<p>
C++ classes are wrapped by Java classes as well. For example, if you have this class,
</p>

<div class="code"><pre>
class List {
public:
  List();
  ~List();
  int  search(char *item);
  void insert(char *item);
  void remove(char *item);
  char *get(int n);
  int  length;
};
</pre></div>

<p>
you can use it in Java like this:
</p>

<div class="code"><pre>
List l = new List();
l.insert("Ale");
l.insert("Stout");
l.insert("Lager");
String item = l.get(2);
int length = l.getLength();
</pre></div>

<p>
Class data members are accessed in the same manner as C structures.  
</p>

<p>
Static class members are unsurprisingly wrapped as static members of the Java class:
</p>

<div class="code">
<pre>
class Spam {
public:
   static void foo();
   static int bar;
};
</pre>
</div>

<p>
The static members work like any other Java static member:
</p>

<div class="code">
<pre>
Spam.foo();
int bar = Spam.getBar();
</pre>
</div>


<H3><a name="Java_inheritance">25.3.9 C++ inheritance</a></H3>


<p>
SWIG is fully aware of issues related to C++ inheritance.  Therefore, if you have
classes like this
</p>

<div class="code">
<pre>
class Foo {
...
};

class Bar : public Foo {
...
};
</pre>
</div>

<p>
those classes are wrapped into a hierarchy of Java classes that reflect the same inheritance
structure:
</p>

<div class="code">
<pre>
Bar b = new Bar();
Class c = b.getClass();
System.out.println(c.getSuperclass().getName());
</pre>
</div>

<p>
will of course display:
</p>

<div class="code"><pre>
Foo
</pre></div>


<p>
Furthermore, if you have functions like this
</p>

<div class="code">
<pre>
void spam(Foo *f);
</pre>
</div>

<p>
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>.
</p>

<p>
Note that Java does not support multiple inheritance so any multiple inheritance in the C++ code is not going to work. 
A warning is given when multiple inheritance is detected and only the first base class is used. 
</p>

<H3><a name="Java_pointers_refs_arrays">25.3.10 Pointers, references, arrays and pass by value</a></H3>


<p>
In C++, there are many different ways a function might receive
and manipulate objects.  For example:
</p>

<div class="code">
<pre>
void spam1(Foo *x);      // Pass by pointer
void spam2(Foo &amp;x);      // Pass by reference
void spam3(Foo x);       // Pass by value
void spam4(Foo x[]);     // Array of objects
</pre>
</div>

<p>
In Java, there is no detailed distinction like this--specifically,
there are only instances of classes.  There are no pointers nor references.
Because of this, SWIG unifies all of these types
together in the wrapper code.  For instance, if you actually had the
above functions, it is perfectly legal to do this from Java:
</p>

<div class="code">
<pre>
Foo f = new Foo();  // Create a Foo
example.spam1(f);   // Ok. Pointer
example.spam2(f);   // Ok. Reference
example.spam3(f);   // Ok. Value.
example.spam4(f);   // Ok. Array (1 element)
</pre>
</div>

<p>
Similar behavior occurs for return values.  For example, if you had
functions like this,
</p>

<div class="code">
<pre>
Foo *spam5();
Foo &amp;spam6();
Foo  spam7();
</pre>
</div>

<p>
then all three functions will return a pointer to some <tt>Foo</tt> object.
Since the third function (spam7) returns a value, newly allocated memory is used 
to hold the result and a pointer is returned (Java will release this memory 
when the returned object's finalizer is run by the garbage collector).
</p>

<H4><a name="Java_null_pointers">25.3.10.1 Null pointers</a></H4>


<p>
Working with null pointers is easy. 
A Java <tt>null</tt> can be used whenever a method expects a proxy class or typewrapper class.
However, it is not possible to pass null to C/C++ functions that take parameters by value or by reference. 
If you try you will get a NullPointerException.
</p>

<div class="code">
<pre>
example.spam1(null);   // Pointer - ok
example.spam2(null);   // Reference - NullPointerException
example.spam3(null);   // Value - NullPointerException
example.spam4(null);   // Array - ok
</pre>
</div>

<p>
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. 
The converse also occurs, that is, NULL pointers are translated into <tt>null</tt> Java objects when returned from a C/C++ function.
</p>

<H3><a name="Java_overloaded_functions">25.3.11 C++ overloaded functions</a></H3>


<p>
C++ overloaded functions, methods, and constructors are mostly supported by SWIG.  For example,
if you have two functions like this:
</p>

<div class="code">
<pre>
%module example

void foo(int);
void foo(char *c);
</pre>
</div>

<p>
You can use them in Java in a straightforward manner:
</p>

<div class="code">
<pre>
example.foo(3);           // foo(int)
example.foo("Hello");     // foo(char *c)
</pre>
</div>

<p>
Similarly, if you have a class like this,
</p>

<div class="code">
<pre>
class Foo {
public:
    Foo();
    Foo(const Foo &amp;);
    ...
};
</pre>
</div>

<p>
you can write Java code like this:
</p>

<div class="code">
<pre>
Foo f = new Foo();        // Create a Foo
Foo g = new Foo(f);       // Copy f
</pre>
</div>

<p>
Overloading support is not quite as flexible as in C++. Sometimes there are methods that SWIG
cannot disambiguate as there can be more than one C++ type mapping onto a single Java type. For example:
</p>

<div class="code">
<pre>
void spam(int);
void spam(unsigned short);
</pre>
</div>

<p>
Here both int and unsigned short map onto a Java int. 
Here is another example:
</p>

<div class="code">
<pre>
void foo(Bar *b);
void foo(Bar &amp;b);
</pre>
</div>

<p>
If declarations such as these appear, you will get a warning message like this:
</p>

<div class="code">
<pre>
example.i:12: Warning 515: Overloaded method spam(unsigned short) ignored.
Method spam(int) at example.i:11 used.
</pre>
</div>

<p>
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:
</p>

<div class="code">
<pre>
%rename(spam_ushort) spam(unsigned short);
...
void spam(int);    
void spam(unsigned short);   // Now renamed to spam_ushort
</pre>
</div>

<p>
or
</p>

<div class="code">
<pre>
%ignore spam(unsigned short);
...
void spam(int);    
void spam(unsigned short);   // Ignored
</pre>
</div>

<H3><a name="Java_default_arguments">25.3.12 C++ default arguments</a></H3>


<p>
Any function with a default argument is wrapped by generating an additional function for each argument that is defaulted.
For example, if we have the following C++:
</p>

<div class="code">
<pre>
%module example

void defaults(double d=10.0, int i=0);
</pre>
</div>

<p>
The following methods are generated in the Java module class:
</p>

<div class="code">
<pre>
public class example {
  public static void defaults(double d, int i) { ... }
  public static void defaults(double d) { ... }
  public static void defaults() { ... }
}
</pre>
</div>

<p>
It is as if SWIG had parsed three separate overloaded methods.
The same approach is taken for static methods, constructors and member methods.
</p>

<p>
<b>Compatibility note:</b> Versions of SWIG prior to SWIG-1.3.23 wrapped these with a
single wrapper method and so the default values could not be taken advantage of from Java.
Further details on default arguments and how to restore this approach are given in the more general 
<a href="SWIGPlus.html#SWIGPlus_default_args">Default arguments</a> section.
</p>


<H3><a name="Java_namespaces">25.3.13 C++ namespaces</a></H3>


<p>
SWIG is aware of named C++ namespaces and they can be mapped to Java packages, however, 
the default wrapping flattens the namespaces, effectively ignoring them.
So by default, the namespace names do not appear in
the module nor do namespaces result in a module that is broken up into
submodules or packages.  For example, if you have a file like this,
</p>

<div class="code">
<pre>
%module example

namespace foo {
   int fact(int n);
   struct Vector {
       double x,y,z;
   };
};
</pre>
</div>

<p>
it works in Java as follows:
</p>

<div class="code">
<pre>
int f = example.fact(3);
Vector v = new Vector();
v.setX(3.4);
double y = v.getY();
</pre>
</div>

<p>
If your program has more than one namespace, name conflicts (if any) can be resolved using <tt>%rename</tt>
For example:
</p>

<div class="code">
<pre>
%rename(Bar_spam) Bar::spam;

namespace Foo {
    int spam();
}

namespace Bar {
    int spam();
}
</pre>
</div>

<p>
If you have more than one namespace and you want to keep their
symbols separate, consider wrapping them as separate SWIG modules.
Each SWIG module can be placed into a separate package.
</p>

<p>
The default behaviour described above can be improved via the <a href="SWIGPlus.html#SWIGPlus_nspace">nspace feature</a>.
Note that it only works for classes, structs, unions and enums declared within a named C++ namespace.
When the nspace feature is used, the C++ namespaces are converted into Java packages of the same name.
Proxy classes are thus declared within a package and this proxy makes numerous calls to the JNI intermediary class which is declared in the unnamed package by default.
As Java does not support types declared in a named package accessing types declared in an unnamed package, the <tt>-package</tt> commandline option described earlier generally should be used to provide a parent package.
So if SWIG is run using the <tt>-package com.myco</tt> option, a wrapped class, <tt>MyWorld::Material::Color</tt>, can then be accessed as <tt>com.myco.MyWorld.Material.Color</tt>.
If you don't specify a package, you will get the following warning:
</p>

<div class="shell">
<pre>
example.i:16: Warning 826: The nspace feature is used on 'MyWorld::Material::Color' without -package. The generated code 
may not compile as Java does not support types declared in a named package accessing types declared in an unnamed package.
</pre>
</div>

<p>
If it is undesirable to have a single top level package, the nspace feature may be used without the <tt>-package</tt> commandline option
(and the resulting warning ignored) if all of the types exposed using SWIG are placed in a package using the nspace feature and the
'jniclasspackage' pragma is used to specify a package for the JNI intermediary class.
</p>

<p>
If the resulting use of the nspace feature and hence packages results in a proxy class in one package deriving or using a proxy class from another package,
you will need to open up the visibility for the pointer constructor and <tt>getCPtr</tt> method from the default 'protected' to 'public' with the <tt>SWIG_JAVABODY_PROXY</tt> macro. See <a href="#Java_code_typemaps">Java code typemaps</a>.
</p>

<H3><a name="Java_templates">25.3.14 C++ templates</a></H3>


<p>
C++ templates don't present a huge problem for SWIG.  However, in order
to create wrappers, you have to tell SWIG to create wrappers for a particular
template instantiation.  To do this, you use the <tt>%template</tt> directive.
For example:
</p>

<div class="code">
<pre>
%module example
%{
#include &lt;utility&gt;
%}

template&lt;class T1, class T2&gt;
struct pair {
   typedef T1 first_type;
   typedef T2 second_type;
   T1 first;
   T2 second;
   pair();
   pair(const T1&amp;, const T2&amp;);
  ~pair();
};

%template(pairii) pair&lt;int,int&gt;;
</pre>
</div>

<p>
In Java:
</p>

<div class="code">
<pre>
pairii p = new pairii(3,4);
int first = p.getFirst();
int second = p.getSecond();
</pre>
</div>

<p>
Obviously, there is more to template wrapping than shown in this example.
More details can be found in the <a href="SWIGPlus.html#SWIGPlus">SWIG and C++</a> chapter.   
</p>

<H3><a name="Java_smart_pointers">25.3.15 C++ Smart Pointers</a></H3>


<H4><a name="Java_smart_pointers_shared_ptr">25.3.15.1 The shared_ptr Smart Pointer</a></H4>


<p>
The C++11 standard provides <tt>std::shared_ptr</tt> which was derived from the Boost
implementation, <tt>boost::shared_ptr</tt>.
Both of these are available for Java in the SWIG library and usage is outlined
in the <a href="Library.html#Library_std_shared_ptr">shared_ptr smart pointer</a> library section.
</p>


<H4><a name="Java_smart_pointers_generic">25.3.15.2 Generic Smart Pointers</a></H4>


<p>
In certain C++ programs, it is common to use classes that have been wrapped by
so-called "smart pointers."   Generally, this involves the use of a template class
that implements <tt>operator-&gt;()</tt> like this:
</p>

<div class="code">
<pre>
template&lt;class T&gt; class SmartPtr {
   ...
   T *operator-&gt;();
   ...
}
</pre>
</div>

<p>
Then, if you have a class like this,
</p>

<div class="code">
<pre>
class Foo {
public:
     int x;
     int bar();
};
</pre>
</div>

<p>
A smart pointer would be used in C++ as follows:
</p>

<div class="code">
<pre>
SmartPtr&lt;Foo&gt; p = CreateFoo();   // Created somehow (not shown)
...
p-&gt;x = 3;                        // Foo::x
int y = p-&gt;bar();                // Foo::bar
</pre>
</div>

<p>
To wrap this in Java, simply tell SWIG about the <tt>SmartPtr</tt> class and the low-level
<tt>Foo</tt> object.  Make sure you instantiate <tt>SmartPtr</tt> using <tt>%template</tt> if necessary.
For example:
</p>

<div class="code">
<pre>
%module example
...
%template(SmartPtrFoo) SmartPtr&lt;Foo&gt;;
...
</pre>
</div>

<p>
Now, in Java, everything should just "work":
</p>

<div class="code">
<pre>
SmartPtrFoo p = example.CreateFoo(); // Create a smart-pointer somehow
p.setX(3);                           // Foo::x
int y = p.bar();                     // Foo::bar
</pre>
</div>

<p>
If you ever need to access the underlying pointer returned by <tt>operator-&gt;()</tt> itself,
simply use the <tt>__deref__()</tt> method.  For example:
</p>

<div class="code">
<pre>
Foo f = p.__deref__();               // Returns underlying Foo *
</pre>
</div>

<H2><a name="Java_further_details">25.4 Further details on the generated Java classes</a></H2>


<p>
In the previous section, a high-level view of Java wrapping was
presented.  A key component of this wrapping is that structures and
classes are wrapped by Java proxy classes and type wrapper classes are used
in situations where no proxies are generated.  This provides a very
natural, type safe Java interface to the C/C++ code and fits in with the Java programming paradigm.
However, a number of low-level details were omitted.  This section provides a brief overview
of how the proxy classes work and then covers the type wrapper classes.
Finally enum classes are covered.
First, the crucial intermediary JNI class is considered.
</p>

<H3><a name="Java_imclass">25.4.1 The intermediary JNI class</a></H3>


<p>
In the <a href="SWIG.html#SWIG">"SWIG basics"</a> and <a href="SWIGPlus.html#SWIGPlus">"SWIG and C++"</a> chapters,
details of low-level structure and class wrapping are described.  To summarize those chapters, if you
have a global function and class like this
</p>

<div class="code">
<pre>
class Foo {
public:
     int x;
     int spam(int num, Foo* foo);
};
void egg(Foo* chips);
</pre>
</div>

<p>
then SWIG transforms the class into a set of low-level procedural wrappers.
These procedural wrappers essentially perform the equivalent of this C++ code:
</p>

<div class="code">
<pre>
Foo *new_Foo() {
    return new Foo();
}
void delete_Foo(Foo *f) {
    delete f;
}
int Foo_x_get(Foo *f) {
    return f-&gt;x;
}
void Foo_x_set(Foo *f, int value) {
    f-&gt;x = value;
}
int Foo_spam(Foo *f, int num, Foo* foo) {
    return f-&gt;spam(num, foo);
}
</pre>
</div>

<p>
These procedural function names don't actually exist, but their functionality appears inside the generated
JNI functions. The JNI functions have to follow a particular naming convention so the function names are actually:
</p>

<div class="code">
<pre>
SWIGEXPORT jlong JNICALL Java_exampleJNI_new_1Foo(JNIEnv *jenv, jclass jcls);
SWIGEXPORT void JNICALL Java_exampleJNI_delete_1Foo(JNIEnv *jenv, jclass jcls,
                                                    jlong jarg1);
SWIGEXPORT void JNICALL Java_exampleJNI_Foo_1x_1set(JNIEnv *jenv, jclass jcls,
                                                    jlong jarg1, jobject jarg1_, jint jarg2);
SWIGEXPORT jint JNICALL Java_exampleJNI_Foo_1x_1get(JNIEnv *jenv, jclass jcls,
                                                    jlong jarg1, jobject jarg1_);
SWIGEXPORT jint JNICALL Java_exampleJNI_Foo_1spam(JNIEnv *jenv, jclass jcls,
                                                  jlong jarg1, jobject jarg1_, jint jarg2,
                                                  jlong jarg3, jobject jarg3_);
SWIGEXPORT void JNICALL Java_exampleJNI_egg(JNIEnv *jenv, jclass jcls,
                                            jlong jarg1, jobject jarg1_);
</pre>
</div>

<p>
For every JNI C function there has to be a static native Java function. These appear in the intermediary JNI class:
</p>

<div class="code">
<pre>
class exampleJNI {
  public final static native long new_Foo();
  public final static native void delete_Foo(long jarg1);
  public final static native void Foo_x_set(long jarg1, Foo jarg1_, int jarg2);
  public final static native int Foo_x_get(long jarg1, Foo jarg1_);
  public final static native int Foo_spam(long jarg1, Foo jarg1_, int jarg2,
                                          long jarg3, Foo jarg3_);
  public final static native void egg(long jarg1, Foo jarg1_);
}
</pre>
</div>

<p>
This class contains the complete Java - C/C++ interface so all function calls go via this class. 
As this class acts as a go-between for all JNI calls to C/C++ code from the Java <a href="#Java_proxy_classes">proxy classes</a>, <a href="#Java_type_wrapper_classes">type wrapper classes</a> and <a href="#Java_module_class">module class</a>, it is known as the intermediary JNI class.
</p>

<p>
You may notice that SWIG uses a Java long wherever a pointer or class object needs to be marshalled across the Java-C/C++ boundary.
This approach leads to minimal JNI code which makes for better performance as JNI code involves a lot of string manipulation.
SWIG favours generating Java code over JNI code as Java code is compiled into byte code and avoids the costly string operations needed in JNI code.
This approach has a downside though as the proxy class might get collected before the native method has completed.
You might notice above that there is an additional parameters with a underscore postfix, eg <tt>jarg1_</tt>.
These are added in order to prevent <a href="#Java_pgcpp">premature garbage collection when marshalling proxy classes</a>.
</p>

<p>
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.
</p>

<a name="Java_module_directive"></a>
<p>
The name of the intermediary JNI class can be changed from its default, that is, the module name with JNI appended after it. 
The module directive attribute <tt>jniclassname</tt> is used to achieve this:
</p>

<div class="code">
<pre>
%module (jniclassname="name") modulename
</pre>
</div>

<p>
If <tt>name</tt> is the same as <tt>modulename</tt> then the module class name gets changed
from <tt>modulename</tt> to <tt>modulenameModule</tt>.
</p>

<H4><a name="Java_imclass_pragmas">25.4.1.1 The intermediary JNI class pragmas</a></H4>


<p>
The intermediary JNI class can be tailored through the use of pragmas, but is not commonly done. The pragmas for this class are:
</p>

<table BORDER summary="Intermediary JNI class pragmas">
<tr VALIGN=TOP>
<td><b>Pragma</b></td>
<td><b>Description</b></td>
</tr>

<tr>
    <td>jniclassbase            </td> <td>Base class for the intermediary JNI class</td>
</tr>
<tr>
    <td>jniclasspackage         </td> <td>Package in which to place the intermediary JNI class</td>
</tr>
<tr>
    <td>jniclassclassmodifiers  </td> <td>Class modifiers and class type for the intermediary JNI class</td>
</tr>
<tr>
    <td>jniclasscode            </td> <td>Java code is copied verbatim into the intermediary JNI class</td>
</tr>
<tr>
    <td>jniclassimports         </td> <td>Java code, usually one or more import statements, placed before the intermediary JNI class definition</td>
</tr>
<tr>
    <td>jniclassinterfaces      </td> <td>Comma separated interface classes for the intermediary JNI class</td>
</tr>
</table>

<p>
The pragma code appears in the generated intermediary JNI class where you would expect:
</p>

<div class="code">
<pre>
[ jniclassimports pragma ]
[ jniclassclassmodifiers pragma ] jniclassname extends [ jniclassbase pragma ]
                                          implements [ jniclassinterfaces pragma ] {
[ jniclasscode pragma ]
... SWIG generated native methods ...
}
</pre>
</div>

<p>
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:
</p>

<div class="code">
<pre>
%pragma(java) jniclasscode=%{
  static {
    try {
        System.loadLibrary("example");
    } catch (UnsatisfiedLinkError e) {
      System.err.println("Native code library failed to load. \n" + e);
      System.exit(1);
    }
  }
%}
</pre>
</div>

<p>
Pragmas will take either <tt>""</tt> or <tt>%{ %}</tt> as delimiters. 
For example, let's change the intermediary JNI class access to just the default package-private access. 
</p>

<div class="code">
<pre>
%pragma(java) jniclassclassmodifiers="class"
</pre>
</div>

<p>
All the methods in the intermediary JNI class will then not be callable outside of the package as the method modifiers have been changed from public access to default access. This is useful if you want to prevent users calling these low level functions.
</p>

<H3><a name="Java_module_class">25.4.2 The Java module class</a></H3>


<p>
All global functions and variable getters/setters appear in the module class. For our example, there is just one function:
</p>

<div class="code">
<pre>
public class example {
  public static void egg(Foo chips) {
    exampleJNI.egg(Foo.getCPtr(chips), chips);
  }
}
</pre>
</div>

<p>
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:
</p>

<div class="code">
<pre>
example.egg(new Foo());
</pre>
</div>

<p>
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.
</p>

<H4><a name="Java_module_class_pragmas">25.4.2.1 The Java module class pragmas</a></H4>


<p>
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:
</p>

<table BORDER summary="Java module class pragmas">
<tr VALIGN=TOP>
<td><b>Pragma</b></td>
<td><b>Description</b></td>
</tr>
<tr>
    <td>modulebase            </td> <td>Base class for the module class</td>
</tr>
<tr>
    <td>moduleclassmodifiers  </td> <td>Class modifiers and class type for the module class</td>
</tr>
<tr>
    <td>modulecode            </td> <td>Java code is copied verbatim into the module class</td>
</tr>
<tr>
    <td>moduleimports         </td> <td>Java code, usually one or more import statements, placed before the module class definition</td>
</tr>
<tr>
    <td>moduleinterfaces      </td> <td>Comma separated interface classes for the module class</td>
</tr>

</table>


<p>
The pragma code appears in the generated module class like this:
</p>

<div class="code">
<pre>
[ moduleimports pragma ]
[ modulemodifiers pragma ] modulename extends [ modulebase pragma ]
                                      implements [ moduleinterfaces pragma ] {
[ modulecode pragma ]
... SWIG generated wrapper functions ...
}
</pre>
</div>

<p>
See <a href="#Java_imclass_pragmas">The intermediary JNI class pragmas</a> section for further details on using pragmas.
</p>


<H3><a name="Java_proxy_classes">25.4.3 Java proxy classes</a></H3>


<p>
A Java proxy class is generated for each structure, union or C++ class that is wrapped.
Proxy classes have also been called <a href="http://java.sun.com/docs/books/jni/html/stubs.html">peer classes</a>.
The default proxy class for our previous example looks like this:
</p>

<div class="code">
<pre>
public class Foo {
  private transient long swigCPtr;
  protected transient boolean swigCMemOwn;

  protected Foo(long cPtr, boolean cMemoryOwn) {
    swigCMemOwn = cMemoryOwn;
    swigCPtr = cPtr;
  }

  protected static long getCPtr(Foo obj) {
    return (obj == null) ? 0 : obj.swigCPtr;
  }

  protected void finalize() {
    delete();
  }

  public synchronized void delete() {
    if(swigCPtr != 0 &amp;&amp; swigCMemOwn) {
      swigCMemOwn = false;
      exampleJNI.delete_Foo(swigCPtr);
    }
    swigCPtr = 0;
  }

  public void setX(int value) {
    exampleJNI.Foo_x_set(swigCPtr, this, value);
  }

  public int getX() {
    return exampleJNI.Foo_x_get(swigCPtr, this);
  }

  public int spam(int num, Foo foo) {
    return exampleJNI.Foo_spam(swigCPtr, this, num, Foo.getCPtr(foo), foo);
  }

  public Foo() {
    this(exampleJNI.new_Foo(), true);
  }

}
</pre>
</div>


<p>
This class merely holds a pointer to the underlying C++ object (<tt>swigCPtr</tt>).
It also contains all the methods in the C++ class it is proxying plus getters and setters for public
member variables. These functions call the native methods in the intermediary JNI class. 
The advantage of having this extra layer is the type safety that the proxy class functions offer. 
It adds static type checking which leads to fewer surprises at runtime. 
For example, you can see that if you attempt to use the <tt>spam()</tt>
function it will only compile when the parameters passed are an <tt>int</tt> and a <tt>Foo</tt>. 
From a user's point of view, it makes the class work as if it were a Java class:
</p>

<div class="code">
<pre>
Foo f = new Foo();
f.setX(3);
int y = f.spam(5, new Foo());
</pre>
</div>

<H4><a name="Java_memory_management">25.4.3.1 Memory management</a></H4>


<p>
Each proxy class has an ownership flag <tt>swigCMemOwn</tt>.   The value of this
flag determines who is responsible for deleting the underlying C++ object.   If set to <tt>true</tt>,
the proxy class's finalizer will destroy the C++ object when the proxy class is 
garbage collected.   If set to false, then the destruction of the proxy class has no effect on the C++ object.
</p>

<p>
When an object is created by a constructor or returned by value, Java automatically takes
ownership of the result. 
On the other hand, when pointers or references are returned to Java, there is often no way to know where
they came from.  Therefore, the ownership is set to false.  For example:
</p>


<div class="code">
<pre>
class Foo {
public:
    Foo();
    Foo bar1();
    Foo &amp;bar2();
    Foo *bar2();
};
</pre>
</div>

<p>
In Java:
</p>

<div class="code">
<pre>
Foo f = new Foo();   //  f.swigCMemOwn = true
Foo f1 = f.bar1();   // f1.swigCMemOwn = true
Foo f2 = f.bar2();   // f2.swigCMemOwn = false
Foo f3 = f.bar3();   // f3.swigCMemOwn = false
</pre>
</div>

<p>
This behavior for pointers and references is especially important for classes that act as containers.  
For example, if a method returns a pointer to an object
that is contained inside another object, you definitely don't want
Java to assume ownership and destroy it!
</p>

<p>
For the most part, memory management issues remain hidden.  However,
there are situations where you might have to manually
change the ownership of an object.  For instance, consider code like this:
</p>

<div class="code">
<pre>
class Obj {};
class Node {
   Obj *value;
public:
   void set_value(Obj *v) { value = v; }
};
</pre>
</div>

<p>
Now, consider the following Java code:
</p>

<div class="code">
<pre>
Node n = new Node();    // Create a node
{
  Obj o = new Obj();    // Create an object
  n.set_value(o);       // Set value
}                       // o goes out of scope
</pre>
</div>

<p>
In this case, the Node <tt>n</tt> is holding a reference to
<tt>o</tt> internally.  However, SWIG has no way to know that this
has occurred.  The Java proxy class still thinks that it has ownership of 
<tt>o</tt>.  As <tt>o</tt> has gone out of scope, it could be garbage collected in which case the C++ destructor
will be invoked and <tt>n</tt> will then be holding a stale-pointer to <tt>o</tt>.  If
you're lucky, you will only get a segmentation fault.
</p>

<p>
To work around this, the ownership flag of <tt>o</tt> needs changing to <tt>false</tt>. 
The ownership flag is a private member variable of the proxy class so this is not possible without some customization of the proxy class. 
This can be achieved by using a typemap to customise the proxy class with pure Java code as detailed later in the section on 
<a href="#Java_typemaps">Java typemaps</a>.
</p>

<p>
Sometimes a function will create memory and return a pointer to a newly allocated object. 
SWIG has no way of knowing this so by default the proxy class does not manage the returned object.
However, you can tell the proxy class to manage the memory if you specify the <tt>%newobject</tt> directive. Consider:
</p>

<div class="code">
<pre>
class Obj {...};
class Factory {
public:
    static Obj *createObj() { return new Obj(); }
};
</pre>
</div>

<p>
If we call the factory function, then we have to manually delete the memory:
</p>

<div class="code">
<pre>
Obj obj = Factory.createObj();   // obj.swigCMemOwn = false
...
obj.delete();
</pre>
</div>

<p>
Now add in the %newobject directive:
</p>

<div class="code">
<pre>
%newobject Factory::createObj();

class Obj {...};
class Factory {
public:
    static Obj *createObj() { return new Obj(); }
};
</pre>
</div>

<p>
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.
</p>

<div class="code">
<pre>
Obj obj = Factory.createObj();   // obj.swigCMemOwn = true;
...
</pre>
</div>

<p>
Some memory management issues are quite tricky to fix and may only be noticeable after using for a long time.
One such issue is premature garbage collection of an object created from Java and resultant usage from C++ code.
The section on typemap examples cover two such scenarios, 
<a href="#Java_memory_management_objects">Memory management for objects passed to the C++ layer</a>
and 
<a href="#Java_memory_management_member_variables">Memory management when returning references to member variables</a>
</p>


<H4><a name="Java_inheritance_mirroring">25.4.3.2 Inheritance</a></H4>


<p>
Java proxy classes will mirror C++ inheritance chains. For example, given the base class <tt>Base</tt> and its derived class <tt>Derived</tt>:
</p>

<div class="code"><pre>
class Base {
public:
  virtual double foo();
};

class Derived : public Base {
public:
  virtual double foo();
};
</pre></div>

<p>
The base class is generated much like any other proxy class seen so far:
</p>

<div class="code"><pre>
public class Base {
  private transient long swigCPtr;
  protected transient boolean swigCMemOwn;

  protected Base(long cPtr, boolean cMemoryOwn) {
    swigCMemOwn = cMemoryOwn;
    swigCPtr = cPtr;
  }

  protected static long getCPtr(Base obj) {
    return (obj == null) ? 0 : obj.swigCPtr;
  }

  protected void finalize() {
    delete();
  }

  public synchronized void delete() {
    if(swigCPtr != 0 &amp;&amp; swigCMemOwn) {
      swigCMemOwn = false;
      exampleJNI.delete_Base(swigCPtr);
    }
    swigCPtr = 0;
  }

  public double foo() {
    return exampleJNI.Base_foo(swigCPtr, this);
  }

  public Base() {
    this(exampleJNI.new_Base(), true);
  }

}
</pre></div>

<p>
The <tt>Derived</tt> class extends <tt>Base</tt> mirroring the C++ class inheritance hierarchy. 
</p>

<div class="code"><pre>
public class Derived extends Base {
  private transient long swigCPtr;

  protected Derived(long cPtr, boolean cMemoryOwn) {
    super(exampleJNI.SWIGDerivedUpcast(cPtr), cMemoryOwn);
    swigCPtr = cPtr;
  }

  protected static long getCPtr(Derived obj) {
    return (obj == null) ? 0 : obj.swigCPtr;
  }

  protected void finalize() {
    delete();
  }

  public synchronized void delete() {
    if(swigCPtr != 0 &amp;&amp; swigCMemOwn) {
      swigCMemOwn = false;
      exampleJNI.delete_Derived(swigCPtr);
    }
    swigCPtr = 0;
    super.delete();
  }

  public double foo() {
    return exampleJNI.Derived_foo(swigCPtr, this);
  }

  public Derived() {
    this(exampleJNI.new_Derived(), true);
  }

}
</pre></div>

<p>
Note the memory ownership is controlled by the base class. 
However each class in the inheritance hierarchy has its own pointer value which is obtained during construction. 
The <tt>SWIGDerivedUpcast()</tt> call converts the pointer from a <tt>Derived *</tt> to a <tt>Base *</tt>.
This is a necessity as C++ compilers are free to implement pointers in the inheritance hierarchy with different values. 
</p>

<p>
It is of course possible to extend <tt>Base</tt> using your own Java classes. 
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>. 
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.
However, true cross language polymorphism can be achieved using the <a href="#Java_directors">directors</a> feature.
</p>


<H4><a name="Java_proxy_classes_gc">25.4.3.3 Proxy classes and garbage collection</a></H4>


<p>
By default each proxy class has a <tt>delete()</tt> and a <tt>finalize()</tt> method. 
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. 
The idea is for <tt>delete()</tt> to be called when you have finished with the C/C++ object. 
Ideally you need not call <tt>delete()</tt>, but rather leave it to the garbage collector to call it from the finalizer. 
When a program exits, the garbage collector does not guarantee to call all finalizers. 
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.
Depending on what the finalizers do and which operating system you use, this may or may not be a problem. 
</p>

<p>
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. 
Say your JNI code creates memory on the heap which your finalizers should clean up, the finalizers may or may not be called before the program exits. 
In Windows and Unix all memory that a process uses is returned to the system on exit, so this isn't a problem. 
This is not the case in some operating systems like vxWorks. 
If however, your finalizer calls into JNI code invoking the C++ destructor which in turn releases a TCP/IP socket for example, there is no guarantee that it will be released. 
Note that with long running programs the garbage collector will eventually run, thereby calling any unreferenced object's finalizers.
</p>

<p>
Some not so ideal solutions are:
</p>

<ol>
<li><p>
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>
<div class="code"><i>
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.
</i></div> 
<p>In many cases you will be lucky and find that it works, but it is not to be advocated. 
Have a look at <a href="http://www.oracle.com/technetwork/java/index.html">Java web site</a> and search for <tt>runFinalizersOnExit</tt>.
</p></li>

<li><p>
From jdk1.3 onwards a new function, <tt>addShutdownHook()</tt>, was introduced which is guaranteed to be called when your program exits. 
You can encourage the garbage collector to call the finalizers, for example, add this static block to the class that has the <tt>main()</tt> function: </p>
<div class="code"><pre>
  static {
    Runtime.getRuntime().addShutdownHook( 
      new Thread() {
        public void run() { System.gc(); System.runFinalization(); }
      }
    );
  }
</pre></div>
<p>Although this usually works, the documentation doesn't guarantee that <tt>runFinalization()</tt> will actually call the finalizers. 
As 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>
</li>

<li>
<p>Call the <tt>delete()</tt> function manually which will immediately invoke the C++ destructor. 
As a suggestion it may be a good idea to set the object to null so that should the object be inadvertently used again a Java null pointer exception is thrown, the alternative would crash the JVM by using a null C pointer. 
For example given a SWIG generated class A:</p>
<div class="code"><pre>
A myA = new A();
// use myA ...
myA.delete();
// any use of myA here would crash the JVM 
myA=null;
// any use of myA here would cause a Java null pointer exception to be thrown
</pre></div>

<p>
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.
</p>
</li>

<li>
<p>
Write your own object manager in Java. 
You could derive all SWIG classes from a single base class which could track which objects have had their finalizers run, then call the rest of them on program termination.
The section on <a href="#Java_typemaps">Java typemaps</a> details how to specify a pure Java base class.
</p>
</li>
</ol>

<p>
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.
</p>

<H4><a name="Java_pgcpp">25.4.3.4 The premature garbage collection prevention parameter for proxy class marshalling</a></H4>


<p>
As covered earlier, the C/C++ struct/class pointer is stored in the proxy class as a Java long and when needed is passed
into the native method where it is cast into the appropriate type.
This approach provides very fast marshalling but could be susceptible to premature garbage collection.
Consider the following C++ code:
</p>

<div class="code"><pre>
class Wibble {
};
void wobble(Wibble &amp;w);
</pre></div>

<p>
The module class contains the Java wrapper for the global <tt>wobble</tt> method:
</p>

<div class="code"><pre>
public class example {
  ...
  public static void wobble(Wibble w) {
    exampleJNI.wobble(Wibble.getCPtr(w), w);
  }
}
</pre></div>

<p>
where <tt>example</tt> is the name of the module. 
All native methods go through the intermediary class which has the native method declared as such:
</p>

<div class="code"><pre>
public class exampleJNI {
  ...
  public final static native void wobble(long jarg1, Wibble jarg1_);
}
</pre></div>

<p>
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.
In order to understand why, consider the alternative where the intermediary class method is declared without the additional parameter:
</p>

<div class="code"><pre>
public class exampleJNI {
  ...
  public final static native void wobble(long jarg1);
}
</pre></div>

<p>
and the following simple call to <tt>wobble</tt>:
</p>

<div class="code"><pre>
{
  Wibble w = new Wibble();
  example.wobble(w);
}
</pre></div>

<p>
The hotspot compiler effectively sees something like:
</p>

<div class="code"><pre>
{
  Wibble w = new Wibble();
  long w_ptr = Wibble.getCPtr(w);
  // w is no longer reachable
  exampleJNI.wobble(w_ptr);
}
</pre></div>

<p>
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.
This means that it is a candidate for garbage collection.
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.
This in turn will call its underlying C++ destructor which 
is obviously disastrous while the method <tt>wobble</tt> is running using this object.
Even if <tt>wobble</tt> is not a long running method, it is possible for the <tt>Wibble</tt> instance to be finalized.
By passing the <tt>Wibble</tt> instance into the native method, it will not be finalized as the JVM guarantees not to
finalize any objects until the native method returns.
Effectively, the code then becomes
</p>

<div class="code"><pre>
{
  Wibble w = new Wibble();
  long w_ptr = Wibble.getCPtr(w);
  exampleJNI.wobble(w_ptr, w);
  // w is no longer reachable
}
</pre></div>

<p>
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.
</p>

<p>
The premature garbage collection prevention parameter for proxy classes is generated by default whenever proxy classes are passed by value, reference or with a pointer.
The 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.
</p>

<p>
The additional parameter does impose a slight performance overhead and the parameter generation can be suppressed globally with the <tt>-nopgcpp</tt> commandline option.
More selective suppression is possible with the 'nopgcpp' attribute in the "jtype" <a href="#Java_typemaps">Java typemap</a>.
The attribute is a flag and so should be set to "1" to enable the suppression, or it can be omitted or set to "0" to disable.
For example:
</p>

<div class="code"><pre>
%typemap(jtype, nopgcpp="1") Wibble &amp; "long"
</pre></div>

<p>
<b>Compatibility note:</b> The generation of this additional parameter did not occur in versions prior to SWIG-1.3.30.
</p>

<H4><a name="Java_multithread_libraries">25.4.3.5 Single threaded applications and thread safety</a></H4>


<p>
Single threaded Java applications using JNI need to consider thread safety.
The same applies for the C# module where the .NET wrappers use PInvoke.
Consider the C++ class:
</p>

<div class="code"><pre>
class Test {
  string str;
public:
  Test() : str("initial") {}
};
</pre></div>

<p>
and the Java proxy class generated by SWIG:
</p>

<div class="code"><pre>
public class Test {
  private transient long swigCPtr;
  protected transient boolean swigCMemOwn;

  protected Test(long cPtr, boolean cMemoryOwn) {
    swigCMemOwn = cMemoryOwn;
    swigCPtr = cPtr;
  }

  protected static long getCPtr(Test obj) {
    return (obj == null) ? 0 : obj.swigCPtr;
  }

  protected void finalize() {
    delete();
  }

  // Call C++ destructor
  public synchronized void delete() {
    if(swigCPtr != 0 &amp;&amp; swigCMemOwn) {
      swigCMemOwn = false;
      exampleJNI.delete_Test(swigCPtr);
    }
    swigCPtr = 0;
  }

  // Call C++ constructor
  public Test() {
    this(exampleJNI.new_Test(), true);
  }

}
</pre></div>


<p>
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. 
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. 
This is because when an object is marked for garbage collection, any objects with finalizers are added to a finalization queue 
and the objects in the finalization queue have their <tt>finalize()</tt> methods run in a separate finalization thread. 
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. 
It is thus essential, even in single threaded usage, to link to the C multi-thread runtime libraries,
for example, use the /MD option for Visual C++ on Windows.
Alternatively, lock all access to C++ functions that have heap allocation/deallocation. 
</p>

<p>
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.
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.
</p>

<p>
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.
</p>
 
<div class="code"><pre>
for (int i=0; i&lt;100000; i++) {
  System.out.println("Iteration " + i);
  for (int k=0; k&lt;10; k++) {
    Test test = new Test();
  }
  System.gc();
}
</pre></div>
 

<H3><a name="Java_type_wrapper_classes">25.4.4 Type wrapper classes</a></H3>


<p>
The generated type wrapper class, for say an <tt>int *</tt>, looks like this:
</p>

<div class="code"><pre>
public class SWIGTYPE_p_int {
  private transient long swigCPtr;

  protected SWIGTYPE_p_int(long cPtr, boolean bFutureUse) {
    swigCPtr = cPtr;
  }

  protected SWIGTYPE_p_int() {
    swigCPtr = 0;
  }

  protected static long getCPtr(SWIGTYPE_p_int obj) {
    return obj.swigCPtr;
  }
}
</pre></div>

<p>
The methods do not have public access, so by default it is impossible to do anything with objects of this class other than 
pass them around. The methods in the class are part of the inner workings of SWIG. 
If you need to mess around with pointers you will have to use some typemaps specific to the Java module to achieve this.
The section on <a href="#Java_typemaps">Java typemaps</a> details how to modify the generated code.
</p>

<p>
Note that if you use a pointer or reference to a proxy class in a function then no type wrapper class is generated because the proxy class can be used
as the function parameter. If however,  you need anything more complicated like a pointer to a pointer to a proxy class then a typewrapper class
is generated for your use. 
</p>

<p>
Note that SWIG generates a type wrapper class and not a proxy class when it has not parsed the definition of a type that gets used. 
For example, say SWIG has not parsed the definition of <tt>class Snazzy</tt> because it is in a header file that you may have forgotten to use the <tt>%include</tt> directive on.
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.
Also recall from earlier that SWIG will use a pointer when a class is passed by value or by reference:
</p>

<div class="code">
<pre>
void spam(Snazzy *x, Snazzy &amp;y, Snazzy z);
</pre>
</div>

<p>
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.
The Java function generated is:
</p>

<div class="code">
<pre>
public static void spam(SWIGTYPE_p_Snazzy x, SWIGTYPE_p_Snazzy y, SWIGTYPE_p_Snazzy z) {
 ...
}
</pre>
</div>

<p>
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:
</p>


<div class="code">
<pre>
typedef int Snazzy;
void spam(Snazzy *x, Snazzy &amp;y, Snazzy z);
</pre>
</div>

<p>
Because the typedefs have been tracked the Java function generated is:
</p>

<div class="code">
<pre>
public static void spam(SWIGTYPE_p_int x, SWIGTYPE_p_int y, int z) { ... }
</pre>
</div>


<H3><a name="Java_enum_classes">25.4.5 Enum classes</a></H3>


<p>
SWIG can generate three types of enum classes.
The <a href="#Java_enumerations">Enumerations</a> section discussed these but omitted all the details.
The following sub-sections detail the various types of enum classes that can be generated.
</p>

<H4><a name="Java_typesafe_enums_classes">25.4.5.1 Typesafe enum classes</a></H4>


<p>
The following example demonstrates the typesafe enum classes which SWIG generates:
</p>

<div class="code">
<pre>
%include "enumtypesafe.swg"
%javaconst(1);
enum Beverage { ALE, LAGER=10, STOUT, PILSNER, PILZ=PILSNER };
</pre>
</div>

<p>
The following is the code that SWIG generates:
</p>

<div class="code">
<pre>
public final class Beverage {
  public final static Beverage ALE = new Beverage("ALE");
  public final static Beverage LAGER = new Beverage("LAGER", 10);
  public final static Beverage STOUT = new Beverage("STOUT");
  public final static Beverage PILSNER = new Beverage("PILSNER");
  public final static Beverage PILZ = new Beverage("PILZ", PILSNER);

  public final int swigValue() {
    return swigValue;
  }

  public String toString() {
    return swigName;
  }

  public static Beverage swigToEnum(int swigValue) {
    if (swigValue &lt; swigValues.length &amp;&amp; swigValue &gt;= 0 &amp;&amp;
        swigValues[swigValue].swigValue == swigValue)
      return swigValues[swigValue];
    for (int i = 0; i &lt; swigValues.length; i++)
      if (swigValues[i].swigValue == swigValue)
        return swigValues[i];
    throw new IllegalArgumentException("No enum " + Beverage.class + " with value " +
                                                                         swigValue);
  }

  private Beverage(String swigName) {
    this.swigName = swigName;
    this.swigValue = swigNext++;
  }

  private Beverage(String swigName, int swigValue) {
    this.swigName = swigName;
    this.swigValue = swigValue;
    swigNext = swigValue+1;
  }

  private Beverage(String swigName, Beverage swigEnum) {
    this.swigName = swigName;
    this.swigValue = swigEnum.swigValue;
    swigNext = this.swigValue+1;
  }

  private static Beverage[] swigValues = { ALE, LAGER, STOUT, PILSNER, PILZ };
  private static int swigNext = 0;
  private final int swigValue;
  private final String swigName;
}
</pre>
</div>

<p>
As can be seen, there are a fair number of support methods for the typesafe enum pattern.
The typesafe enum pattern involves creating a fixed number of static instances of the enum class.
The constructors are private to enforce this.
Three constructors are available - two for C/C++ enums with an initializer and one for those without an initializer.
Note that the two enums with initializers, <tt>LAGER</tt> and <tt>PILZ</tt>, each call one the two different initializer constructors.
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.
The JNI layer returns the enum value from the C/C++ world as an integer and this method is used to find the appropriate Java enum static instance.
The <tt>swigValue</tt> method is used for marshalling in the other direction.
The <tt>toString</tt> method is overridden so that the enum name is available.
</p>

<H4><a name="Java_proper_enums_classes">25.4.5.2 Proper Java enum classes</a></H4>


<p>
The following example demonstrates the Java enums approach:
</p>

<div class="code">
<pre>
%include "enums.swg"
%javaconst(1);
enum Beverage { ALE, LAGER=10, STOUT, PILSNER, PILZ=PILSNER };
</pre>
</div>

<p>
SWIG will generate the following Java enum:
</p>

<div class="code">
<pre>
public enum Beverage {
  ALE,
  LAGER(10),
  STOUT,
  PILSNER,
  PILZ(PILSNER);

  public final int swigValue() {
    return swigValue;
  }

  public static Beverage swigToEnum(int swigValue) {
    Beverage[] swigValues = Beverage.class.getEnumConstants();
    if (swigValue &lt; swigValues.length &amp;&amp; swigValue &gt;= 0 &amp;&amp;
        swigValues[swigValue].swigValue == swigValue)
      return swigValues[swigValue];
    for (Beverage swigEnum : swigValues)
      if (swigEnum.swigValue == swigValue)
        return swigEnum;
    throw new IllegalArgumentException("No enum " + Beverage.class +
                                       " with value " + swigValue);
  }

  private Beverage() {
    this.swigValue = SwigNext.next++;
  }

  private Beverage(int swigValue) {
    this.swigValue = swigValue;
    SwigNext.next = swigValue+1;
  }

  private Beverage(Beverage swigEnum) {
    this.swigValue = swigEnum.swigValue;
    SwigNext.next = this.swigValue+1;
  }

  private final int swigValue;

  private static class SwigNext {
    private static int next = 0;
  }
}
</pre>
</div>

<p>
The enum items appear first.
Like the typesafe enum pattern, the constructors are private.
The constructors are required to handle C/C++ enums with initializers.
The <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.
Marshalling between Java enums and the C/C++ enum integer value is handled via the <tt>swigToEnum</tt> and <tt>swigValue</tt> methods.
All the constructors and methods in the Java enum are required just to handle C/C++ enums with initializers.
These needn't be generated if the enum being wrapped does not have any initializers and the 
<a href="#Java_simpler_enum_classes">Simpler Java enums for enums without initializers</a> section describes how typemaps can be used to achieve this.
</p>

<H4><a name="Java_typeunsafe_enums_classes">25.4.5.3 Type unsafe enum classes</a></H4>


<p>
The following example demonstrates type unsafe enums:
</p>

<div class="code">
<pre>
%include "enumtypeunsafe.swg"
%javaconst(1);
enum Beverage { ALE, LAGER=10, STOUT, PILSNER, PILZ=PILSNER };
</pre>
</div>

<p>
SWIG will generate the following simple class:
</p>

<div class="code">
<pre>
public final class Beverage {
  public final static int ALE = 0;
  public final static int LAGER = 10;
  public final static int STOUT = LAGER + 1;
  public final static int PILSNER = STOUT + 1;
  public final static int PILZ = PILSNER;
}
</pre>
</div>

<H2><a name="Java_directors">25.5 Cross language polymorphism using directors</a></H2>


<p>
Proxy classes provide a natural, object-oriented way to wrap C++ classes.
as described earlier, each proxy instance has an associated C++ instance, and method calls from Java to the proxy are passed to the C++ instance transparently via C wrapper functions.
</p>

<p>
This arrangement is asymmetric in the sense that no corresponding mechanism exists to pass method calls down the inheritance chain from C++ to Java. 
In particular, if a C++ class has been extended in Java (by deriving from the proxy class), these classes will not be visible from C++ code. 
Virtual method calls from C++ are thus not able to access the lowest implementation in the inheritance chain.
</p>

<p>
SWIG can address this problem and make the relationship between C++ classes and proxy classes more symmetric. 
To achieve this goal, new classes called directors are introduced at the bottom of the C++ inheritance chain. 
The job of the directors is to route method calls correctly, either to C++ implementations higher in the inheritance chain or to Java implementations lower in the inheritance chain. 
The upshot is that C++ classes can be extended in Java and from C++ these extensions look exactly like native C++ classes. 
Neither C++ code nor Java code needs to know where a particular method is implemented: the combination of proxy classes, director classes, and C wrapper functions transparently takes care of all the cross-language method routing.
</p>

<H3><a name="Java_enabling_directors">25.5.1 Enabling directors</a></H3>


<p>
The director feature is disabled by default.
To use directors you must make two changes to the interface file.
First, add the "directors" option to the %module directive, like this:
</p>

<div class="code">
<pre>
%module(directors="1") modulename
</pre>
</div>

<p>
Without this option no director code will be generated.
Second, you must use the %feature("director") directive to tell SWIG which classes and methods should get directors.
The %feature directive can be applied globally, to specific classes, and to specific methods, like this:
</p>

<div class="code">
<pre>
// generate directors for all classes that have virtual methods
%feature("director");         

// generate directors for all virtual methods in class Foo
%feature("director") Foo;      
</pre>
</div>

<p>
You can use the %feature("nodirector") directive to turn off directors for specific classes or methods.
So for example,
</p>

<div class="code">
<pre>
%feature("director") Foo;
%feature("nodirector") Foo::bar;
</pre>
</div>

<p>
will generate directors for all virtual methods of class Foo except bar().  
</p>

<p>
Directors can also be generated implicitly through inheritance. 
In the following, class Bar will get a director class that handles the methods one() and two() (but not three()):
</p>

<div class="code">
<pre>
%feature("director") Foo;
class Foo {
public:
    virtual void one();
    virtual void two();
};

class Bar: public Foo {
public:
    virtual void three();
};
</pre>
</div>

<H3><a name="Java_directors_classes">25.5.2 Director classes</a></H3>


<p>
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. 
These new classes, referred to as director classes, can be loosely thought of as the C++ equivalent of the Java proxy classes.
The director classes store a pointer to their underlying Java proxy classes.
</p>

<p>
For simplicity let's ignore the <tt>Swig::Director</tt> class and refer to the original C++ class as the director's base class.
By default, a director class extends all virtual methods in the inheritance chain of its base class (see the preceding section for how to modify this behavior).
Thus all virtual method calls, whether they originate in C++ or in Java via proxy classes, eventually end up in at the implementation in the director class.
The job of the director methods is to route these method calls to the appropriate place in the inheritance chain.
By "appropriate place" we mean the method that would have been called if the C++ base class and its Java derived classes were seamlessly integrated.
That seamless integration is exactly what the director classes provide, transparently skipping over all the messy JNI glue code that binds the two languages together.
</p>

<p>
In reality, the "appropriate place" is one of only two possibilities: C++ or Java.
Once this decision is made, the rest is fairly easy.
If the correct implementation is in C++, then the lowest implementation of the method in the C++ inheritance chain is called explicitly.
If the correct implementation is in Java, the Java API is used to call the method of the underlying Java object 
(after which the usual virtual method resolution in Java automatically finds the right implementation).
</p>


<H3><a name="Java_directors_overhead">25.5.3 Overhead and code bloat</a></H3>


<p>
Enabling directors for a class will generate a new director method for every virtual method in the class' inheritance chain.
This alone can generate a lot of code bloat for large hierarchies.
Method arguments that require complex conversions to and from Java types can result in large director methods.
For this reason it is recommended that directors are selectively enabled only for specific classes that are likely to be extended in Java and used in C++.
</p>

<p>
Although directors make it natural to mix native C++ objects with Java objects (as director objects),
one should be aware of the obvious fact that method calls to Java objects from C++ will be much slower than calls to C++ objects.
Additionally, compared to classes that do not use directors, the call routing in the director methods adds a small overhead.
This situation can be optimized by selectively enabling director methods (using the %feature directive) for only those methods that are likely to be extended in Java.
</p>


<H3><a name="Java_directors_example">25.5.4 Simple directors example</a></H3>


<p>
Consider the following SWIG interface file:
</p>

<div class="code">
<pre>
%module(directors="1") example;

%feature("director") DirectorBase;

class DirectorBase {
public:
  virtual ~DirectorBase() {}
  virtual void upcall_method() {}
};

void callup(DirectorBase *director) {
  director-&gt;upcall_method();
}
</pre>
</div>

<p>
The following <code>DirectorDerived</code> Java class is derived from the Java proxy class <code>DirectorBase</code> and overrides <code>upcall_method()</code>.
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.
Naturally, the SWIG generated C++ code and the generated Java intermediary class marshal and convert arguments between C++ and Java when needed.
</p>

<div class="code">
<pre>
public class DirectorDerived extends DirectorBase {
  public DirectorDerived() {
  }

  public void upcall_method() {
    System.out.println("DirectorDerived::upcall_method() invoked.");
  }
}
</pre>
</div>

<p>
Running the following Java code
</p>

<div class="code">
<pre>
DirectorDerived director = new DirectorDerived();
example.callup(director);
</pre>
</div>

<p>
will result in the following being output:
</p>

<div class="code">
<pre>
DirectorDerived::upcall_method() invoked.
</pre>
</div>

<H3><a name="Java_directors_threading">25.5.5 Director threading issues</a></H3>


<p>
Depending on your operating system and version of Java and how you are using threads, you might find the JVM hangs on exit.
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.
</p>

<p>
Macros can be defined on the commandline when compiling your C++ code, or alternatively added to the C++ wrapper file as shown below:
</p>

<div class="code">
<pre>
%insert("runtime") %{
#define SWIG_JAVA_NO_DETACH_CURRENT_THREAD
%}
</pre>
</div>

<H3><a name="Java_directors_performance">25.5.6 Director performance tuning</a></H3>


<p>
When a new instance of a director (or subclass) is created in Java, the C++ side of the director performs a runtime check per director method to determine if that particular method is overridden in Java or if it should invoke the C++ base implementation directly.  Although this makes initialization slightly more expensive, it is generally a good overall tradeoff.
</p>

<p>
However, if all director methods are expected to usually be overridden by Java subclasses, then initialization can be made faster by avoiding these checks via the <tt>assumeoverride</tt> attribute.  For example:
</p>

<div class="code">
<pre>
%feature("director", assumeoverride=1) Foo;
</pre>
</div>

<p>
The disadvantage is that invocation of director methods from C++ when Java doesn't actually override the method will require an additional call up into Java and back to C++.  As such, this option is only useful when overrides are extremely common and instantiation is frequent enough that its performance is critical.
</p>

<H3><a name="Java_exceptions_from_directors">25.5.7 Java exceptions from directors</a></H3>


<p>
With directors routing method calls to Java, and proxies routing them
to C++, the handling of exceptions is an important concern.
The default behavior from SWIG 3.0
onwards is to convert the thrown Java exception into a SWIG defined
<code>DirectorException</code> C++ exception.
SWIG 2.0 and earlier versions didn't provide any mechanism to handle the Java director method exceptions in C++.
</p>

<p>
Converting Java exceptions into C++ exceptions can be done in two different ways using
the <code>director:except</code> <a href="Customization.html#Customization_features">feature</a>.
In the simplest approach, a code block is attached to each director method to
handle the mapping of Java exceptions into C++ exceptions.
</p>

<div class="code">
<pre>
%feature("director:except") MyClass::method(int x) {
  jthrowable $error = jenv-&gt;ExceptionOccurred();
  if ($error) {
    jenv-&gt;ExceptionClear();
    if (Swig::ExceptionMatches(jenv, $error, "java/lang/IndexOutOfBoundsException"))
      throw std::out_of_range(Swig::JavaExceptionMessage(jenv, $error).message());
    if (Swig::ExceptionMatches(jenv, $error, "$packagepath/MyJavaException"))
      throw MyCppException(Swig::JavaExceptionMessage(jenv, $error).message());
    throw std::runtime_error("Unexpected exception thrown in MyClass::method");
  }
}

class MyClass {
  /** Throws either a std::out_of_range or MyCppException on error */
  void method(int x);
}
</pre>
</div>

<p>
This approach allows a flexible mapping of Java exceptions thrown by director methods into
C++ exceptions expected by a C++ caller.  There
need not be any C++ <em>exception specifications</em> on the C++ method. The
utility function <code>Swig::ExceptionMatches</code>
and class <code>Swig::JavaExceptionMessage</code> are provided to simplify
writing code for wrappers that use the <code>director:except</code> feature. The
function <code>Swig::ExceptionMatches</code> matches the type of the
<code>jthrowable</code> thrown against a <b>fully qualified</b> JNI style class
name, such as <code>"java/lang/IOError"</code>.  If the throwable class is the same
type, or derives from the given type, <code>Swig::ExceptionMatches</code> will return true.  Care must be taken to
provide the correct fully qualified name, since for wrapped exceptions the
generated proxy class will have additional package qualification, depending on
the '-package' argument and use of the <a href="#Java_namespaces">nspace
  feature</a>.  The special variable <code>$error</code> is expanded by SWIG into a unique variable name and
should be used for the 
assignment of the exception that occurred.  The special variable <code>$packagepath</code> is
replaced by the outer package provided for SWIG generation by the -package
option.  The utility class <code>Swig::JavaExceptionMessage</code> is a holder
providing access to the message from the thrown Java exception.
The <code>message()</code> method returns the exception message as a <code>const char *</code>,
which is only valid during the lifetime of the holder.  Any code using this message
needs to copy it, for example into a std::string or a newly constructed C++ exception.
</p>

<p>
Using the above approach to
write handlers for a large number of methods will require 
repetitive duplication of the <code>director:except</code> feature code.
To mitigate this, an alternative approach is provided via typemaps in a
fashion analagous to
the <a href="Typemaps.html#throws_typemap">"throws" typemap.</a>  The
"throws" typemap provides an approach to automatically map all the C++
exceptions listed in a method's defined exceptions (either from
a C++ <em>exception specification</em> or a <code>%catches</code>
feature) into Java exceptions.
The "directorthrows" typemap provides the inverse mapping and should contain
code to convert a suitably matching Java exception into a C++ exception.
The example below converts a Java <code>java.lang.IndexOutOfBoundsException</code> exception
to the typemap's type, that is <code>std::out_of_range</code>:

<div class="code">
<pre>
%typemap(directorthrows) std::out_of_range %{
  if (Swig::ExceptionMatches(jenv, $error, "java/lang/IndexOutOfBoundsException")) {
    throw std::out_of_range(Swig::JavaExceptionMessage(jenv, $error).message());
  }
%}
</pre>
</div>

<p>
The "directorthrows" typemap is then used in conjunction with the
<code>director:except</code> feature if the <code>$directorthrowshandlers</code> special variable
is used in the feature code. Consider the following, which also happens to be the default:
</p>

<div class="code">
<pre>
%feature("director:except") %{
   jthrowable $error = jenv-&gt;ExceptionOccurred();
   if ($error) {
     jenv-&gt;ExceptionClear();
     $directorthrowshandlers
     throw Swig::DirectorException(jenv, $error);
   }
%}
</pre>
</div>

<p>The code generated using the <code>director:except</code> feature
replaces the <code>$directorthrowshandlers</code> special variable with the code in
the "directorthrows" typemaps, for each and every exception defined for the method. 
The possible exceptions can be defined either with a C++ exception
specification or <code>%catches</code> as described for the
<a href="Typemaps.html#throws_typemap">"throws" typemap</a>.
</p>

<p>
Consider the following director method:
</p>

<div class="code">
<pre>
  ...
  virtual void doSomething(int index) throw (std::out_of_range);
  ...
</pre>
</div>

<p>
When combined with the default <code>director:except</code> feature and the "directorthrows" typemap above,
the resulting code generated in the director method after calling up to Java will be:
</p>

<div class="code">
<pre>
jthrowable swigerror = jenv-&gt;ExceptionOccurred();
if (swigerror) {
  jenv-&gt;ExceptionClear();
  if (Swig::ExceptionMatches(jenv, swigerror, "java/lang/IndexOutOfBoundsException")) {
    throw std::out_of_range(Swig::JavaExceptionMessage(jenv, swigerror).message());
  }
  
  throw Swig::DirectorException(jenv, swigerror);
}
</pre>
</div>

<p><em>
Note: Beware of using exception specifications as the SWIG director methods
will be generated with the same exception specifications and if the
director method throws an exception that is not specified it is likely
to terminate your program. See the C++ standard for more details.
Using the %catches feature instead to define the handled exceptions does not suffer
this potential fate.
</em></p>

<p>Because the default code generation maps any unhandled Java exceptions to
<code>Swig::DirectorException</code>, any director methods that have exception
specifications may cause program termination.  To simply ignore
unexpected exceptions, the default handling can be changed with:
</p>

<div class="code">
<pre>
%feature("director:except") %{
   jthrowable $error = jenv-&gt;ExceptionOccurred();
   if ($error) {
     jenv-&gt;ExceptionClear();
     $directorthrowshandlers
     return $null; // exception is ignored
   }
%}
</pre>
</div>

<p>Alternatively an exception compatible with the existing director
method exception specifications can be thrown. Assuming that all
methods allow std::runtime_error to be thrown,
the <code>return&nbsp;$null;</code> could be changed to:
</p>

<div class="code">
<pre>
   throw std::runtime_error(Swig::JavaExceptionMessage(jenv, $error).message());
</pre>
</div>

<p>In more complex situations, a separate <code>director:except</code> feature
may need to be attached to specific methods.
</p>

<p>Below is a complete example demonstrating the use
of the "directorthrows" typemaps.  In this example, a
generic "directorthrows" typemap is appropriate for all three exceptions - all
take single string constructors.  If the exceptions had different constructors,
it would be necessary to have separate typemaps for each exception type.


<!-- All the DEFINE_ and DECLARE_EXCEPTIONS CAN BE OMITTED to make
  this more succinct.  They are included to make this a complete
  example interface that could be generated and built.  -->
<div class="code">
<pre>
%module(directors="1") example

%{
  #include &lt;string&gt;
  #include &lt;stdexcept&gt;
%}

// Define exceptions in header section using std::runtime_error
%define DEFINE_EXCEPTION(NAME)
%{
  namespace MyNS {
    struct NAME : public std::runtime_error { NAME(const std::string &amp;what) : runtime_error(what) {} };
  }
%}
%enddef

// Expose C++ exceptions as Java Exceptions by changing the Java base class and providing a getMessage()
%define DECLARE_EXCEPTION(NAME)
%typemap(javabase) MyNS::NAME "java.lang.Exception";
%rename(getMessage) MyNS::NAME::what;
namespace MyNS {
  struct NAME {
    NAME(const std::string&amp; what);
    const char * what();
  };
}
%enddef

DEFINE_EXCEPTION(ExceptionA)
DEFINE_EXCEPTION(ExceptionB)
DEFINE_EXCEPTION(Unexpected)

// Mark three methods to map director thrown exceptions.
%feature("director:except") MyClass::meth1(int);
%feature("director:except") MyClass::meth2;
%feature("director:except") meth3;

%typemap(directorthrows) MyNS::ExceptionA, MyNS::ExceptionB, MyNS::Unexpected %{
  if (Swig::ExceptionMatches(jenv, $error, "$packagepath/$javaclassname"))
    throw $1_type(Swig::JavaExceptionMessage(jenv, $error).message());
%}

DECLARE_EXCEPTION(ExceptionA)
DECLARE_EXCEPTION(ExceptionB)
DECLARE_EXCEPTION(Unexpected)

%catches(MyNS::ExceptionA, MyNS::ExceptionB, MyNS::Unexpected) MyClass::meth2();

%inline {
  class MyClass {
  public:
    virtual void meth1(int x) throw(MyNS::ExceptionA, MyNS::ExceptionB) = 0;
    virtual void meth2() = 0;   /* throws MyNS::ExceptionA, MyNS::ExceptionB, MyNS::Unexpected */
    virtual void meth3(float x) throw(MyNS::Unexpected) = 0;
    virtual ~MyClass() {}
  };
}
</pre>
</div>

<p>
In this case the three different "directorthrows" typemaps will be used
to generate the three different exception handlers for
<code>meth1</code>, <code>meth2</code> and <code>meth3</code>.  The generated
handlers will have "if" blocks for each exception type specified, in
the exception specification or <code>%catches</code> feature. 
</p>

<p>Note that the "directorthrows" typemaps are important
only if it is important for the the exceptions passed through the C++
layer to be mapped to distinct C++ exceptions.  If director methods
are being called by C++ code that is itself wrapped in a
SWIG generated Java wrapper and access is always through this wrapper,
the default <code>Swig::DirectorException</code> class provides enough information
to reconstruct the original exception.  In this case removing the
<code>$directorthrowshandlers</code> special variable from the
default <code>director:except</code> feature and simply always
throwing a <code>Swig::DirectorException</code> will achieve the desired result.
Along with this a generic exception feature is added to convert any
caught <code>Swig::DirectorException</code>s back into the underlying
Java exceptions via the <code>Swig::DirectorException::raiseJavaException</code> method,
as demonstrated with <code>%javaexception</code> below:
</p>

<div class="code">
<pre>
%javaexception("Exception") MyClass::myMethod %{
  try {
    $action
  } catch (Swig::DirectorException &amp;e) {
    // raise/throw the Java exception that originally caused the DirectorException
    e.raiseJavaException(jenv);
    return $null;
  }
%}
</pre>
</div>

<p>
See the <a href="#Java_exception_handling">Exception handling with %exception and %javaexception</a>
section for more on converting C++ exceptions to Java exceptions.
</p>

<H2><a name="Java_allprotected">25.6 Accessing protected members</a></H2>


<p>
When using directors, the protected virtual methods are also wrapped. 
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.
</p>

<p>
Members which are protected and non-virtual can also be accessed when using the 'allprotected' mode.
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:
</p>

<div class="code">
<pre>
%module(directors="1", allprotected="1") modulename
</pre>
</div>

<p>
Protected member variables and methods (both static and non-static) will then be wrapped with protected access in the Java proxy class.
</p>

<p>
<b>Note:</b> Neither the directors option nor the allprotected mode support types defined with protected scope.
This includes any enums or typedefs declared in the protected section of the C++ class.
</p>

<p>
The following simple example is a class with numerous protected members, including the constructor and destructor:
</p>

<div class="code">
<pre>
%module(directors="1", allprotected="1") example

%feature("director") ProtectedBase;

// Ignore use of unsupported types (those defined in the protected section)
%ignore ProtectedBase::typedefs;

%inline %{

class ProtectedBase {
protected:
  ProtectedBase() {}
  virtual ~ProtectedBase() {}
  virtual void virtualMethod() const {}
  void nonStaticMethod(double d) const {}
  static void staticMethod(int i) {}
  int instanceMemberVariable;
  static int staticMemberVariable;

  // unsupported: types defined with protected access and the methods/variables which use them
  typedef int IntegerType;
  IntegerType typedefs(IntegerType it) { return it; }
};
int ProtectedBase::staticMemberVariable = 10;

%}

</pre>
</div>

<p>
Note that the <tt>IntegerType</tt> has protected scope and the members which use this type must be ignored as they cannot be wrapped.
</p>

<p>
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:
</p>

<div class="code">
<pre>
class MyProtectedBase extends ProtectedBase
{
  public MyProtectedBase() {
  }

  public void accessProtected() {
    virtualMethod();
    nonStaticMethod(1.2);
    staticMethod(99);

    setInstanceMemberVariable(5);
    int i = getInstanceMemberVariable();

    setStaticMemberVariable(10);
    i = getStaticMemberVariable();
  }
}
</pre>
</div>



<H2><a name="Java_common_customization">25.7 Common customization features</a></H2>


<p>
An earlier section presented the absolute basics of C/C++ wrapping. If you do nothing
but feed SWIG a header file, you will get an interface that mimics the behavior
described.  However, sometimes this isn't enough to produce a nice module.  Certain
types of functionality might be missing or the interface to certain functions might
be awkward.  This section describes some common SWIG features that are used
to improve the interface to existing C/C++ code.
</p>

<H3><a name="Java_helper_functions">25.7.1 C/C++ helper functions</a></H3>


<p>
Sometimes when you create a module, it is missing certain bits of functionality. For
example, if you had a function like this
</p>

<div class="code">
<pre>
typedef struct Image {...};
void set_transform(Image *im, double m[4][4]);
</pre>
</div>

<p>
it would be accessible from Java, but there may be no easy way to call it.
The problem here is that a type wrapper class is generated for the two dimensional array parameter so
there is no easy way to construct and manipulate a suitable
<tt>double [4][4]</tt> value.   To fix this, you can write some extra C helper
functions.  Just use the <tt>%inline</tt> directive. For example:
</p>

<div class="code">
<pre>
%inline %{
/* Note: double[4][4] is equivalent to a pointer to an array double (*)[4] */
double (*new_mat44())[4] {
   return (double (*)[4]) malloc(16*sizeof(double));
}
void free_mat44(double (*x)[4]) {
   free(x);
}
void mat44_set(double x[4][4], int i, int j, double v) {
   x[i][j] = v;
}
double mat44_get(double x[4][4], int i, int j) {
   return x[i][j];
}
%}
</pre>
</div>

<p>
From Java, you could then write code like this:
</p>

<div class="code">
<pre>
Image im = new Image();
SWIGTYPE_p_a_4__double a = example.new_mat44();
example.mat44_set(a,0,0,1.0);
example.mat44_set(a,1,1,1.0);
example.mat44_set(a,2,2,1.0);
...
example.set_transform(im,a);
example.free_mat44(a);
</pre>
</div>

<p>
Admittedly, this is not the most elegant looking approach.  However, it works and it wasn't too
hard to implement.  It is possible to improve on this using Java code, typemaps, and other
customization features as covered in later sections, but sometimes helper functions are a quick and easy solution to difficult cases.  
</p>

<H3><a name="Java_class_extension">25.7.2 Class extension with %extend</a></H3>


<p>
One of the more interesting features of SWIG is that it can extend
structures and classes with new methods or constructors.
Here is a simple example:
</p>

<div class="code">
<pre>
%module example
%{
#include "someheader.h"
%}

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

%extend Vector {
   char *toString() {
       static char tmp[1024];
       sprintf(tmp,"Vector(%g,%g,%g)", $self-&gt;x,$self-&gt;y,$self-&gt;z);
       return tmp;
   }
   Vector(double x, double y, double z) {
       Vector *v = (Vector *) malloc(sizeof(Vector));
       v-&gt;x = x;
       v-&gt;y = y;
       v-&gt;z = z;
       return v;
   }
};
</pre>
</div>

<p>
Now, in Java
</p>

<div class="code">
<pre>
Vector v = new Vector(2,3,4);
System.out.println(v);
</pre>
</div>

<p>
will display
</p>

<div class="code">
<pre>
Vector(2,3,4)
</pre>
</div>

<p>
<tt>%extend</tt> works with both C and C++ code.  It does not modify the underlying object
in any way---the extensions only show up in the Java interface.
</p>

<H3><a name="Java_exception_handling">25.7.3 Exception handling with %exception and %javaexception</a></H3>


<p>
If a C or C++ function throws an error, you may want to convert that error into a Java
exception. To do this, you can use the <tt>%exception</tt> directive.  The <tt>%exception</tt> directive
simply lets you rewrite part of the generated wrapper code to include an error check.
It is detailed in full in the <a href="Customization.html#Customization_exception">Exception handling with %exception</a> section.
</p>

<p>
In C, a function often indicates an error by returning a status code (a negative number
or a NULL pointer perhaps).  Here is a simple example of how you might handle that:
</p>

<div class="code">
<pre>
%exception malloc {
  $action
  if (!result) {
    jclass clazz = (*jenv)-&gt;FindClass(jenv, "java/lang/OutOfMemoryError");
    (*jenv)-&gt;ThrowNew(jenv, clazz, "Not enough memory");
    return $null;
  }
}
void *malloc(size_t nbytes);
</pre>
</div>

<p>
In Java,
</p>

<div class="code">
<pre>
SWIGTYPE_p_void a = example.malloc(2000000000);
</pre>
</div>

<p>
will produce a familiar looking Java exception:
</p>

<div class="code">
<pre>
Exception in thread "main" java.lang.OutOfMemoryError: Not enough memory
        at exampleJNI.malloc(Native Method)
        at example.malloc(example.java:16)
        at runme.main(runme.java:112)
</pre>
</div>

<p>
If a library provides some kind of general error handling framework, you can also use
that.  For example:
</p>

<div class="code">
<pre>
%exception malloc {
  $action
  if (err_occurred()) {
    jclass clazz = (*jenv)-&gt;FindClass(jenv, "java/lang/OutOfMemoryError");
    (*jenv)-&gt;ThrowNew(jenv, clazz, "Not enough memory");
    return $null;
  }
}
void *malloc(size_t nbytes);
</pre>
</div>

<p>
If no declaration name is given to <tt>%exception</tt>, it is applied to all wrapper functions.
The <tt>$action</tt> is a SWIG special variable and is replaced by the C/C++ function call being wrapped.
The <tt>return $null;</tt> handles all native method return types, namely those that have a void return and those that do not.
This is useful for typemaps that will be used in native method returning all return types. 
See the section on
<a href="#Java_special_variables">Java special variables</a> for further explanation.
</p>

<p>
C++ exceptions are also easy to handle.  
We can catch the C++ exception and rethrow it as a Java exception like this:</p>

<div class="code">
<pre>
%exception getitem {
  try {
     $action
  } catch (std::out_of_range &amp;e) {
    jclass clazz = jenv-&gt;FindClass("java/lang/Exception");
    jenv-&gt;ThrowNew(clazz, "Range error");
    return $null;
   }
}

class FooClass {
public:
     FooClass *getitem(int index);      // Might throw std::out_of_range exception
     ...
};
</pre>
</div>

<p>
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>.
Classes can be specified for adding to the throws clause using <tt>%javaexception(classes)</tt> instead of <tt>%exception</tt>,
where <tt>classes</tt> is a string containing one or more comma separated Java classes.
The <tt>%clearjavaexception</tt> feature is the equivalent to <tt>%clearexception</tt> and clears previously declared exception handlers. 
The <tt>%nojavaexception</tt> feature is the equivalent to <tt>%noexception</tt> and disables the exception handler.
See <a href="Customization.html#Customization_clearing_features">Clearing features</a> for the difference on disabling and clearing features.
</p>

<div class="code">
<pre>
%javaexception("java.lang.Exception") getitem {
  try {
     $action
  } catch (std::out_of_range &amp;e) {
    jclass clazz = jenv-&gt;FindClass("java/lang/Exception");
    jenv-&gt;ThrowNew(clazz, "Range error");
    return $null;
   }
}

class FooClass {
public:
     FooClass *getitem(int index);      // Might throw std::out_of_range exception
     ...
};
</pre>
</div>

<p>
The generated proxy method now generates a throws clause containing <tt>java.lang.Exception</tt>:
</p>

<div class="code">
<pre>
public class FooClass {
  ...
  public FooClass getitem(int index) throws java.lang.Exception { ... }
  ...
}
</pre>
</div>


<p>
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.
It is however possible to write JNI calls which will compile under both C and C++ and is covered in the <a href="#Java_typemaps_for_c_and_cpp">Typemaps for both C and C++ compilation</a> section. 
</p>

<p>
The language-independent <tt>exception.i</tt> library file can also be used
to raise exceptions.  See the <a href="Library.html#Library">SWIG Library</a> chapter.
The typemap example <a href="#Java_exception_typemap">Handling C++ exception specifications as Java exceptions</a> provides further exception handling capabilities.
</p>

<H3><a name="Java_method_access">25.7.4 Method access with %javamethodmodifiers</a></H3>


<p>
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:
</p>

<div class="code">
<pre>
%javamethodmodifiers protect_me() "protected";
void protect_me();
</pre>
</div>

<p>
Will produce the method in the module class with protected access.
</p>

<div class="code">
<pre>
protected static void protect_me() {
  exampleJNI.protect_me();
}
</pre>
</div>

<H2><a name="Java_tips_techniques">25.8 Tips and techniques</a></H2>


<p>
Although SWIG is largely automatic, there are certain types of wrapping problems that
require additional user input.    Examples include dealing with output parameters,
strings and arrays.   This chapter discusses the common techniques for
solving these problems.
</p>

<H3><a name="Java_input_output_parameters">25.8.1 Input and output parameters using primitive pointers and references</a></H3>


<p>
A common problem in some C programs is handling parameters passed as simple pointers or references.  For
example:
</p>

<div class="code">
<pre>
void add(int x, int y, int *result) {
   *result = x + y;
}
</pre>
</div>

<p>
or perhaps
</p>

<div class="code">
<pre>
int sub(int *x, int *y) {
   return *x-*y;
}
</pre>
</div>

<p>
The <tt>typemaps.i</tt> library file will help in these situations.  For example:
</p>

<div class="code">
<pre>
%module example
%include "typemaps.i"

void add(int, int, int *OUTPUT);
int  sub(int *INPUT, int *INPUT);
</pre>
</div>

<p>
In Java, this allows you to pass simple values.  For example:
</p>

<div class="code">
<pre>
int result = example.sub(7,4);
System.out.println("7 - 4 = " + result);
int[] sum = {0};
example.add(3,4,sum);
System.out.println("3 + 4 = " + sum[0]);
</pre>
</div>

<p>
Which will display:
</p>

<div class="code"> <pre>
7 - 4 = 3
3 + 4 = 7
</pre></div>

<p>
Notice how the <tt>INPUT</tt> parameters allow integer values to be passed instead of pointers
and how the <tt>OUTPUT</tt> parameter will return the result in the first element of the integer array.
</p>

<p>
If you don't want to use the names <tt>INPUT</tt> or <tt>OUTPUT</tt>, use the <tt>%apply</tt>
directive.  For example:
</p>

<div class="code">
<pre>
%module example
%include "typemaps.i"

%apply int *OUTPUT { int *result };
%apply int *INPUT  { int *x, int *y};

void add(int x, int y, int *result);
int  sub(int *x, int *y);
</pre>
</div>

<p>
If a function mutates one of its parameters like this,
</p>

<div class="code">
<pre>
void negate(int *x) {
   *x = -(*x);
}
</pre>
</div>

<p>
you can use <tt>INOUT</tt> like this:
</p>

<div class="code">
<pre>
%include "typemaps.i"
...
void negate(int *INOUT);
</pre>
</div>

<p>
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:
</p>

<div class="code">
<pre>
int[] neg = {3};
example.negate(neg);
System.out.println("Negative of 3 = " + neg[0]);
</pre>
</div>

<p>
And no prizes for guessing the output:
</p>

<div class="code"><pre>
Negative of 3 = -3
</pre></div>

<p>
These typemaps can also be applied to C++ references. 
The above examples would work the same if they had been defined using references instead of pointers.
For example, the Java code to use the <tt>negate</tt> function would be the same if it were defined either as it is above: 
</p>

<div class="code">
<pre>
void negate(int *INOUT);
</pre>
</div>

<p>
or using a reference:
</p>

<div class="code">
<pre>
void negate(int &amp;INOUT);
</pre>
</div>

<p>
Note: Since most Java primitive types are immutable and are passed by value, it is not possible to
perform in-place modification of a type passed as a parameter.
</p>

<p>
Be aware that the primary purpose of the <tt>typemaps.i</tt> file is to support primitive datatypes.
Writing a function like this
</p>

<div class="code">
<pre>
void foo(Bar *OUTPUT);
</pre>
</div>

<p>
will not have the intended effect since <tt>typemaps.i</tt> does not define an OUTPUT rule for <tt>Bar</tt>.
</p>

<H3><a name="Java_simple_pointers">25.8.2 Simple pointers</a></H3>


<p>
If you must work with simple pointers such as <tt>int *</tt> or <tt>double *</tt> another approach to using 
<tt>typemaps.i</tt> is to use the <tt>cpointer.i</tt> pointer library file.    For example:
</p>

<div class="code">
<pre>
%module example
%include "cpointer.i"

%inline %{
extern void add(int x, int y, int *result);
%}

%pointer_functions(int, intp);
</pre>
</div>

<p>
The <tt>%pointer_functions(type,name)</tt> macro generates five helper functions that can be used to create,
destroy, copy, assign, and dereference a pointer.  In this case, the functions are as follows:
</p>

<div class="code">
<pre>
int  *new_intp();
int  *copy_intp(int *x);
void  delete_intp(int *x);
void  intp_assign(int *x, int value);
int   intp_value(int *x);
</pre>
</div>

<p>
In Java, you would use the functions like this:
</p>

<div class="code">
<pre>
SWIGTYPE_p_int intPtr = example.new_intp();
example.add(3,4,intPtr);
int result = example.intp_value(intPtr);
System.out.println("3 + 4 = " + result);
</pre>
</div>

<p>
If you replace <tt>%pointer_functions(int,intp)</tt> by <tt>%pointer_class(int,intp)</tt>, the interface is more class-like.
</p>

<div class="code">
<pre>
intp intPtr = new intp();
example.add(3,4,intPtr.cast());
int result = intPtr.value();
System.out.println("3 + 4 = " + result);
</pre>
</div>

<p>
See the <a href="Library.html#Library">SWIG Library</a> chapter for further details.
</p>

<H3><a name="Java_c_arrays">25.8.3 Wrapping C arrays with Java arrays</a></H3>


<p>
SWIG can wrap arrays in a more natural Java manner than the default by using the <tt>arrays_java.i</tt> library file. 
Let's consider an example:
</p>

<div class="code">
<pre>
%include "arrays_java.i";
int array[4];
void populate(int x[]) {
    int i;
    for (i=0; i&lt;4; i++)
        x[i] = 100 + i;
}
</pre>
</div>

<p>
These one dimensional arrays can then be used as if they were Java arrays:
</p>

<div class="code">
<pre>
int[] array = new int[4];
example.populate(array);

System.out.print("array: ");
for (int i=0; i&lt;array.length; i++)
    System.out.print(array[i] + " ");

example.setArray(array);

int[] global_array = example.getArray();

System.out.print("\nglobal_array: ");
for (int i=0; i&lt;array.length; i++)
    System.out.print(global_array[i] + " ");
</pre>
</div>

<p>
Java arrays are always passed by reference, so any changes a function makes to the array will be seen by the calling function. 
Here is the output after running this code:
</p>

<div class="code">
<pre>
array: 100 101 102 103
global_array: 100 101 102 103
</pre>
</div>

<p>
Note that for assigning array variables the length of the C variable is used, so it is possible to use a Java array that is bigger than the C code will cope with.
Only the number of elements in the C array will be used.
However, if the Java array is not large enough then you are likely to get a segmentation fault or access violation, just like you would in C.
When arrays are used in functions like <tt>populate</tt>, the size of the C array passed to the function is determined by the size of the Java array.
</p>

<p>
Please be aware that the typemaps in this library are not efficient as all the elements are copied from the Java array to a C array whenever the array is passed to and from JNI code.
There is an alternative approach using the SWIG array library and this is covered in the next section.
</p>

<H3><a name="Java_unbounded_c_arrays">25.8.4 Unbounded C Arrays</a></H3>


<p>
Sometimes a C function expects an array to be passed as a pointer.  For example,
</p>

<div class="code">
<pre>
int sumitems(int *first, int nitems) {
    int i, sum = 0;
    for (i = 0; i &lt; nitems; i++) {
        sum += first[i];
    }
    return sum;
}
</pre>
</div>

<p>
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:
</p>

<div class="code">
<pre>
%include "arrays_java.i"
%apply int[] {int *};
</pre>
</div>

<p>
The <tt>ANY</tt> size will ensure the typemap is applied to arrays of all sizes.
You could narrow the typemap matching rules by specifying a particular array size.
Now you can use a pure Java array and pass it to the C code:
</p>

<div class="code">
<pre>
int[] array = new int[10000000];          // Array of 10-million integers
for (int i=0; i&lt;array.length; i++) {      // Set some values
  array[i] = i;
}
int sum = example.sumitems(array,10000);
System.out.println("Sum = " + sum);
</pre>
</div>

<p>
and the sum would be displayed:
</p>

<div class="code">
<pre>
Sum = 49995000
</pre>
</div>

<p>
This approach is probably the most natural way to use arrays.
However, it suffers from performance problems when using large arrays as a lot of copying
of the elements occurs in transferring the array from the Java world to the C++ world.
An alternative approach to using Java arrays for C arrays is to use an alternative SWIG library file <tt>carrays.i</tt>.
This approach can be more efficient for large arrays as the array is accessed one element at a time.
For example:
</p>

<div class="code">
<pre>
%include "carrays.i"
%array_functions(int, intArray);
</pre>
</div>

<p>
The <tt>%array_functions(type,name)</tt> macro generates four helper functions that can be used to create and
destroy arrays and operate on elements.  In this case, the functions are as follows:
</p>

<div class="code">
<pre>
int *new_intArray(int nelements);
void delete_intArray(int *x);
int intArray_getitem(int *x, int index);
void intArray_setitem(int *x, int index, int value);
</pre>
</div>

<p>
In Java, you would use the functions like this:
</p>

<div class="code">
<pre>
SWIGTYPE_p_int array = example.new_intArray(10000000);  // Array of 10-million integers
for (int i=0; i&lt;10000; i++) {                           // Set some values
    example.intArray_setitem(array,i,i);
}
int sum = example.sumitems(array,10000);
System.out.println("Sum = " + sum);
</pre>
</div>

<p>
If you replace <tt>%array_functions(int,intp)</tt> by <tt>%array_class(int,intp)</tt>, the interface is more class-like
and a couple more helper functions are available for casting between the array and the type wrapper class.
</p>

<div class="code">
<pre>
%include "carrays.i"
%array_class(int, intArray);
</pre>
</div>

<p>
The <tt>%array_class(type, name)</tt> macro creates wrappers for an unbounded array object that
can be passed around as a simple pointer like <tt>int *</tt> or <tt>double *</tt>.
For instance, you will be able to do this in Java:
</p>

<div class="code">
<pre>
intArray array = new intArray(10000000);  // Array of 10-million integers
for (int i=0; i&lt;10000; i++) {             // Set some values
    array.setitem(i,i);
}
int sum = example.sumitems(array.cast(),10000);
System.out.println("Sum = " + sum);
</pre>
</div>

<p>
The array "object" created by <tt>%array_class()</tt> does not
encapsulate pointers inside a special array object.  In fact, there is
no bounds checking or safety of any kind (just like in C).  Because of
this, the arrays created by this library are extremely low-level
indeed.  You can't iterate over them nor can you even query their
length.  In fact, any valid memory address can be accessed if you want
(negative indices, indices beyond the end of the array, etc.).
Needless to say, this approach is not going to suit all applications.
On the other hand, this low-level approach is extremely efficient and
well suited for applications in which you need to create buffers,
package binary data, etc.
</p>

<H3><a name="Java_binary_char">25.8.5 Binary data vs Strings</a></H3>


<p>
By default SWIG handles <tt>char *</tt> as a string but there is a handy multi-argument typemap available as mentioned in <a href="Library.html#Library_nn10">Passing binary data</a>.
The following simple example demonstrates using a byte array instead of passing the default string type and length to the wrapped function.
</p>


<div class="code">
<pre>
%apply (char *STRING, size_t LENGTH) { (const char data[], size_t len) }
%inline %{
void binaryChar1(const char data[], size_t len) {
  printf("len: %d data: ", len);
  for (size_t i=0; i&lt;len; ++i)
    printf("%x ", data[i]);
  printf("\n");
}
%}
</pre>
</div>

<p>
Calling from Java requires just the byte array to be passed in as the multi-argument typemap being applied reduces the number of arguments in the target language to one, from the original two:
</p>

<div class="code">
<pre>
byte[] data = "hi\0jk".getBytes();
example.binaryChar1(data);     
</pre>
</div>

<p>
resulting in the output
</p>

<div class="code"><pre>
$ java runme
len: 5 data: 68 69 0 6a 6b
</pre></div>


<H3><a name="Java_heap_allocations">25.8.6 Overriding new and delete to allocate from Java heap</a></H3>


<p>
Unlike some languages supported by SWIG, Java has a true garbage collection
subsystem.  Other languages will free SWIG wrapped objects when their reference
count reaches zero.  Java only schedules these objects for finalization, which
may not occur for some time.  Because SWIG objects are allocated on the C
heap, Java users may find the JVM memory use 
quickly exceeds the assigned limits, as memory fills with unfinalized proxy
objects.  Forcing garbage collection is clearly an undesirable solution.
</p>

<p>
An elegant fix for C++ users is to override new and delete using the following
code (here shown included in a SWIG interface file)
</p>

<div class="code">
<pre>
/* File: java_heap.i */
%module test
%{
#include &lt;stdexcept&gt;
#include "jni.h"

/**
 *  A stash area embedded in each allocation to hold java handles
 */
struct Jalloc {
  jbyteArray jba;
  jobject ref;
};

static JavaVM *cached_jvm = 0;

JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *jvm, void *reserved) {
  cached_jvm = jvm;
  return JNI_VERSION_1_2;
}

static JNIEnv * JNU_GetEnv() {
  JNIEnv *env;
  jint rc = cached_jvm-&gt;GetEnv((void **)&amp;env, JNI_VERSION_1_2);
  if (rc == JNI_EDETACHED)
    throw std::runtime_error("current thread not attached");
  if (rc == JNI_EVERSION)
    throw std::runtime_error("jni version not supported");
  return env;
}

void * operator new(size_t t) {
  if (cached_jvm != 0) {
    JNIEnv *env = JNU_GetEnv();
    jbyteArray jba = env-&gt;NewByteArray((int) t + sizeof(Jalloc));
    if (env-&gt;ExceptionOccurred())
      throw bad_alloc();
    void *jbuffer = static_cast&lt;void *&gt;(env-&gt;GetByteArrayElements(jba, 0));
    if (env-&gt;ExceptionOccurred())
      throw bad_alloc();
    Jalloc *pJalloc = static_cast&lt;Jalloc *&gt;(jbuffer);
    pJalloc-&gt;jba = jba;
    /* Assign a global reference so byte array will persist until delete'ed */
    pJalloc-&gt;ref = env-&gt;NewGlobalRef(jba);
    if (env-&gt;ExceptionOccurred())
      throw bad_alloc();
    return static_cast&lt;void *&gt;(static_cast&lt;char *&gt;(jbuffer) + sizeof(Jalloc));
  }
  else { /* JNI_OnLoad not called, use malloc and mark as special */
    Jalloc *pJalloc = static_cast&lt;Jalloc *&gt;(malloc((int) t + sizeof(Jalloc)));
    if (!pJalloc)
      throw bad_alloc();
    pJalloc-&gt;ref = 0;
    return static_cast&lt;void *&gt;(
        static_cast&lt;char *&gt;(static_cast&lt;void *&gt;(pJalloc)) + sizeof(Jalloc));
  }
}

void operator delete(void *v) {
  if (v != 0) {
    void *buffer = static_cast&lt;void *&gt;( static_cast&lt;char *&gt;(v) - sizeof(Jalloc));
    Jalloc *pJalloc = static_cast&lt;Jalloc *&gt;(buffer);
    if (pJalloc-&gt;ref) {
      JNIEnv *env = JNU_GetEnv();
      env-&gt;DeleteGlobalRef(pJalloc-&gt;ref);
      env-&gt;ReleaseByteArrayElements(pJalloc-&gt;jba, static_cast&lt;jbyte *&gt;(buffer), 0);
    }
    else {
      free(buffer);
    }
  }
}
%}
...
</pre>
</div>

<p>
This code caches the Java environment during initialization,
and when new is called, a Java ByteArray is allocated to provide the
SWIG objects with space in the Java heap.  This has the combined
effect of re-asserting the Java virtual machine's limit on memory allocation,
and puts additional pressure on the garbage collection system to run more
frequently.
This code is made slightly more complicated because allowances must be made
if new is called before the JNI_OnLoad is executed.  This can happen during
static class initialization, for example.  
</p>

<p>
Unfortunately, because most Java implementations call malloc and free, this
solution will not work for C wrapped structures.  However, you are free to
make functions that allocate and free memory from the Java heap using this
model and use these functions in place of malloc and free in your own
code.
</p>

<H2><a name="Java_typemaps">25.9 Java typemaps</a></H2>


<p>
This section describes how you can modify SWIG's default wrapping behavior
for various C/C++ datatypes using the <tt>%typemap</tt> directive.   
You are advised to be familiar with the material in the "<a href="Typemaps.html#Typemaps">Typemaps</a>" chapter.
While not absolutely essential knowledge, this section assumes some familiarity with the Java Native Interface (JNI). 
JNI documentation can be consulted either online at <a href="http://java.sun.com">Sun's Java web site</a> or from a good JNI book. 
The following two books are recommended:</p>

<ul>
<li> Title: 'Essential JNI: Java Native Interface.' Author: Rob Gordon. Publisher: Prentice Hall. ISBN: 0-13-679895-0.  </li>
<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>
</ul>

<p>
Before proceeding, it should be stressed that typemaps are not a required 
part of using SWIG---the default wrapping behavior is enough in most cases.
Typemaps are only used if you want to change some aspect of the generated code.

<H3><a name="Java_default_primitive_type_mappings">25.9.1 Default primitive type mappings</a></H3>


<p>
The following table lists the default type mapping from Java to C/C++.</p>

<table BORDER summary="Default primitive type mappings">
<tr>
<td><b>C/C++ type</b></td>
<td><b>Java type</b></td>
<td><b>JNI type</b></td>
</tr>

<tr>
<td>bool<br> const bool &amp; </td>
<td>boolean</td>
<td>jboolean</td>
</tr>

<tr>
<td>char<br>const char &amp;</td>
<td>char</td>
<td>jchar</td>
</tr>

<tr>
<td>signed char<br>const signed char &amp;</td>
<td>byte</td>
<td>jbyte</td>
</tr>

<tr>
<td>unsigned char<br>const unsigned char &amp;</td>
<td>short</td>
<td>jshort</td>
</tr>

<tr>
<td>short<br>const short &amp;</td>
<td>short</td>
<td>jshort</td>
</tr>

<tr>
<td>unsigned short<br> const unsigned short &amp;</td>
<td>int</td>
<td>jint</td>
</tr>

<tr>
<td>int<br> const int &amp;</td>
<td>int</td>
<td>jint</td>
</tr>

<tr>
<td>unsigned int<br> const unsigned int &amp;</td>
<td>long</td>
<td>jlong</td>
</tr>

<tr>
<td>long<br>const long &amp;</td>
<td>int</td>
<td>jint</td>
</tr>

<tr>
<td>unsigned long<br>const unsigned long &amp;</td>
<td>long</td>
<td>jlong</td>
</tr>

<tr>
<td>long long<br> const long long &amp;</td>
<td>long</td>
<td>jlong</td>
</tr>

<tr>
<td>unsigned long long<br>const unsigned long long &amp;</td>
<td>java.math.BigInteger</td>
<td>jobject</td>
</tr>

<tr>
<td>float<br>const float &amp;</td>
<td>float</td>
<td>jfloat</td>
</tr>

<tr>
<td>double<br> const double &amp;</td>
<td>double</td>
<td>jdouble</td>
</tr>

<tr>
<td>char *<br>char []</td>
<td>String</td>
<td>jstring</td>
</tr>

</table>

<p>
Note that SWIG wraps the C <tt>char</tt> type as a character. Pointers and arrays of this type are wrapped as strings. 
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.
Also note that all const references to primitive types are treated as if they are passed by value.
</p>

<p>
Given the following C function:
</p>

<div class="code"> <pre>
void func(unsigned short a, char *b, const long &amp;c, unsigned long long d);
</pre> </div>

<p>
The module class method would be:
</p>

<div class="code"> <pre>
public static void func(int a, String b, int c, java.math.BigInteger d) {...}
</pre> </div>

<p>
The intermediary JNI class would use the same types:
</p>

<div class="code"> <pre>
public final static native void func(int jarg1, String jarg2, int jarg3,
                                     java.math.BigInteger jarg4);
</pre> </div>

<p>
and the JNI function would look like this:
</p>

<div class="code"> <pre>
SWIGEXPORT void JNICALL Java_exampleJNI_func(JNIEnv *jenv, jclass jcls,
                jint jarg1, jstring jarg2, jint jarg3, jobject jarg4) {...}
</pre> </div>

<p>
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. 
There is no perfect mapping between Java and C as Java doesn't support all the unsigned C data types. 
However, the mappings allow the full range of values for each C type from Java. 
</p>


<H3><a name="Java_default_non_primitive_typemaps">25.9.2 Default typemaps for non-primitive types</a></H3>


<p>
The previous section covered the primitive type mappings.
Non-primitive types such as classes and structs are mapped using pointers on the C/C++ side and storing the pointer into a Java <tt>long</tt> variable which is held by
the proxy class or type wrapper class. This applies whether the type is marshalled as a pointer, by reference or by value.
It also applies for any unknown/incomplete types which use type wrapper classes.
</p>

<p>
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>.
The Java type is either the proxy class or type wrapper class.
</p>

<H3><a name="Java_jvm64">25.9.3 Sixty four bit JVMs</a></H3>


<p>
If you are using a 64 bit JVM you may have to override the C long, but probably not C int default mappings. 
Mappings will be system dependent, for example long will need remapping on Unix LP64 systems (long, pointer 64 bits, int 32 bits), but not on 
Microsoft 64 bit Windows which will be using a P64 IL32 (pointer 64 bits and int, long 32 bits) model. 
This may be automated in a future version of SWIG. 
Note that the Java write once run anywhere philosophy holds true for all pure Java code when moving to a 64 bit JVM. 
Unfortunately it won't of course hold true for JNI code.
</p>


<H3><a name="Java_what_is_typemap">25.9.4 What is a typemap?</a></H3>


<p>
A typemap is nothing more than a code generation rule that is attached to 
a specific C datatype.   For example, to convert integers from Java to C,
you might define a typemap like this:
</p>

<div class="code"><pre>
%module example

%typemap(in) int {
  $1 = $input;
  printf("Received an integer : %d\n",  $1);
}
%inline %{
extern int fact(int nonnegative);
%}
</pre></div>

<p>
Typemaps are always associated with some specific aspect of code generation.
In this case, the "in" method refers to the conversion of input arguments
to C/C++.  The datatype <tt>int</tt> is the datatype to which the typemap
will be applied.  The supplied C code is used to convert values.  In this
code a number of special variables prefaced by a <tt>$</tt> are used.  The
<tt>$1</tt> variable is a placeholder for a local variable of type <tt>int</tt>.
The <tt>$input</tt> variable contains the Java data, the JNI <tt>jint</tt> in this case.
</p>

<p>
When this example is compiled into a Java module, it can be used as follows:
</p>

<div class="code"><pre>
System.out.println(example.fact(6));
</pre></div>

<p>
and the output will be:
</p>

<div class="code"><pre>
Received an integer : 6
720
</pre></div>

<p>
In this example, the typemap is applied to all occurrences of the <tt>int</tt> datatype.
You can refine this by supplying an optional parameter name.  For example:
</p>

<div class="code"><pre>
%module example

%typemap(in) int nonnegative {
  $1 = $input;
  printf("Received an integer : %d\n",  $1);
}

%inline %{
extern int fact(int nonnegative);
%}
</pre></div>

<p>
In this case, the typemap code is only attached to arguments that exactly match <tt>int nonnegative</tt>.
</p>

<p>
The application of a typemap to specific datatypes and argument names involves
more than simple text-matching--typemaps are fully integrated into the
SWIG C++ type-system.   When you define a typemap for <tt>int</tt>, that typemap
applies to <tt>int</tt> and qualified variations such as <tt>const int</tt>.  In addition,
the typemap system follows <tt>typedef</tt> declarations.  For example:
</p>

<div class="code">
<pre>
%typemap(in) int nonnegative {
  $1 = $input;
  printf("Received an integer : %d\n",  $1);
}
%inline %{
typedef int Integer;
extern int fact(Integer nonnegative);    // Above typemap is applied
%}
</pre>
</div>

<p>
However, the matching of <tt>typedef</tt> only occurs in one direction.  If you
defined a typemap for <tt>Integer</tt>, it is not applied to arguments of
type <tt>int</tt>.
</p>

<p>
Typemaps can also be defined for groups of consecutive arguments.  For example:
</p>

<div class="code">
<pre>
%typemap(in) (char *str, int len) {
...
};

int count(char c, char *str, int len);
</pre>
</div>

<p>
When a multi-argument typemap is defined, the arguments are always handled as a single
Java parameter.  This allows the function to be used like this (notice how the length
parameter is omitted):
</p>

<div class="code">
<pre>
int c = example.count('e',"Hello World");
</pre>
</div>

<H3><a name="Java_typemaps_c_to_java_types">25.9.5 Typemaps for mapping C/C++ types to Java types</a></H3>


<p>
The typemaps available to the Java module include the common typemaps listed in the main typemaps section. 
There are a number of additional typemaps which are necessary for using SWIG with Java.
The most important of these implement the mapping of C/C++ types to Java types:
</p>

<br>&nbsp;
<table BORDER summary="Typemap mappings for C/C++ types to Java types">
<tr>
<td><b>Typemap</b></td>

<td><b>Description</b></td>
</tr>

<tr>
<td>jni</td>
<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>
</tr>

<tr>
<td>jtype</td>
<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>
</tr>

<tr>
<td>jstype</td>
<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>
</tr>

<tr>
<td>javain</td>
<td>Conversion from jstype to jtype. 
    These are Java code typemaps which transform the type used in the Java module class, proxy classes and type wrapper classes (as specified in the "jstype" typemap)
    to the type used in the Java intermediary JNI class (as specified in the "jtype" typemap).
    In other words the typemap provides the conversion to the native method call parameter types.</td>
</tr>

<tr>
<td>javaout</td>
<td>Conversion from jtype to jstype.
    These are Java code typemaps which transform the type used in the Java intermediary JNI class (as specified in the "jtype" typemap) to 
    the Java type used in the Java module class, proxy classes and type wrapper classes (as specified in the "jstype" typemap).
    In other words the typemap provides the conversion from the native method call return type. </td>
</tr>

<tr>
<td>javadirectorin</td>
<td>Conversion from jtype to jstype for director methods.
    These are Java code typemaps which transform the type used in the Java intermediary JNI class (as specified in the "jtype" typemap) to 
    the Java type used in the Java module class, proxy classes and type wrapper classes (as specified in the "jstype" typemap).
    This typemap provides the conversion for the parameters in the director methods when calling up from C++ to Java.
    See <a href="#Java_directors_typemaps">Director typemaps</a>.  </td>
</tr>

<tr>
<td>javadirectorout</td>
<td>Conversion from jstype to jtype for director methods.
    These are Java code typemaps which transform the type used in the Java module class, proxy classes and type wrapper classes (as specified in the "jstype" typemap)
    to the type used in the Java intermediary JNI class (as specified in the "jtype" typemap).
    This typemap provides the conversion for the return type in the director methods when returning from the C++ to Java upcall.
    See <a href="#Java_directors_typemaps">Director typemaps</a>.  </td>
</tr>

<tr>
<td>directorin</td>
<td>Conversion from C++ type to jni type for director methods.
  These are C++ typemaps which convert the parameters used in the C++ director method to the appropriate JNI intermediary type.
  The conversion is done in JNI code prior to calling the Java function from the JNI code.
  See <a href="#Java_directors_typemaps">Director typemaps</a>. </td>
</tr>

<tr>
<td>directorout</td>
<td>Conversion from jni type to C++ type for director methods.
  These are C++ typemaps which convert the JNI return type used in the C++ director method to the appropriate C++ return type.
  The conversion is done in JNI code after calling the Java function from the JNI code.
  See <a href="#Java_directors_typemaps">Director typemaps</a>. </td>
</tr>

</table>

<p>
If you are writing your own typemaps to handle a particular type, you will normally have to write a collection of them. 
The default typemaps are in "<tt>java.swg</tt>" and so might be a good place for finding typemaps to base any new ones on.
</p>

<p>
The "jni", "jtype" and "jstype" typemaps are usually defined together to handle the Java to C/C++ type mapping.
An "in" typemap should be accompanied by a "javain" typemap and likewise an "out" typemap by a "javaout" typemap.
If an "in" typemap is written, a "freearg" and "argout" typemap may also need to be written
as some types have a default "freearg" and/or "argout" typemap which may need overriding. 
The "freearg" typemap sometimes releases memory allocated by the "in" typemap. 
The "argout" typemap sometimes sets values in function parameters which are passed by reference in Java. 
</p>

<p>
Note that the "in" typemap marshals the JNI type held in the "jni" typemap to the real C/C++ type and for the opposite direction,
the "out" typemap marshals the real C/C++ type to the JNI type held in the "jni" typemap.
For <a href="#Java_default_non_primitive_typemaps">non-primitive types</a> 
the "in" and "out" typemaps are responsible for casting between the C/C++ pointer and the 64 bit <tt>jlong</tt> type.
There is no portable way to cast a pointer into a 64 bit integer type and the approach taken by SWIG is mostly portable, but breaks C/C++ aliasing rules.
In summary, these rules state that a pointer to any type must never be dereferenced by a pointer to any other incompatible type.
The following code snippet might aid in understand aliasing rules better:
</p>

<div class="code"><pre>
    short a;
    short* pa = 0;
    int i = 0x1234;

    a = (short)i;    /* okay */
    a = *(short*)&amp;i; /* breaks aliasing rules */
</pre></div>

<p>
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.
In SWIG, the "in" and "out" typemaps for pointers are typically
</p>

<div class="code"><pre>
    %typemap(in) struct Foo * %{
      $1 = *(struct Foo **)&amp;$input; /* cast jlong into C ptr */
    %}
    %typemap(out) struct Bar * %{
      *(struct Bar **)&amp;$result = $1; /* cast C ptr into jlong */
    %} 
    struct Bar {...};
    struct Foo {...};
    struct Bar * FooBar(struct Foo *f);
</pre></div>

<p>
resulting in the following code which breaks the aliasing rules:
</p>

<div class="code"><pre>
SWIGEXPORT jlong JNICALL Java_exampleJNI_FooBar(JNIEnv *jenv, jclass jcls,
                                                jlong jarg1, jobject jarg1_) {
  jlong jresult = 0 ;
  struct Foo *arg1 = (struct Foo *) 0 ;
  struct Bar *result = 0 ;
  
  (void)jenv;
  (void)jcls;
  (void)jarg1_;
  arg1 = *(struct Foo **)&amp;jarg1; 
  result = (struct Bar *)FooBar(arg1);
  *(struct Bar **)&amp;jresult = result; 
  return jresult;
}
</pre></div>

<p>
If you are using gcc as your C compiler, you might get a "dereferencing type-punned pointer will break strict-aliasing rules" warning about this.
Please see <a href="#Java_compiling_dynamic">Compiling a dynamic module</a> to avoid runtime problems with these strict aliasing rules.
</p>

<p>
The default code generated by SWIG for the Java module comes from the typemaps in the "<tt>java.swg</tt>" library file which implements the 
<a href="#Java_default_primitive_type_mappings">Default primitive type mappings</a> and 
<a href="#Java_default_non_primitive_typemaps">Default typemaps for non-primitive types</a> covered earlier.
There are other type mapping typemaps in the Java library. 
These are listed below:
</p>

<br>&nbsp;
<table BORDER summary="Java library typemap mappings">
<tr VALIGN=TOP>
<td><b>C Type</b></td>
<td><b>Typemap</b></td>
<td><b>File</b></td>
<td><b>Kind</b></td>
<td><b>Java Type</b></td>
<td><b>Function</b></td>
</tr>

<tr>
<td>primitive pointers and references</td>
<td>INPUT</td>
<td>typemaps.i</td>
<td>input</td>
<td>Java basic types</td>
<td>Allows values to be used for C functions taking pointers for data input.

<tr>
<td>primitive pointers and references</td>
<td>OUTPUT</td>
<td>typemaps.i</td>
<td>output</td>
<td>Java basic type arrays</td>
<td>Allows values held within an array to be used for C functions taking pointers for data output.

<tr>
<td>primitive pointers and references</td>
<td>INOUT</td>
<td>typemaps.i</td>
<td>input<br>output</td>
<td>Java basic type arrays</td>
<td>Allows values held within an array to be used for C functions taking pointers for data input and output.

<tr>
<td>string <br>wstring</td>
<td>[unnamed]</td>
<td>std_string.i</td>
<td>input<br> output</td>
<td>String</td>
<td>Use for std::string mapping to Java String.</td>
</tr>

<tr>
<td>arrays of primitive types</td>
<td>[unnamed]</td>
<td>arrays_java.i</td>
<td>input<br> output</td>
<td>arrays of primitive Java types</td>
<td>Use for mapping C arrays to Java arrays.</td>
</tr>

<tr>
<td>arrays of classes/structs/unions</td>
<td>JAVA_ARRAYSOFCLASSES macro</td>
<td>arrays_java.i</td>
<td>input<br> output</td>
<td>arrays of proxy classes</td>
<td>Use for mapping C arrays to Java arrays.</td>
</tr>

<tr>
<td>arrays of enums</td>
<td>ARRAYSOFENUMS</td>
<td>arrays_java.i</td>
<td>input<br> output</td>
<td>int[]</td>
<td>Use for mapping C arrays to Java arrays (typeunsafe and simple enum wrapping approaches only).</td>
</tr>

<tr VALIGN=TOP>
<td>char *</td>
<td>BYTE</td>
<td>various.i</td>
<td>input</td>
<td>byte[]</td>

<td VALIGN=TOP>Java byte array is converted to char array</td>
</tr>

<tr>
<td>char **</td>
<td>STRING_ARRAY</td>
<td>various.i</td>
<td>input<br> output</td>
<td>String[]</td>
<td>Use for mapping NULL terminated arrays of C strings to Java String arrays</td>
</tr>

<tr>
<td>unsigned char *</td>
<td>NIOBUFFER</td>
<td>various.i</td>
<td>input<br> output</td>
<td>java.nio.Buffer</td>
<td>Use for mapping directly allocated buffers to c/c++. useful with directors and long lived memory objects</td>
</tr>

</table>

<H3><a name="Java_typemap_attributes">25.9.6 Java typemap attributes</a></H3>


<p>
There are a few additional typemap attributes that the Java module supports.
</p>

<p>
The first of these is the 'throws' attribute.
The throws attribute is optional and specified after the typemap name and contains one or more comma separated classes for adding to the throws clause for any methods that use that typemap.
It is analogous to the <a href="#Java_exception_handling">%javaexception</a> feature's throws attribute.
</p>

<div class="code">
<pre>
%typemap(typemapname, throws="ExceptionClass1, ExceptionClass2") type { ... }
</pre>
</div>

<p>
The attribute is necessary for supporting Java checked exceptions and can be added to just about any typemap.
The list of typemaps include all the C/C++ (JNI) typemaps in the "<a href="Typemaps.html#Typemaps">Typemaps</a>" chapter and the
Java specific typemaps listed in <a href="#Java_typemaps_c_to_java_types">the previous section</a>, barring
the "jni", "jtype" and "jstype" typemaps as they could never contain code to throw an exception.
</p>

<p>
The throws clause is generated for the proxy method as well as the JNI method in the JNI intermediary class.
If a method uses more than one typemap and each of those typemaps have classes specified in the throws clause,
the union of the exception classes is added to the throws clause ensuring there are no duplicate classes.
See the <a href="#Java_nan_exception_typemap">NaN exception example</a> for further usage.
</p>

<p>
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>.
</p>

<p>
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.
</p>

<p>
<a name="Java_constructor_helper_function"></a>
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.
</p>

<H3><a name="Java_special_variables">25.9.7 Java special variables</a></H3>


<p>
The standard SWIG special variables are available for use within typemaps as described in the <a href="Typemaps.html#Typemaps">Typemaps documentation</a>, for example <tt>$1</tt>, <tt>$input</tt>,<tt>$result</tt> etc.
</p>

<p>
The Java module uses a few additional special variables:
</p>

<p>
<b><tt>$javaclassname</tt></b><br>
This special variable works like the other <a href="Typemaps.html#Typemaps_special_variables">special variables</a>
and <tt>$javaclassname</tt> is similar to <tt>$1_type</tt>. It expands to the class name for use in Java given a pointer. 
SWIG wraps unions, structs and classes using pointers and in this case it expands to the Java proxy class name.
For example, <tt>$javaclassname</tt> is replaced by the proxy classname <tt>Foo</tt> when wrapping a <tt>Foo *</tt> and 
<tt>$&amp;javaclassname</tt> expands to the proxy classname when wrapping the C/C++ type <tt>Foo</tt> and <tt>$*javaclassname</tt>
expands to the proxy classname when wrapping <tt>Foo *&amp;</tt>.
If the type does not have an associated proxy class, it expands to the type wrapper class name, for example,
<tt>SWIGTYPE_p_unsigned_short</tt> is generated when wrapping <tt>unsigned short *</tt>.
</p>

<p>
<b><tt>$javaclazzname</tt></b><br>
This special variable works like <tt>$javaclassname</tt>, but expands the fully qualified C++ class into the package name,
if used by the <a href="SWIGPlus.html#SWIGPlus_nspace">nspace feature</a>, and the proxy class name, mangled for use as a function name. 
For example, <tt>Namespace1::Namespace2::Klass</tt> is expanded into <tt>Namespace1_Namespace2_Klass_</tt>.
This special variable is usually used for making calls to a function in the intermediary JNI class, as they are mangled with this prefix.
</p>

<p>
<b><tt>$null</tt></b><br>
Used in input typemaps to return early from JNI functions that have either void or a non-void return type. Example:
</p>

<div class="code"><pre>
%typemap(check) int * %{ 
  if (error) {
    SWIG_JavaThrowException(jenv, SWIG_JavaIndexOutOfBoundsException, "Array element error");
    return $null;
  }
%}
</pre></div>

<p>
If the typemap gets put into a function with void as return, $null will expand to nothing:
</p>

<div class="code"><pre>
SWIGEXPORT void JNICALL Java_jnifn(...) {
    if (error) {
      SWIG_JavaThrowException(jenv, SWIG_JavaIndexOutOfBoundsException, "Array element error");
      return ;
    }
  ...
}
</pre></div>

<p>
otherwise $null expands to <i>NULL</i>
</p>

<div class="code"><pre>
SWIGEXPORT jobject JNICALL Java_jnifn(...) {
    if (error) {
      SWIG_JavaThrowException(jenv, SWIG_JavaIndexOutOfBoundsException, "Array element error");
      return NULL;
    }
  ...
}
</pre></div>

<p>
<b><tt>$javainput, $jnicall and $owner</tt></b><br>
The $javainput special variable is used in "javain" typemaps and $jnicall and $owner are used in "javaout" typemaps.
$jnicall is analogous to $action in %exception. It is replaced by the call to the native method in the intermediary JNI class.
$owner is replaced by either <tt>true</tt> if %newobject has been used, otherwise <tt>false</tt>.
$javainput is analogous to the $input special variable. It is replaced by the parameter name.
</p>

<p>
Here is an example:
</p>

<div class="code"><pre>
%typemap(javain) Class "Class.getCPtr($javainput)"
%typemap(javain) unsigned short "$javainput"
%typemap(javaout) Class * {
    return new Class($jnicall, $owner);
  }

%inline %{
    class Class {...};
    Class * bar(Class cls, unsigned short ush) { return new Class(); };
%}
</pre></div>

<p>
The generated proxy code is then:
</p>

<div class="code"><pre>
public static Class bar(Class cls, int ush) {
  return new Class(exampleJNI.bar(Class.getCPtr(cls), cls, ush), false);
}
</pre></div>

<p>
Here $javainput has been replaced by <tt>cls</tt> and <tt>ush</tt>. $jnicall has been replaced by 
the native method call, <tt>exampleJNI.bar(...)</tt> and $owner has been replaced by <tt>false</tt>.
If %newobject is used by adding the following at the beginning of our example:
</p>

<div class="code"><pre>
%newobject bar(Class cls, unsigned short ush);
</pre></div>

<p>
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>:
</p>

<div class="code"><pre>
public static Class bar(Class cls, int ush) {
  return new Class(exampleJNI.bar(Class.getCPtr(cls), cls, ush), true);
}
</pre></div>

<p>
<b><tt>$static</tt></b><br>
This special variable expands to either <i>static</i> or nothing depending on whether the class is an inner Java class or not.
It is used in the "javaclassmodifiers" typemap so that global classes can be wrapped as Java proxy classes and nested C++ classes/enums
can be wrapped with the Java equivalent, that is, static inner proxy classes.
</p>

<p>
<b><tt>$error, $jniinput, $javacall and $packagepath</tt></b><br>
These special variables are used in the directors typemaps. See <a href="#Java_directors_typemaps">Director specific typemaps</a> for details.
</p>

<p>
<b><tt>$module</tt></b><br>
This special variable expands to the module name, as specified by <tt>%module</tt> or the <tt>-module</tt> commandline option.
</p>

<p>
<b><tt>$imclassname</tt></b><br>
This special variable expands to the intermediary class name. Usually this is the same as '$moduleJNI',
unless the jniclassname attribute is specified in the <a href="Java.html#Java_module_directive">%module directive</a>.
</p>

<H3><a name="Java_typemaps_for_c_and_cpp">25.9.8 Typemaps for both C and C++ compilation</a></H3>


<p>
JNI calls must be written differently depending on whether the code is being compiled as C or C++. 
For example C compilation requires the pointer to a function pointer struct member syntax like
</p>

<div class="code"><pre>
const jclass clazz = (*jenv)-&gt;FindClass(jenv, "java/lang/String");
</pre></div>

<p>
whereas C++ code compilation of the same function call is a member function call using a class pointer like
</p>

<div class="code"><pre>
const jclass clazz = jenv-&gt;FindClass("java/lang/String");
</pre></div>

<p>
To enable typemaps to be used for either C or C++ compilation, a set of JCALLx macros have been defined in Lib/java/javahead.swg, 
where x is the number of arguments in the C++ version of the JNI call. 
The above JNI calls would be written in a typemap like this
</p>

<div class="code"><pre>
const jclass clazz = JCALL1(FindClass, jenv, "java/lang/String");
</pre></div>

<p>
Note that the SWIG preprocessor expands these into the appropriate C or C++ JNI calling convention. 
The C calling convention is emitted by default and the C++ calling convention is emitted when using the -c++ SWIG commandline option. 
If you do not intend your code to be targeting both C and C++ then your typemaps can use the appropriate JNI calling convention and need not use the JCALLx macros.
</p>


<H3><a name="Java_code_typemaps">25.9.9 Java code typemaps</a></H3>


<p>
Most of SWIG's typemaps are used for the generation of C/C++ code. 
The typemaps in this section are used solely for the generation of Java code. 
Elements of proxy classes and type wrapper classes come from the following typemaps (the defaults).
</p>

<p><tt>%typemap(javabase)</tt></p>
<div class="indent">
base (extends) for Java class: empty default
<br>
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
that might have been parsed. If this flag is not specified and there are C++ base classes, then a multiple inheritance warning
is issued and the code in the typemap is ignored.
The typemap also accepts a <tt>notderived</tt> attribute as an optional flag. When set to "1", it will not apply to classes that
are derived from a C++ base. 
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>.
</div>

<p><tt>%typemap(javabody)</tt></p>
<div class="indent">
  the essential support body for proxy classes (proxy base classes only), typewrapper classes and enum classes.
  Default contains extra constructors, memory ownership control member variables (<tt>swigCMemOwn</tt>, <tt>swigCPtr</tt>), the <tt>getCPtr</tt> method etc.
</div>

<p><tt>%typemap(javabody_derived)</tt></p>
<div class="indent">
  the essential support body for proxy classes (derived classes only).
  Same as "javabody" typemap, but only used for proxy derived classes.
</div>

<p><tt>%typemap(javaclassmodifiers)</tt></p>
<div class="indent">
class modifiers for the Java class: default is "public class"
</div>

<p><tt>%typemap(javacode)</tt></p>
<div class="indent">
Java code is copied verbatim to the Java class: empty default
</div>

<p><tt>%typemap(javadestruct, methodname="delete", methodmodifiers="public synchronized")</tt> <br></p>
<div class="indent">
destructor wrapper - the <tt>delete()</tt> method (proxy classes only),
used for all proxy classes except those which have a base class
: default calls C++ destructor (or frees C memory) and resets <tt>swigCPtr</tt> and <tt>swigCMemOwn</tt> flags
<br>
<br>
Note that the <tt>delete()</tt> method name is configurable and is specified by the <tt>methodname</tt> attribute.
The method modifiers are also configurable via the <tt>methodmodifiers</tt> attribute.
</div>

<p><tt>%typemap(javadestruct_derived, methodname="delete", methodmodifiers="public synchronized")</tt></p>
<div class="indent">
destructor wrapper - the <tt>delete()</tt> method (proxy classes only),
same as "javadestruct" but only used for derived proxy classes
: default calls C++ destructor (or frees C memory) and resets <tt>swigCPtr</tt> and <tt>swigCMemOwn</tt> flags
<br>
<br>
Note that the <tt>delete()</tt> method name is configurable and is specified by the <tt>methodname</tt> attribute.
The method modifiers are also configurable via the <tt>methodmodifiers</tt> attribute.
</div>

<p><tt>%typemap(javaimports)</tt></p>
<div class="indent">
import statements for Java class: empty default
</div>

<p><tt>%typemap(javainterfaces)</tt></p>
<div class="indent">
interfaces (implements) for Java class: empty default
</div>

<p><tt>%typemap(javafinalize)</tt></p>
<div class="indent">
the <tt>finalize()</tt> method (proxy classes only): default calls the <tt>delete()</tt> method

<p>
Note that the default javafinalize typemap must contain the full implementation of the finalize method.
Any customization to this typemap must still declare a java finalize method with the correct signature.
Note also that the name of the generated "delete" method may be affected by <tt>javadestruct</tt> and <tt>javadestruct_derived</tt> typemaps.
Below shows an example modifying the finalizer, assuming the <tt>delete</tt> method has been renamed to <tt>swig_delete</tt>.
</p>

<div class="code"><pre>
%typemap(javafinalize) SWIGTYPE %{
   protected void finalize() {
     swig_delete();  // renamed to prevent conflict with existing delete method
   }
]%
</pre></div>

</div>

<p>
<b>Compatibility Note:</b> In SWIG-1.3.21 and earlier releases, typemaps called "javagetcptr" and "javaptrconstructormodifiers" were available.
These are deprecated and the "javabody" typemap can be used instead.
</p>

<p>
In summary the contents of the typemaps make up a proxy class like this:
</p>

<div class="code">
<pre>
[ javaimports typemap ]
[ javaclassmodifiers typemap ] javaclassname extends [ javabase typemap ]
                                             implements [ javainterfaces typemap ] {
[ javabody or javabody_derived typemap ]
[ javafinalize typemap ]
public synchronized void <i>delete</i>() [ javadestruct OR javadestruct_derived typemap ]
[ javacode typemap ]
... proxy functions ...
}
</pre>
</div>

<p>
Note the <tt><i>delete</i>()</tt> methodname and method modifiers are configurable, see "javadestruct" and "javadestruct_derived" typemaps above.
</p>

<p>
The type wrapper class is similar in construction:
</p>

<div class="code">
<pre>
[ javaimports typemap ]
[ javaclassmodifiers typemap ] javaclassname extends [ javabase typemap ]
                                             implements [ javainterfaces typemap ] {
[ javabody typemap ]
[ javacode typemap ]
}
</pre>
</div>

<p>The enum class is also similar in construction:</p>
<div class="code">
<pre>
[ javaimports typemap ]
[ javaclassmodifiers typemap ] javaclassname extends [ javabase typemap ]
                                             implements [ javainterfaces typemap ] {
... Enum values ...
[ javabody typemap ]
[ javacode typemap ]
}
</pre>
</div>

<p>
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.
</p>

<p>
The defaults can be overridden to tailor these classes.
Here is an example which will change the <tt>getCPtr</tt> method and constructor from the default public access to protected access. 
If the classes in one package are not using the classes in another package, then these methods need not be public and removing access to these low level implementation details, is a good thing.
If you are invoking SWIG more than once and generating the wrapped classes into different packages in each invocation, then you cannot do this as you will then have different packages.
</p>

<div class="code">
<pre>
%typemap(javabody) SWIGTYPE %{
  private transient long swigCPtr;
  protected transient boolean swigCMemOwn;

  protected $javaclassname(long cPtr, boolean cMemoryOwn) {
    swigCMemOwn = cMemoryOwn;
    swigCPtr = cPtr;
  }

  protected static long getCPtr($javaclassname obj) {
    return (obj == null) ? 0 : obj.swigCPtr;
  }
%}
</pre>
</div>

<p>
The typemap code is the same that is in "<tt>java.swg</tt>", barring the last two method modifiers.
Note that <tt>SWIGTYPE</tt> will target all proxy classes, but not the type wrapper classes.
Also the above typemap is only used for proxy classes that are potential base classes.
To target proxy classes that are derived from a wrapped class as well, the "javabody_derived" typemap should also be overridden.
</p>

<p>
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:
</p>

<div class="code">
<pre>
%typemap(javabody) SWIGTYPE *, SWIGTYPE &amp;, SWIGTYPE [], SWIGTYPE (CLASS::*) %{
  private transient long swigCPtr;

  protected $javaclassname(long cPtr, boolean bFutureUse) {
    swigCPtr = cPtr;
  }

  protected $javaclassname() {
    swigCPtr = 0;
  }

  protected static long getCPtr($javaclassname obj) {
    return (obj == null) ? 0 : obj.swigCPtr;
  }
%}
</pre>
</div>

<p>
Again this is the same that is in "<tt>java.swg</tt>", barring the method modifier for <tt>getCPtr</tt>.
</p>

<p>
When using <a href="Modules.html#Modules">multiple modules</a> or the <a href="#Java_namespaces">nspace feature</a> it is common to invoke SWIG with a different <tt>-package</tt>
command line option for each module.
However, by default the generated code may not compile if 
generated classes in one package use generated classes in another package.
The visibility of the
<tt>getCPtr()</tt> and pointer constructor generated from the <tt>javabody</tt> typemaps needs changing.
The default visibility is <tt>protected</tt> but it needs to be <tt>public</tt> for access from a different package.
Just changing 'protected' to 'public' in the typemap achieves this.
Two macros are available in <tt>java.swg</tt> to make this easier and using them is the preferred approach
over simply copying the typemaps and modifying as this is forward compatible with any changes in
the <tt>javabody</tt> typemap in future versions of SWIG.
The macros are for the proxy and typewrapper classes and can respectively be used to
to make the method and constructor public:
</p>

<div class="code">
<pre>
  SWIG_JAVABODY_PROXY(public, public, SWIGTYPE)
  SWIG_JAVABODY_TYPEWRAPPER(public, public, public, SWIGTYPE)
</pre>
</div>

<H3><a name="Java_directors_typemaps">25.9.10 Director specific typemaps</a></H3>


<p>
The Java directors feature requires the "javadirectorin", "javadirectorout", "directorin" and the "directorout" typemaps in order to work properly.
The "javapackage" typemap is an optional typemap used to identify the Java package path for individual SWIG generated proxy classes used in director methods.
</p>

<p><tt>%typemap(directorin)</tt></p>
<div class="indent">

<p>
The "directorin" typemap is used for converting arguments in the C++ director class to the appropriate JNI type before the upcall to Java.
This typemap also specifies the JNI field descriptor for the type in the "descriptor" attribute.
For example, integers are converted as follows:
</p>

<div class="code">
<pre>
%typemap(directorin,descriptor="I") int "$input = (jint) $1;"
</pre>
</div>

<p>
<code>$input</code> is the SWIG name of the JNI temporary variable passed to Java in the upcall.
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++.
For more about JNI field descriptors and their importance, refer to the <a href="#Java_typemaps">JNI documentation mentioned earlier</a>.
A typemap for C character strings is:
</p>

<div class="code">
<pre>
%typemap(directorin,descriptor="Ljava/lang/String;") char *
  %{ $input = jenv-&gt;NewStringUTF($1); %}
</pre>
</div>


<p>
User-defined types have the default "descriptor" attribute "<code>L$packagepath/$javaclassname;</code>" where <code>$packagepath</code> 
is the package name passed from the SWIG command line and <code>$javaclassname</code> is the Java proxy class' name.
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.
<b>Do not forget the terminating ';' for JNI field descriptors starting with 'L'.</b>
If the ';' is left out, Java will generate a "method not found" runtime error.
Note that the <code>$packagepath</code> substitution always uses the path separator '/' when expanded.
The <code>$javaclassname</code> expansion can be confusing as it is normally expanded using the '.' separator.
However, <code>$javaclassname</code> is expanded using the path separator '/' in typemap's "descriptor" attribute
as well as in the "directorthrows" typemap.
</p>
</div>


<p><tt>%typemap(directorout)</tt></p>
<div class="indent">

<p>
The "directorout" typemap is used for converting the JNI return type in the C++ director class to the appropriate C++ type after the upcall to Java.
For example, integers are converted as follows:
</p>

<div class="code">
<pre>
%typemap(directorout) int %{ $result = (int)$input; %}
</pre>
</div>

<p>
<code>$input</code> is the SWIG name of the JNI temporary variable returned from Java after the upcall.
<code>$result</code> is the resulting output.
A typemap for C character strings is:
</p>

<div class="code">
<pre>
%typemap(directorout) char * {
  $1 = 0;
  if ($input) {
    $result = (char *)jenv-&gt;GetStringUTFChars($input, 0);
    if (!$1) return $null;
  }
}
</pre>
</div>

</div>


<p><tt>%typemap(javadirectorin)</tt></p>
<div class="indent">

<p>
Conversion from jtype to jstype for director methods.
These are Java code typemaps which transform the type used in the Java intermediary JNI class (as specified in the "jtype" typemap) to 
the Java type used in the Java module class, proxy classes and type wrapper classes (as specified in the "jstype" typemap).
This typemap provides the conversion for the parameters in the director methods when calling up from C++ to Java.
</p>

<p>
For primitive types, this typemap is usually specified as:
</p>

<div class="code">
<pre>
%typemap(javadirectorin) int "$jniinput"
</pre>
</div>

<p>
The <code>$jniinput</code> special variable is analogous to <code>$javainput</code> special variable.
It is replaced by the input parameter name.
</p>

</div>


<p><tt>%typemap(javadirectorout)</tt></p>
<div class="indent">

<p>
Conversion from jstype to jtype for director methods.
These are Java code typemaps which transform the type used in the Java module class, proxy classes and type wrapper classes (as specified in the "jstype" typemap)
to the type used in the Java intermediary JNI class (as specified in the "jtype" typemap).
This typemap provides the conversion for the return type in the director methods when returning from the C++ to Java upcall.
</p>

<p>
For primitive types, this typemap is usually specified as:
</p>

<div class="code">
<pre>
%typemap(javadirectorout) int "$javacall"
</pre>
</div>

<p>
The <code>$javacall</code> special variable is analogous to the <code>$jnicall</code> special variable.
It is replaced by the call to the target Java method.
The target method is the method in the Java proxy class which overrides the virtual C++ method in the C++ base class.
</p>

</div>

<p><tt>%typemap(directorthrows)</tt></p>
<div class="indent">

<p>
Conversion of Java exceptions to C++ exceptions in director method's exception handling.
This typemap is expected to test the <tt>$error</tt> special variable for a matching Java exception
and if successful convert and throw it into a C++ exception given by the typemap's type.
The <code>$error</code> special variable is of type <code>jthrowable</code> and is
substituted with a unique variable name in the generated code.
</p>

<p>
The example below converts a Java <code>java.lang.IndexOutOfBoundsException</code> exception
to the typemap's type, that is <code>std::out_of_range</code>:
</p>

<div class="code">
<pre>
%typemap(directorthrows) std::out_of_range %{
  if (Swig::ExceptionMatches(jenv, $error, "java/lang/IndexOutOfBoundsException")) {
    throw std::out_of_range(Swig::JavaExceptionMessage(jenv, $error).message());
  }
%}
</pre>
</div>

<p>
The utility function <code>Swig::ExceptionMatches</code>
and class <code>Swig::JavaExceptionMessage</code> are helpers available when using directors and are described
in the <a href="#Java_exceptions_from_directors">Java Exceptions from Directors</a> section.
</p>

</div>

<p><tt>%typemap(javapackage)</tt></p>
<div class="indent">


<p>
The "javapackage" typemap is optional; it serves to identify a class's Java package.
This typemap should be used in conjunction with classes that are defined outside of the current SWIG interface file.
The typemap is only used if the type is used in a director method, that is, in a virtual method in a director class.
For example:
</p>

<div class="code">
<pre>
// class Foo is handled in a different interface file:
%import "Foo.i"

%feature("director") Example;

%inline {
  class Bar { };

  class Example {
  public:
    virtual ~Example();
    virtual void ping(Foo *arg1, Bar *arg2);
  };
}
</pre>
</div>

<p>
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>.
Without the "javapackage" typemap, SWIG will assume that the Foo class belongs to <i>com.wombat.example</i> class.
The corrected interface file looks like:
</p>

<div class="code">
<pre>
// class Foo is handled in a different interface file:
%import "Foo.i"
%typemap("javapackage") Foo, Foo *, Foo &amp; "com.wombat.foo";
%feature("director") Example;

%inline {
  class Bar { };

  class Example {
  public:
    virtual ~Example();
    virtual void ping(Foo *arg1, Bar *arg2);
  };
}
</pre>
</div>

<p>
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.
Practically speaking, you should create a separate SWIG interface file, which is %import-ed into each SWIG interface file, when you have multiple Java packages.
Note the helper macros below, <code>OTHER_PACKAGE_SPEC</code> and <code>ANOTHER_PACKAGE_SPEC</code>, which reduce the amount of extra typing.
"<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.
</p>

<div class="code">
<pre>
%typemap("javapackage") SWIGTYPE, SWIGTYPE *, SWIGTYPE &amp;
                                            "package.for.most.classes";

%define OTHER_PACKAGE_SPEC(TYPE...)
%typemap("javapackage") TYPE, TYPE *, TYPE &amp; "package.for.other.classes";
%enddef

%define ANOTHER_PACKAGE_SPEC(TYPE...)
%typemap("javapackage") TYPE, TYPE *, TYPE &amp; "package.for.another.set";
%enddef

OTHER_PACKAGE_SPEC(Package_2_class_one)
ANOTHER_PACKAGE_SPEC(Package_3_class_two)
/* etc */
</pre>
</div>

<p>
The basic strategy here is to provide a default package typemap for the majority of the classes, only providing "javapackage" typemaps for the exceptions.
</p>

</div>

<H2><a name="Java_typemap_examples">25.10 Typemap Examples</a></H2>


<p>
This section includes a few examples of typemaps.  For more examples, you
might look at the files "<tt>java.swg</tt>" and "<tt>typemaps.i</tt>" in
the SWIG library.
</p>


<H3><a name="Java_simpler_enum_classes">25.10.1 Simpler Java enums for enums without initializers</a></H3>


<p>
The default <a href="#Java_proper_enums_classes">Proper Java enums</a> approach to wrapping enums is somewhat verbose.
This is to handle all possible C/C++ enums, in particular enums with initializers.
The generated code can be simplified if the enum being wrapped does not have any initializers.
</p>

<p>
The following shows how to remove the support methods that are generated by default and instead use the methods in the Java
enum base class <tt>java.lang.Enum</tt> and <tt>java.lang.Class</tt> for marshalling enums between C/C++ and Java.
The type used for the typemaps below is <tt>enum SWIGTYPE</tt> which is the default type used for all enums.
The "enums.swg" file should be examined in order to see the original overridden versions of the typemaps.
</p>

<div class="code">
<pre>
%include "enums.swg"

%typemap(javain) enum SWIGTYPE "$javainput.ordinal()"
%typemap(javaout) enum SWIGTYPE {
    return $javaclassname.class.getEnumConstants()[$jnicall];
  }
%typemap(javabody) enum SWIGTYPE ""

%inline %{
  enum HairType { blonde, ginger, brunette };
  void setHair(HairType h);
  HairType getHair();
%}
</pre>
</div>

<p>
SWIG will generate the following Java enum, which is somewhat simpler than the default:
</p>

<div class="code">
<pre>
public enum HairType {
  blonde,
  ginger,
  brunette;
}
</pre>
</div>

<p>
and the two Java proxy methods will be:
</p>

<div class="code">
<pre>
public static void setHair(HairType h) {
  exampleJNI.setHair(h.ordinal());
}

public static HairType getHair() {
  return HairType.class.getEnumConstants()[exampleJNI.getHair()];
}
</pre>
</div>

<p>
For marshalling Java enums to C/C++ enums, the <tt>ordinal</tt> method is used to convert the
Java enum into an integer value for passing to the JNI layer, see the "javain" typemap.
For marshalling C/C++ enums to Java enums, the C/C++ enum value is cast to an integer in the C/C++ typemaps (not shown).
This integer value is then used to index into the array of enum constants that the Java language provides.
See the <tt>getEnumConstants</tt> method in the "javaout" typemap.
</p>

<p>
These typemaps can often be used as the default for wrapping enums as in many cases there won't be any enum initializers.
In fact a good strategy is to always use these typemaps and to specifically handle enums with initializers using %apply.
This would be done by using the original versions of these typemaps in "enums.swg" under another typemap name for applying using %apply.
</p>


<H3><a name="Java_exception_typemap">25.10.2 Handling C++ exception specifications as Java exceptions</a></H3>


<p>
This example demonstrates various ways in which C++ exceptions can be tailored and converted into Java exceptions.
Let's consider a simple file class <tt>SimpleFile</tt> and an exception class <tt>FileException</tt> which it may throw on error:
</p>

<div class="code">
<pre>
%include "std_string.i" // for std::string typemaps
#include &lt;string&gt;

class FileException {
  std::string message;
public:
  FileException(const std::string&amp; msg) : message(msg) {}
  std::string what() {
    return message;
  }
};

class SimpleFile {
  std::string filename;
public:
  SimpleFile(const std::string&amp; filename) : filename(filename) {}
  void open() throw(FileException) {
  ...
  }
};
</pre>
</div>

<p>
As the <tt>open</tt> method has a C++ exception specification, SWIG will parse this and know that the method can throw an exception.
The <a href="Typemaps.html#throws_typemap">"throws" typemap</a> is then used when SWIG encounters an exception specification.
The default generic "throws" typemap looks like this:
</p>

<div class="code">
<pre>
%typemap(throws) SWIGTYPE, SWIGTYPE &amp;, SWIGTYPE *, SWIGTYPE [ANY] %{
  SWIG_JavaThrowException(jenv, SWIG_JavaRuntimeException,
                          "C++ $1_type exception thrown");
  return $null;
%}
</pre>
</div>

<p>
Basically SWIG will generate a C++ try catch block and the body of the "throws" typemap constitutes the catch block.
The above typemap calls a SWIG supplied method which throws a <tt>java.lang.RuntimeException</tt>.
This exception class is a runtime exception and therefore not a checked exception.
If, however, we wanted to throw a checked exception, say <tt>java.io.IOException</tt>, then we could use the following typemap:
</p>

<div class="code">
<pre>
%typemap(throws, throws="java.io.IOException") FileException {
  jclass excep = jenv-&gt;FindClass("java/io/IOException");
  if (excep)
    jenv-&gt;ThrowNew(excep, $1.what().c_str());
  return $null;
}
</pre>
</div>

<p>
Note that this typemap uses the 'throws' <a href="#Java_typemap_attributes">typemap attribute</a> to ensure a throws clause is generated.
The generated proxy method then specifies the checked exception by containing <tt>java.io.IOException</tt> in the throws clause:
</p>

<div class="code">
<pre>
public class SimpleFile {
  ...
  public void open() throws java.io.IOException { ... }
}
</pre>
</div>

<p>
Lastly, if you don't want to map your C++ exception into one of the standard Java exceptions, the C++ class can be wrapped and turned into a custom Java exception class.
If we go back to our example, the first thing we must do is get SWIG to wrap <tt>FileException</tt> and ensure that it derives from <tt>java.lang.Exception</tt>.
Additionally, we might want to override the <tt>java.lang.Exception.getMessage()</tt> method.
The typemaps to use then are as follows:
</p>

<div class="code">
<pre>
%typemap(javabase) FileException "java.lang.Exception";
%typemap(javacode) FileException %{
  public String getMessage() {
    return what();
  }
%}
</pre>
</div>

<p>
This generates:
</p>

<div class="code">
<pre>
public class FileException extends java.lang.Exception {
  ...
  public String getMessage() {
    return what();
  }

  public FileException(String msg) { ... }

  public String what() {
    return exampleJNI.FileException_what(swigCPtr, this);
  }
}
</pre>
</div>

<p>
We could alternatively have used <tt>%rename</tt> to rename <tt>what()</tt> into <tt>getMessage()</tt>.
</p>


<H3><a name="Java_nan_exception_typemap">25.10.3 NaN Exception - exception handling for a particular type</a></H3>


<p>
A Java exception can be thrown from any Java or JNI code.
Therefore, as most typemaps contain either Java or JNI code, just about any typemap could throw an exception.
The following example demonstrates exception handling on a type by type basis by checking for 'Not a number' (NaN) whenever a parameter of type <tt>float</tt> is wrapped.
</p>

<p>
Consider the following C++ code:
</p>

<div class="code">
<pre>
bool calculate(float first, float second);
</pre>
</div>

<p>
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':
</p>

<div class="code">
<pre>
%module example
%typemap(javain) float "$module.CheckForNaN($javainput)"
%pragma(java) modulecode=%{
  /** Simply returns the input value unless it is not a number,
      whereupon an exception is thrown. */
  static protected float CheckForNaN(float num) {
    if (Float.isNaN(num))
      throw new RuntimeException("Not a number");
    return num;
  }
%}
</pre>
</div>

<p>
Note that the <tt>CheckForNaN</tt> support method has been added to the module class using the <tt>modulecode</tt> pragma.
The following shows the generated code of interest:
</p>

<div class="code">
<pre>
public class example {
  ...

  /** Simply returns the input value unless it is not a number,
      whereupon an exception is thrown. */
  static protected float CheckForNaN(float num) {
    if (Float.isNaN(num))
      throw new RuntimeException("Not a number");
    return num;
  }

  public static boolean calculate(float first, float second) {
    return exampleJNI.calculate(example.CheckForNaN(first), example.CheckForNaN(second));
  }
}
</pre>
</div>

<p>
Note that the "javain" typemap is used for every occurrence of a <tt>float</tt> being used as an input.
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>.
</p>

<p>
The exception checking could alternatively have been placed into the 'pre' attribute that the "javain" typemap supports.
The "javain" typemap above could be replaced with the following:
</p>

<div class="code">
<pre>
%typemap(javain, pre="    $module.CheckForNaN($javainput);") float "$javainput"
</pre>
</div>

<p>
which would modify the <tt>calculate</tt> function to instead be generated as:
</p>

<div class="code">
<pre>
public class example {
  ...
  public static boolean calculate(float first, float second) {
    example.CheckForNaN(first);
    example.CheckForNaN(second);
    {
      return exampleJNI.calculate(first, second);
    }
  }
}
</pre>
</div>

<p>
See the <a href="#Java_date_marshalling">Date marshalling example</a> for an example using further "javain" typemap attributes.
</p>

<p>
If we decide that what we actually want is a checked exception instead of a runtime exception, we can change this easily enough.
The proxy method that uses <tt>float</tt> as an input, must then add the exception class to the throws clause.
SWIG can handle this as it supports the 'throws' <a href="#Java_typemap_attributes">typemap attribute</a> for specifying classes for the throws clause.
Thus we can modify the pragma and the typemap for the throws clause:
</p>

<div class="code">
<pre>
%typemap(javain, throws="java.lang.Exception") float "$module.CheckForNaN($javainput)"
%pragma(java) modulecode=%{
  /** Simply returns the input value unless it is not a number,
      whereupon an exception is thrown. */
  static protected float CheckForNaN(float num) throws java.lang.Exception {
    if (Float.isNaN(num))
      throw new RuntimeException("Not a number");
    return num;
  }
%}
</pre>
</div>

<p>
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>,
the throws clause contains a single instance of <tt>java.lang.Exception</tt>:
</p>

<div class="code">
<pre>
public class example {
  ...

  /** Simply returns the input value unless it is not a number,
      whereupon an exception is thrown. */
  static protected float CheckForNaN(float num) throws java.lang.Exception {
    if (Float.isNaN(num))
      throw new RuntimeException("Not a number");
    return num;
  }

  public static boolean calculate(float first, float second) throws java.lang.Exception {
    return exampleJNI.calculate(example.CheckForNaN(first), example.CheckForNaN(second));
  }
}
</pre>
</div>

<p>
If we were a martyr to the JNI cause, we could replace the succinct code within the "javain" typemap with a few pages of JNI code.
If we had, we would have put it in the "in" typemap which, like all JNI and Java typemaps, also supports the 'throws' attribute.
</p>

<H3><a name="Java_converting_java_string_arrays">25.10.4 Converting Java String arrays to char ** </a></H3>


<p>
A common problem in many C programs is the processing of command line arguments, which are usually passed in an array of NULL terminated strings.   
The following SWIG interface file allows a Java String array to be used as a <tt>char **</tt> object.
</p>

<div class="code"><pre>
%module example

/* This tells SWIG to treat char ** as a special case when used as a parameter
   in a function call */
%typemap(in) char ** (jint size) {
    int i = 0;
    size = (*jenv)-&gt;GetArrayLength(jenv, $input);
    $1 = (char **) malloc((size+1)*sizeof(char *));
    /* make a copy of each string */
    for (i = 0; i&lt;size; i++) {
        jstring j_string = (jstring)(*jenv)-&gt;GetObjectArrayElement(jenv, $input, i);
        const char * c_string = (*jenv)-&gt;GetStringUTFChars(jenv, j_string, 0);
        $1[i] = malloc((strlen(c_string)+1)*sizeof(char));
        strcpy($1[i], c_string);
        (*jenv)-&gt;ReleaseStringUTFChars(jenv, j_string, c_string);
        (*jenv)-&gt;DeleteLocalRef(jenv, j_string);
    }
    $1[i] = 0;
}

/* This cleans up the memory we malloc'd before the function call */
%typemap(freearg) char ** {
    int i;
    for (i=0; i&lt;size$argnum-1; i++)
      free($1[i]);
    free($1);
}

/* This allows a C function to return a char ** as a Java String array */
%typemap(out) char ** {
    int i;
    int len=0;
    jstring temp_string;
    const jclass clazz = (*jenv)-&gt;FindClass(jenv, "java/lang/String");

    while ($1[len]) len++;    
    jresult = (*jenv)-&gt;NewObjectArray(jenv, len, clazz, NULL);
    /* exception checking omitted */

    for (i=0; i&lt;len; i++) {
      temp_string = (*jenv)-&gt;NewStringUTF(jenv, *result++);
      (*jenv)-&gt;SetObjectArrayElement(jenv, jresult, i, temp_string);
      (*jenv)-&gt;DeleteLocalRef(jenv, temp_string);
    }
}

/* These 3 typemaps tell SWIG what JNI and Java types to use */
%typemap(jni) char ** "jobjectArray"
%typemap(jtype) char ** "String[]"
%typemap(jstype) char ** "String[]"

/* These 2 typemaps handle the conversion of the jtype to jstype typemap type
   and vice versa */
%typemap(javain) char ** "$javainput"
%typemap(javaout) char ** {
    return $jnicall;
  }

/* Now a few test functions */
%inline %{

int print_args(char **argv) {
    int i = 0;
    while (argv[i]) {
         printf("argv[%d] = %s\n", i, argv[i]);
         i++;
    }
    return i;
}

char **get_args() {
  static char *values[] = { "Dave", "Mike", "Susan", "John", "Michelle", 0};
  return &amp;values[0];
}

%}
</pre></div>

<p>
Note that the 'C' JNI calling convention is used. 
Checking for any thrown exceptions after JNI function calls has been omitted. 
When this module is compiled, our wrapped C functions can be used by the following Java program:
</p>

<div class="code"><pre>
// File runme.java

public class runme {

  static {
    try {
      System.loadLibrary("example");
    } catch (UnsatisfiedLinkError e) {
      System.err.println("Native code library failed to load. " + e);
      System.exit(1);
    }
  }

  public static void main(String argv[]) {
    String animals[] = {"Cat","Dog","Cow","Goat"};
    example.print_args(animals);
    String args[] = example.get_args();
    for (int i=0; i&lt;args.length; i++)
        System.out.println(i + ":" + args[i]);
  }
}
</pre></div>

<p>
When compiled and run we get:
</p>

<div class="code"><pre>
$ java runme
argv[0] = Cat
argv[1] = Dog
argv[2] = Cow
argv[3] = Goat
0:Dave
1:Mike
2:Susan
3:John
4:Michelle
</pre></div>

<p>
In the example, a few different typemaps are used.  The "in" typemap is
used to receive an input argument and convert it to a C array.  Since dynamic
memory allocation is used to allocate memory for the array, the
"freearg" typemap is used to later release this memory after the execution of
the C function. The "out" typemap is used for function return values.
Lastly the "jni", "jtype" and "jstype" typemaps are also required to specify
what Java types to use.
</p>

<H3><a name="Java_expanding_java_object">25.10.5 Expanding a Java object to multiple arguments</a></H3>


<p>
Suppose that you had a collection of C functions with arguments
such as the following:
</p>

<div class="code">
<pre>
int foo(int argc, char **argv);
</pre>
</div>

<p>
In the previous example, a typemap was written to pass a Java String array as the <tt>char **argv</tt>.  This
allows the function to be used from Java as follows:
</p>

<div class="code">
<pre>
example.foo(4, new String[]{"red", "green", "blue", "white"});
</pre>
</div>

<p>
Although this works, it's a little awkward to specify the argument count.  To fix this, a multi-argument
typemap can be defined.  This is not very difficult--you only have to make slight modifications to the
previous example's typemaps:
</p>

<div class="code">
<pre>
%typemap(in) (int argc, char **argv) {
    int i = 0;
    $1 = (*jenv)-&gt;GetArrayLength(jenv, $input);
    $2 = (char **) malloc(($1+1)*sizeof(char *));
    /* make a copy of each string */
    for (i = 0; i&lt;$1; i++) {
        jstring j_string = (jstring)(*jenv)-&gt;GetObjectArrayElement(jenv, $input, i);
        const char * c_string = (*jenv)-&gt;GetStringUTFChars(jenv, j_string, 0);
        $2[i] = malloc((strlen(c_string)+1)*sizeof(char));
        strcpy($2[i], c_string);
        (*jenv)-&gt;ReleaseStringUTFChars(jenv, j_string, c_string);
        (*jenv)-&gt;DeleteLocalRef(jenv, j_string);
    }
    $2[i] = 0;
}

%typemap(freearg) (int argc, char **argv) {
    int i;
    for (i=0; i&lt;$1-1; i++)
      free($2[i]);
    free($2);
}

%typemap(jni) (int argc, char **argv) "jobjectArray"
%typemap(jtype) (int argc, char **argv) "String[]"
%typemap(jstype) (int argc, char **argv) "String[]"

%typemap(javain) (int argc, char **argv) "$javainput"
</pre>
</div>

<p>
When writing a multiple-argument typemap, each of the types is referenced by a variable such 
as <tt>$1</tt> or <tt>$2</tt>.   The typemap code simply fills in the appropriate values from
the supplied Java parameter.
</p>

<p>
With the above typemap in place, you will find it no longer necessary
to supply the argument count.  This is automatically set by the typemap code.  For example:
</p>

<div class="code">
<pre>
example.foo(new String[]{"red", "green", "blue", "white"});
</pre>
</div>


<H3><a name="Java_using_typemaps_return_arguments">25.10.6 Using typemaps to return arguments</a></H3>


<p>
A common problem in some C programs is that values may be returned in function parameters rather than in the return value of a function. 
The <tt>typemaps.i</tt> file defines INPUT, OUTPUT and INOUT typemaps which can be used to solve some instances of this problem. 
This library file uses an array as a means of moving data to and from Java when wrapping a C function that takes non const pointers or non const references as parameters.
</p>
 
<p>
Now we are going to outline an alternative approach to using arrays for C pointers. 
The INOUT typemap uses a <tt>double[]</tt> array for receiving and returning the <tt>double*</tt> parameters. 
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.
</p>

<p>
Here is our example function:
</p>

<div class="code"><pre>
/* Returns a status value and two values in out1 and out2 */
int spam(double a, double b, double *out1, double *out2);
</pre></div>

<p>
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:
</p>

<div class="code"><pre>
%module example

/* Define a new structure to use instead of double * */
%inline %{
typedef struct {
    double value;
} MyDouble;
%}


%{
/* Returns a status value and two values in out1 and out2 */
int spam(double a, double b, double *out1, double *out2) {
  int status = 1;
  *out1 = a*10.0;
  *out2 = b*100.0;
  return status;
}
%}

/* 
This typemap will make any double * function parameters with name <tt>OUTVALUE</tt> take an
argument of MyDouble instead of double *. This will 
allow the calling function to read the double * value after returning from the function.
*/
%typemap(in) double *OUTVALUE {
    jclass clazz = jenv-&gt;FindClass("MyDouble");
    jfieldID fid = jenv-&gt;GetFieldID(clazz, "swigCPtr", "J");
    jlong cPtr = jenv-&gt;GetLongField($input, fid);
    MyDouble *pMyDouble = NULL;
    *(MyDouble **)&amp;pMyDouble = *(MyDouble **)&amp;cPtr;
    $1 = &amp;pMyDouble-&gt;value;
}

%typemap(jtype) double *OUTVALUE "MyDouble"
%typemap(jstype) double *OUTVALUE "MyDouble"
%typemap(jni) double *OUTVALUE "jobject"

%typemap(javain) double *OUTVALUE "$javainput"

/* Now we apply the typemap to the named variables */
%apply double *OUTVALUE { double *out1, double *out2 };
int spam(double a, double b, double *out1, double *out2);
</pre></div>

<p>
Note that the C++ JNI calling convention has been used this time and so must be compiled as C++ and the -c++ commandline must be passed to SWIG. 
JNI error checking has been omitted for clarity.
</p>

<p>
What the typemaps do are make the named <tt>double*</tt> function parameters use our new <tt>MyDouble</tt> wrapper structure. 
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. 
In Java, when the function returns, we use the SWIG created <tt>getValue()</tt> function to get the output value. 
The following Java program demonstrates this:
</p>

<div class="code"><pre>
// File: runme.java

public class runme {

  static {
    try {
      System.loadLibrary("example");
    } catch (UnsatisfiedLinkError e) {
      System.err.println("Native code library failed to load. " + e);
      System.exit(1);
    }
  }

  public static void main(String argv[]) {
    MyDouble out1 = new MyDouble();
    MyDouble out2 = new MyDouble();
    int ret = example.spam(1.2, 3.4, out1, out2);
    System.out.println(ret + "  " + out1.getValue() + "  " + out2.getValue());
  }
}
</pre></div>

<p>
When compiled and run we get:
</p>

<div class="code"><pre>
$ java runme
1 12.0  340.0
</pre></div>

<H3><a name="Java_adding_downcasts">25.10.7 Adding Java downcasts to polymorphic return types</a></H3>


<p>
SWIG support for polymorphism works in that the appropriate virtual function is called. However, the default generated code does not allow for downcasting. 
Let's examine this with the following code:
</p>

<div class="code"><pre>
%include "std_string.i"

#include &lt;iostream&gt;
using namespace std;
class Vehicle {
public:
    virtual void start() = 0;
...
};

class Ambulance : public Vehicle {
    string vol;
public:
    Ambulance(string volume) : vol(volume) {}
    virtual void start() {
        cout &lt;&lt; "Ambulance started" &lt;&lt; endl;
    }
    void sound_siren() {
        cout &lt;&lt; vol &lt;&lt; " siren sounded!" &lt;&lt; endl;
    }
...
};

Vehicle *vehicle_factory() {
    return new Ambulance("Very loud");
}
</pre></div>

<p>
If we execute the following Java code:
</p>

<div class="code"><pre>
Vehicle vehicle = example.vehicle_factory();
vehicle.start();

Ambulance ambulance = (Ambulance)vehicle;
ambulance.sound_siren();
</pre></div>

<p>
We get:
</p>

<div class="code"><pre>
Ambulance started
java.lang.ClassCastException
        at runme.main(runme.java:16)
</pre></div>

<p>
Even though we know from examination of the C++ code that <tt>vehicle_factory</tt> returns an object of type <tt>Ambulance</tt>, 
we are not able to use this knowledge to perform the downcast in Java.
This occurs because the runtime type information is not completely passed from C++ to Java when returning the type from <tt>vehicle_factory()</tt>.
Usually this is not a problem as virtual functions do work by default, such as in the case of <tt>start()</tt>. 
There are a few solutions to getting downcasts to work.
</p>

<p>
The first is not to use a Java cast but a call to C++ to make the cast. Add this to your code:
</p>

<div class="code"><pre>
%exception Ambulance::dynamic_cast(Vehicle *vehicle) {
    $action
    if (!result) {
        jclass excep = jenv-&gt;FindClass("java/lang/ClassCastException");
        if (excep) {
            jenv-&gt;ThrowNew(excep, "dynamic_cast exception");
        }
    }
}
%extend Ambulance {
    static Ambulance *dynamic_cast(Vehicle *vehicle) {
        return dynamic_cast&lt;Ambulance *&gt;(vehicle);
    }
};
</pre></div>

<p>
It would then be used from Java like this
</p>

<div class="code"><pre>
Ambulance ambulance = Ambulance.dynamic_cast(vehicle);
ambulance.sound_siren();
</pre></div>

<p>
Should <tt>vehicle</tt> not be of type <tt>ambulance</tt> then a Java <tt>ClassCastException</tt> is thrown.
The next solution is a purer solution in that Java downcasts can be performed on the types.
Add the following before the definition of <tt>vehicle_factory</tt>:
</p>

<div class="code"><pre>
%typemap(out) Vehicle * {
    Ambulance *downcast = dynamic_cast&lt;Ambulance *&gt;($1);
    *(Ambulance **)&amp;$result = downcast;
}

%typemap(javaout) Vehicle * {
    return new Ambulance($jnicall, $owner);
  }
</pre></div>

<p>
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>.
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.
Consider expanding our example with a new Vehicle type and a more flexible factory function:
</p>

<div class="code"><pre>
class FireEngine : public Vehicle {
public:
    FireEngine() {}
    virtual void start() {
        cout &lt;&lt; "FireEngine started" &lt;&lt; endl;
    }
    void roll_out_hose() {
        cout &lt;&lt; "Hose rolled out" &lt;&lt; endl;
    }
 ...
};
Vehicle *vehicle_factory(int vehicle_number) {
    if (vehicle_number == 0)
        return new Ambulance("Very loud");
    else
        return new FireEngine();
}
</pre></div>

<p>
To be able to downcast with this sort of Java code:
</p>

<div class="code"><pre>
FireEngine fireengine = (FireEngine)example.vehicle_factory(1);
fireengine.roll_out_hose();
Ambulance ambulance = (Ambulance)example.vehicle_factory(0);
ambulance.sound_siren();
</pre></div>

<p>
the following typemaps targeted at the <tt>vehicle_factory</tt> function will achieve this. 
Note that in this case, the Java class is constructed using JNI code rather than passing a pointer across the JNI boundary in a Java long for construction in Java code.
</p>

<div class="code"><pre>
%typemap(jni) Vehicle *vehicle_factory "jobject"
%typemap(jtype) Vehicle *vehicle_factory "Vehicle"
%typemap(jstype) Vehicle *vehicle_factory "Vehicle"
%typemap(javaout) Vehicle *vehicle_factory {
    return $jnicall;
  }

%typemap(out) Vehicle *vehicle_factory {
    Ambulance *ambulance = dynamic_cast&lt;Ambulance *&gt;($1);
    FireEngine *fireengine = dynamic_cast&lt;FireEngine *&gt;($1);
    if (ambulance) {
        // call the Ambulance(long cPtr, boolean cMemoryOwn) constructor
        jclass clazz = jenv-&gt;FindClass("Ambulance");
        if (clazz) {
            jmethodID mid = jenv-&gt;GetMethodID(clazz, "&lt;init&gt;", "(JZ)V");
            if (mid) {
                jlong cptr = 0;
                *(Ambulance **)&amp;cptr = ambulance; 
                $result = jenv-&gt;NewObject(clazz, mid, cptr, false);
            }
        }
    } else if (fireengine) {
        // call the FireEngine(long cPtr, boolean cMemoryOwn) constructor
        jclass clazz = jenv-&gt;FindClass("FireEngine");
        if (clazz) {
            jmethodID mid = jenv-&gt;GetMethodID(clazz, "&lt;init&gt;", "(JZ)V");
            if (mid) {
                jlong cptr = 0;
                *(FireEngine **)&amp;cptr = fireengine; 
                $result = jenv-&gt;NewObject(clazz, mid, cptr, false);
            }
        }
    }
    else {
        cout &lt;&lt; "Unexpected type " &lt;&lt; endl;
    }

    if (!$result)
        cout &lt;&lt; "Failed to create new java object" &lt;&lt; endl;
}
</pre></div>

<p>
Better error handling would need to be added into this code. 
There are other solutions to this problem, but this last example demonstrates some more involved JNI code.
SWIG usually generates code which constructs the proxy classes using Java code as it is easier to handle error conditions and is faster. 
Note that the JNI code above uses a number of string lookups to call a constructor, whereas this would not occur using byte compiled Java code.
</p>

<H3><a name="Java_adding_equals_method">25.10.8 Adding an equals method to the Java classes</a></H3>


<p>
When a pointer is returned from a JNI function, it is wrapped using a new Java proxy class or type wrapper class. 
Even when the pointers are the same, it will not be possible to know that the two Java classes containing those pointers are actually the same object.
It is common in Java to use the <tt>equals()</tt> method to check whether two objects are equivalent.
The <tt>equals()</tt> method is usually accompanied by a <tt>hashCode()</tt> method in order to fulfill
the requirement that the hash code is equal for equal objects.
Pure Java code methods like these can be easily added:
</p>

<div class="code">
<pre>
%typemap(javacode) SWIGTYPE %{
  public boolean equals(Object obj) {
    boolean equal = false;
    if (obj instanceof $javaclassname)
      equal = ((($javaclassname)obj).swigCPtr == this.swigCPtr);
    return equal;
  }
  public int hashCode() {
     return (int)getPointer();
  }
%}

class Foo { };
Foo* returnFoo(Foo *foo) { return foo; }
</pre>
</div>

<p>
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>.
</p>

<div class="code">
<pre>
Foo foo1 = new Foo();
Foo foo2 = example.returnFoo(foo1);
System.out.println("foo1? " + foo1.equals(foo2));
</pre>
</div>


<H3><a name="Java_void_pointers">25.10.9 Void pointers and a common Java base class</a></H3>


<p>
One might wonder why the common code that SWIG emits for the proxy and type wrapper classes is not pushed into a base class. 
The reason is that although <tt>swigCPtr</tt> could be put into a common base class for all classes 
wrapping C structures, it would not work for C++ classes involved in an inheritance chain.
Each class derived from a base needs a separate <tt>swigCPtr</tt> because C++ compilers sometimes use a different pointer value when casting a derived class to a base.
Additionally as Java only supports single inheritance, it would not be possible to derive wrapped classes from your own pure Java classes if the base class has been 'used up' by SWIG.
However, you may want to move some of the common code into a base class. 
Here is an example which uses a common base class for all proxy classes and type wrapper classes:
</p>

<div class="code">
<pre>
%typemap(javabase) SWIGTYPE, SWIGTYPE *, SWIGTYPE &amp;, SWIGTYPE [], 
                                                         SWIGTYPE (CLASS::*) "SWIG"

%typemap(javacode) SWIGTYPE, SWIGTYPE *, SWIGTYPE &amp;, SWIGTYPE [], 
                                                         SWIGTYPE (CLASS::*) %{
  protected long getPointer() {
    return swigCPtr;
  }
%}
</pre>
</div>

<p>
Define new base class called SWIG:
</p>

<div class="code">
<pre>
public abstract class SWIG {
  protected abstract long getPointer();

  public boolean equals(Object obj) {
    boolean equal = false;
    if (obj instanceof SWIG)
      equal = (((SWIG)obj).getPointer() == this.getPointer());
    return equal;
  }
  
  SWIGTYPE_p_void getVoidPointer() {
    return new SWIGTYPE_p_void(getPointer(), false);
  }
}
</pre>
</div>

<p>
This example contains some useful functionality which you may want in your code. 
</p>

<ul>
    <li> It has an <tt>equals()</tt> method. Unlike the previous example, the method code isn't replicated in all classes.
    <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.
</ul>

<H3><a name="Java_struct_pointer_pointer">25.10.10 Struct pointer to pointer</a></H3>


<p>
Pointers to pointers are often used as output parameters in C factory type functions.
These are a bit more tricky to handle.
Consider the following situation where a <tt>Butler</tt> can be hired and fired:
</p>

<div class="code">
<pre>
typedef struct {
  int hoursAvailable;
  char *greeting;
} Butler;

// Note: HireButler will allocate the memory 
// The caller must free the memory by calling FireButler()!!
extern int HireButler(Butler **ppButler);
extern void FireButler(Butler *pButler);
</pre>
</div>

<p>
C code implementation:
</p>

<div class="code">
<pre>
int HireButler(Butler **ppButler) {
  Butler *pButler = (Butler *)malloc(sizeof(Butler));
  pButler-&gt;hoursAvailable = 24;
  pButler-&gt;greeting = (char *)malloc(32);
  strcpy(pButler-&gt;greeting, "At your service Sir");
  *ppButler = pButler;
  return 1;
}
void FireButler(Butler *pButler) {
  free(pButler-&gt;greeting);
  free(pButler);
}
</pre>
</div>

<p>
Let's take two approaches to wrapping this code.
The first is to provide a functional interface, much like the original C interface.
The following Java code shows how we intend the code to be used:
</p>

<div class="code">
<pre>
    Butler jeeves = new Butler();
    example.HireButler(jeeves);
    System.out.println("Greeting:     " + jeeves.getGreeting());
    System.out.println("Availability: " + jeeves.getHoursAvailable() + " hours per day");
    example.FireButler(jeeves);
</pre>
</div>

<p>
Resulting in the following output when run:
</p>

<div class="shell">
<pre>
Greeting:     At your service Sir
Availability: 24 hours per day
</pre>
</div>

<p>
Note the usage is very much like it would be used if we were writing C code, that is, explicit memory management is needed.
No C memory is allocated in the construction of the <tt>Butler</tt> proxy class and 
the proxy class will not destroy the underlying C memory when it is collected.
A number of typemaps and features are needed to implement this approach. 
The following interface file code should be placed before SWIG parses the above C code.
</p>

<div class="code">
<pre>
%module example

// Do not generate the default proxy constructor or destructor
%nodefaultctor Butler;
%nodefaultdtor Butler;

// Add in pure Java code proxy constructor
%typemap(javacode) Butler %{
  /** This constructor creates the proxy which initially does not create nor own any C memory */
  public Butler() {
    this(0, false);
  }
%}

// Type typemaps for marshalling Butler **
%typemap(jni) Butler ** "jobject"
%typemap(jtype) Butler ** "Butler"
%typemap(jstype) Butler ** "Butler"

// Typemaps for Butler ** as a parameter output type
%typemap(in) Butler ** (Butler *ppButler = 0) %{
  $1 = &amp;ppButler;
%}
%typemap(argout) Butler ** {
  // Give Java proxy the C pointer (of newly created object)
  jclass clazz = (*jenv)-&gt;FindClass(jenv, "Butler");
  jfieldID fid = (*jenv)-&gt;GetFieldID(jenv, clazz, "swigCPtr", "J");
  jlong cPtr = 0;
  *(Butler **)&amp;cPtr = *$1;
  (*jenv)-&gt;SetLongField(jenv, $input, fid, cPtr);
}
%typemap(javain) Butler ** "$javainput"
</pre>
</div>

<p>
Note that the JNI code sets the proxy's <tt>swigCPtr</tt> member variable to point to the newly created object.
The <tt>swigCMemOwn</tt> remains unchanged (at false), so that the proxy does not own the memory.
</p>

<p>
Note: The old %nodefault directive disabled the default constructor
and destructor at the same time. This is unsafe in most of the cases,
and you can use the explicit %nodefaultctor and %nodefaultdtor
directives to achieve the same result if needed.
</p>

<p>
The second approach offers a more object oriented interface to the Java user.
We do this by making the Java proxy class's
constructor call the <tt>HireButler()</tt> method to create the underlying C object.
Additionally we get the proxy to take ownership of the memory so that the
finalizer will call the <tt>FireButler()</tt> function.
The proxy class will thus take ownership of the memory and clean it up when no longer needed.
We will also prevent the user from being able to explicitly call the <tt>HireButler()</tt> and <tt>FireButler()</tt> functions.
Usage from Java will simply be:
</p>

<div class="code">
<pre>
Butler jeeves = new Butler();
System.out.println("Greeting:     " + jeeves.getGreeting());
System.out.println("Availability: " + jeeves.getHoursAvailable() + " hours per day");
</pre>
</div>

<p>
Note that the Butler class is used just like any other Java class and no extra coding by the user needs to be written to 
clear up the underlying C memory as the finalizer will be called by the garbage collector which in turn will call the <tt>FireButler()</tt> function.
To implement this, we use the above interface file code but remove the <tt>javacode</tt> typemap and add the following:
</p>

<div class="code">
<pre>
// Don't expose the memory allocation/de-allocation functions
%ignore FireButler(Butler *pButler);
%ignore HireButler(Butler **ppButler);

// Add in a custom proxy constructor and destructor
%extend Butler {
  Butler() {
    Butler *pButler = 0;
    HireButler(&amp;pButler);
    return pButler;
  }
  ~Butler() {
     FireButler($self);
   }
}
</pre>
</div>

<p>
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,
see <a href="SWIG.html#SWIG_adding_member_functions">Adding member functions to C structures</a>.
The C functional interface has been completely morphed into an object-oriented interface and
the Butler class would behave much like any pure Java class and feel more natural to Java users.
</p>

<H3><a name="Java_memory_management_member_variables">25.10.11 Memory management when returning references to member variables</a></H3>


<p>
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.
</p>

<p>
Consider the following C++ code:
</p>

<div class="code">
<pre>
struct Wheel {
  int size;
  Wheel(int sz) : size(sz) {}
};

class Bike {
  Wheel wheel;
public:
  Bike(int val) : wheel(val) {}
  Wheel&amp; getWheel() { return wheel; }
};
</pre>
</div>

<p>
and the following usage from Java after running the code through SWIG:
</p>


<div class="code">
<pre>
    Wheel wheel = new Bike(10).getWheel();
    System.out.println("wheel size: " + wheel.getSize());
    // Simulate a garbage collection
    System.gc();
    System.runFinalization();
    System.out.println("wheel size: " + wheel.getSize());
</pre>
</div>

<p>
Don't be surprised that if the resulting output gives strange results such as...
</p>

<div class="shell">
<pre>
wheel size: 10
wheel size: 135019664
</pre>
</div>

<p>
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.
The proxy instance, <tt>wheel</tt>, contains a reference to memory that was deleted when the <tt>Bike</tt> instance was collected.
In order to prevent the garbage collector from collecting the <tt>Bike</tt> instance a reference to the <tt>Bike</tt> must
be added to the <tt>wheel</tt> instance. You can do this by adding the reference when the <tt>getWheel()</tt> method
is called using the following typemaps.
</p>


<div class="code">
<pre>
%typemap(javacode) Wheel %{
  // Ensure that the GC doesn't collect any Bike instance set from Java
  private Bike bikeReference;
  protected void addReference(Bike bike) {
    bikeReference = bike;
  }
%}

// Add a Java reference to prevent premature garbage collection and resulting use
// of dangling C++ pointer. Intended for methods that return pointers or
// references to a member variable.
%typemap(javaout) Wheel&amp; getWheel {
    long cPtr = $jnicall;
    $javaclassname ret = null;
    if (cPtr != 0) {
      ret = new $javaclassname(cPtr, $owner);
      ret.addReference(this);
    }
    return ret;
  }
</pre>
</div>

<p>
The code in the first typemap gets added to the <tt>Wheel</tt> proxy class.
The code in the second typemap constitutes the bulk of the code in the generated <tt>getWheel()</tt> function:
</p>

<div class="code">
<pre>
public class Wheel {
  ...
  // Ensure that the GC doesn't collect any bike set from Java 
  private Bike bikeReference;
  protected void addReference(Bike bike) {
    bikeReference = bike;
  }
}

public class Bike {
  ...
  public Wheel getWheel() {
    long cPtr = exampleJNI.Bike_getWheel(swigCPtr, this);
    Wheel ret = null;
    if (cPtr != 0) {
      ret = new Wheel(cPtr, false);
      ret.addReference(this);
    }
    return ret;
  }
}
</pre>
</div>

<p>
Note the <tt>addReference</tt> call.
</p>

<H3><a name="Java_memory_management_objects">25.10.12 Memory management for objects passed to the C++ layer</a></H3>


<p>
Managing memory can be tricky when using C++ and Java proxy classes.
The previous example shows one such case and this example looks at memory management for a class passed to a C++ method which expects the object to remain in scope
after the function has returned. Consider the following two C++ classes:
</p>

<div class="code">
<pre>
struct Element {
  int value;
  Element(int val) : value(val) {}
};
class Container {
  Element* element;
public:
  Container() : element(0) {}
  void setElement(Element* e) { element = e; }
  Element* getElement() { return element; }
};
</pre>
</div>

<p>
and usage from C++
</p>

<div class="code">
<pre>
    Container container;
    Element element(20);
    container.setElement(&amp;element);
    cout &lt;&lt; "element.value: " &lt;&lt; container.getElement()-&gt;value &lt;&lt; endl;
</pre>
</div>

<p>
and more or less equivalent usage from Java
</p>

<div class="code">
<pre>
    Container container = new Container();
    container.setElement(new Element(20));
    System.out.println("element value: " + container.getElement().getValue());
</pre>
</div>

<p>
The C++ code will always print out 20, but the value printed out may not be this in the Java equivalent code.
In order to understand why, consider a garbage collection occuring...
</p>

<div class="code">
<pre>
    Container container = new Container();
    container.setElement(new Element(20));
    // Simulate a garbage collection
    System.gc();
    System.runFinalization();
    System.out.println("element value: " + container.getElement().getValue());
</pre>
</div>

<p>
The temporary element created with <tt>new Element(20)</tt> could get garbage collected
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.
One solution is to add in the appropriate references in the Java layer...
</p>

<div class="code">
<pre>
public class Container {

  ...

  // Ensure that the GC doesn't collect any Element set from Java
  // as the underlying C++ class stores a shallow copy
  private Element elementReference;
  private long getCPtrAndAddReference(Element element) {
    elementReference = element;
    return Element.getCPtr(element);
  }

  public void setElement(Element e) {
    exampleJNI.Container_setElement(swigCPtr, this, getCPtrAndAddReference(e), e);
  }
}
</pre>
</div>

<p>
The following typemaps will generate the desired code.
The 'javain' typemap matches the input parameter type for the <tt>setElement</tt> method.
The 'javacode' typemap simply adds in the specified code into the Java proxy class.
</p>

<div class="code">
<pre>
%typemap(javain) Element *e "getCPtrAndAddReference($javainput)"

%typemap(javacode) Container %{
  // Ensure that the GC doesn't collect any element set from Java
  // as the underlying C++ class stores a shallow copy
  private Element elementReference;
  private long getCPtrAndAddReference(Element element) {
    elementReference = element;
    return Element.getCPtr(element);
  }
%}
</pre>
</div>


<H3><a name="Java_date_marshalling">25.10.13 Date marshalling using the javain typemap and associated attributes</a></H3>


<p>
The <a href="#Java_nan_exception_typemap">NaN Exception example</a> is a simple example of the "javain" typemap and its 'pre' attribute.
This example demonstrates how a C++ date class, say <tt>CDate</tt>, can be mapped onto the standard Java date class,
<tt>java.util.GregorianCalendar</tt> by using the 'pre', 'post' and 'pgcppname' attributes of the "javain" typemap.
The idea is that the <tt>GregorianCalendar</tt> is used wherever the C++ API uses a <tt>CDate</tt>.
Let's assume the code being wrapped is as follows:
</p>

<div class="code">
<pre>
class CDate {
public:
  CDate(int year, int month, int day);
  int getYear();
  int getMonth();
  int getDay();
  ...
};
struct Action {
  static int doSomething(const CDate &amp;dateIn, CDate &amp;dateOut);
  Action(const CDate &amp;date, CDate &amp;dateOut);
};
</pre>
</div>

<p>
Note that <tt>dateIn</tt> is const and therefore read only and <tt>dateOut</tt> is a non-const output type.
</p>

<p>
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:
</p>

<div class="code">
<pre>
public class Action {
  ...
  public static int doSomething(CDate dateIn, CDate dateOut) {
    return exampleJNI.Action_doSomething(CDate.getCPtr(dateIn), dateIn, 
                                         CDate.getCPtr(dateOut), dateOut);
  }

  public Action(CDate date, CDate dateOut) {
    this(exampleJNI.new_Action(CDate.getCPtr(date), date, 
                               CDate.getCPtr(dateOut), dateOut), true);
  }
}
</pre>
</div>

<p>
The <tt>CDate &amp;</tt> and <tt>const CDate &amp;</tt> Java code is generated from the following two default typemaps:
</p>

<div class="code">
<pre>
%typemap(jstype) SWIGTYPE &amp; "$javaclassname"
%typemap(javain) SWIGTYPE &amp; "$javaclassname.getCPtr($javainput)"
</pre>
</div>

<p>
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>.
From Java, the intention is then to call into a modifed API with something like:
</p>

<div class="code">
<pre>
java.util.GregorianCalendar calendarIn = 
    new java.util.GregorianCalendar(2011, java.util.Calendar.APRIL, 13, 0, 0, 0);
java.util.GregorianCalendar calendarOut = new java.util.GregorianCalendar();

// Note in calls below, calendarIn remains unchanged and calendarOut 
// is set to a new value by the C++ call
Action.doSomething(calendarIn, calendarOut);
Action action = new Action(calendarIn, calendarOut);
</pre>
</div>

<p>
To achieve this mapping, we need to alter the default code generation slightly so that at the Java layer, 
a <tt>GregorianCalendar</tt> is converted into a <tt>CDate</tt>. 
The JNI intermediary layer will still take a pointer to the underlying <tt>CDate</tt> class.
The typemaps to achieve this are shown below.
</p>

<div class="code">
<pre>
%typemap(jstype) const CDate&amp; "java.util.GregorianCalendar"
%typemap(javain, 
         pre="    CDate temp$javainput = new CDate($javainput.get(java.util.Calendar.YEAR), "
             "$javainput.get(java.util.Calendar.MONTH), $javainput.get(java.util.Calendar.DATE));", 
         pgcppname="temp$javainput") const CDate &amp;
         "$javaclassname.getCPtr(temp$javainput)"

%typemap(jstype) CDate&amp; "java.util.Calendar"
%typemap(javain, 
         pre="    CDate temp$javainput = new CDate($javainput.get(java.util.Calendar.YEAR), "
             "$javainput.get(java.util.Calendar.MONTH), $javainput.get(java.util.Calendar.DATE));", 
         post="      $javainput.set(temp$javainput.getYear(), temp$javainput.getMonth(), "
              "temp$javainput.getDay(), 0, 0, 0);", 
         pgcppname="temp$javainput") CDate &amp;
         "$javaclassname.getCPtr(temp$javainput)"
</pre>
</div>

<p>
The resulting generated proxy code in the <tt>Action</tt> class follows:
 </p>

<div class="code">
<pre>
public class Action {
  ...
  public static int doSomething(java.util.GregorianCalendar dateIn, 
                                java.util.Calendar dateOut) {
    CDate tempdateIn = new CDate(dateIn.get(java.util.Calendar.YEAR), 
                                 dateIn.get(java.util.Calendar.MONTH), 
                                 dateIn.get(java.util.Calendar.DATE));
    CDate tempdateOut = new CDate(dateOut.get(java.util.Calendar.YEAR), 
                                  dateOut.get(java.util.Calendar.MONTH), 
                                  dateOut.get(java.util.Calendar.DATE));
    try {
      return exampleJNI.Action_doSomething(CDate.getCPtr(tempdateIn), tempdateIn, 
                                           CDate.getCPtr(tempdateOut), tempdateOut);
    } finally {
      dateOut.set(tempdateOut.getYear(), tempdateOut.getMonth(), tempdateOut.getDay(), 0, 0, 0);
    }
  }

  static private long SwigConstructAction(java.util.GregorianCalendar date, 
                                          java.util.Calendar dateOut) {
    CDate tempdate = new CDate(date.get(java.util.Calendar.YEAR), 
                               date.get(java.util.Calendar.MONTH), 
                               date.get(java.util.Calendar.DATE));
    CDate tempdateOut = new CDate(dateOut.get(java.util.Calendar.YEAR), 
                                  dateOut.get(java.util.Calendar.MONTH), 
                                  dateOut.get(java.util.Calendar.DATE));
    try {
      return exampleJNI.new_Action(CDate.getCPtr(tempdate), tempdate, 
                                   CDate.getCPtr(tempdateOut), tempdateOut);
    } finally {
      dateOut.set(tempdateOut.getYear(), tempdateOut.getMonth(), tempdateOut.getDay(), 0, 0, 0);
    }
  }

  public Action(java.util.GregorianCalendar date, java.util.Calendar dateOut) {
    this(Action.SwigConstructAction(date, dateOut), true);
  }
}
</pre>
</div>

<p>
A few things to note:
</p>
<ul>
  <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.
  <li> The code in the 'pre' attribute appears before the JNI call (<tt>exampleJNI.new_Action</tt> / <tt>exampleJNI.Action_doSomething</tt>).
  <li> The code in the 'post' attribute appears after the JNI call.
  <li> A try .. finally block is generated with the JNI call in the try block and 'post' code in the finally block.
  The alternative of just using a temporary variable for the return value from the JNI call and the 'post' code being generated before the
  return statement is not possible given that the JNI call is in one line and comes from the "javaout" typemap.
  <li> The temporary variables in the "javain" typemaps are called <tt>temp$javain</tt>, where "$javain" is replaced with the parameter name.
  "$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 
  more local variables with the same name would be generated.
  <li> The use of the "javain" typemap causes a constructor helper function (<tt>SwigConstructAction</tt>) to be generated.
  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.
  <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).
</ul>




<H2><a name="Java_directors_faq">25.11 Living with Java Directors</a></H2>


<p>
  This section is intended to address frequently asked questions and frequently encountered problems when using Java directors.
</p>

<ol>
  <li><i>When my program starts up, it complains that </i>method_foo<i> cannot
  be found in a Java method called </i>swig_module_init<i>. How do I fix
  this?</i>

  <p>
  Open up the C++ wrapper source code file and look for <code>"method_foo"</code> (include the double quotes, they are important!)
  Look at the JNI field descriptor and make sure that each class that occurs in the descriptor has the correct package name in front of it.
  If the package name is incorrect, put a "javapackage" typemap in your SWIG interface file.
  </p>
  </li>

  <li><i>I'm compiling my code and I'm using templates. I provided a
  javapackage typemap, but SWIG doesn't generate the right JNI field
  descriptor.</i>
  <p>
  Use the template's renamed name as the argument to the "javapackage" typemap:
  </p>
<div class="code">
<pre>
%typemap(javapackage)  std::vector&lt;int&gt;  "your.package.here"
%template(VectorOfInt) std::vector&lt;int&gt;;
</pre>
</div>
  </li>

  <li><p><i>When I pass class pointers or references through a C++ upcall and I
  try to type cast them, Java complains with a ClassCastException. What am I
  doing wrong?</i></p>
  <p>
  Normally, a non-director generated Java proxy class creates temporary Java objects as follows:
  </p>
<div class="code">
<pre>
public static void MyClass_method_upcall(MyClass self, long jarg1)
{
  Foo darg1 = new Foo(jarg1, false);

  self.method_upcall(darg1);
}
</pre>
</div>
  <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.
  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.
  Thus, for director-enabled classes <b>and only for director-enabled classes</b>, the generated proxy Java code looks something like:
  </p>

<div class="code">
<pre>
public static void MyClass_method_upcall(MyClass self, long jarg1,
                                         Foo jarg1_object)
{
  Foo darg1 = (jarg1_object != null ? jarg1_object : new Foo(jarg1, false));

  self.method_upcall(darg1);
}
</pre>
</div>

  <p>
  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.
  This applies even when the class being wrapped isn't a director-enabled class but takes parameters that are director-enabled classes.
  </p>

  <p>
  The current "type symmetry" design will work for simple C++ inheritance, but will most likely fail for anything more complicated such as tree or diamond C++ inheritance hierarchies.
  Those who are interested in challenging problems are more than welcome to hack the <code>Java::Java_director_declaration</code> method in <code>Source/Modules/java.cxx</code>.
  </p>
  <p>
  If all else fails, you can use the downcastXXXXX() method to attempt to recover the director class's Java object pointer.
  For the Java Foo proxy class, the Foo director class's java object pointer can be accessed through the javaObjectFoo() method.
  The generated method's signature is:
  </p>

<div class="code">
<pre>
  public static Foo javaObjectFoo(Foo obj);
</pre>
</div>

<p>
  From your code, this method is invoked as follows:
</p>

<div class="code">
<pre>
public class MyClassDerived {
  public void method_upcall(Foo foo_object)
  {
    FooDerived    derived = (foo_object != null ?
                 (FooDerived) Foo.downcastFoo(foo_object) : null);
    /* rest of your code here */
  }
}
</pre>
</div>

<p>
  An good approach for managing downcasting is placing a static method in each derived class that performs the downcast from the superclass, e.g.,
</p>

<div class="code">
<pre>
public class FooDerived extends Foo {
  /* ... */
  public static FooDerived downcastFooDerived(Foo foo_object)
  {
    try {
     return (foo_object != null ? (FooDerived) Foo.downcastFoo(foo_object);
    }

    catch (ClassCastException exc) {
      // Wasn't a FooDerived object, some other subclass of Foo
      return null;
    }
  }
}
</pre>
</div>

<p>
  Then change the code in MyClassDerived as follows:
</p>

<div class="code">
<pre>
public class MyClassDerived extends MyClass {
  /* ... */
  public void method_upcall(Foo foo_object)
  {
    FooDerived    derived = FooDerived.downcastFooDerived(foo_object);
    /* rest of your code here */
  }
}
</pre>
</div>
  </li>

  <li><p><i>Why isn't the proxy class declared abstract? Why aren't the director
  upcall methods in the proxy class declared abstract?</i></p>

  <p>
  Declaring the proxy class and its methods abstract would break the JNI argument marshalling and SWIG's downcall functionality (going from Java to C++.)
  Create an abstract Java subclass that inherits from the director-enabled class instead.
  Using the previous Foo class example:
  </p>

<div class="code">
<pre>
public abstract class UserVisibleFoo extends Foo {
  /** Make sure user overrides this method, it's where the upcall
   * happens.
   */
  public abstract void method_upcall(Foo foo_object);

  /// Downcast from Foo to UserVisibleFoo
  public static UserVisibleFoo downcastUserVisibleFoo(Foo foo_object)
  {
    try {
     return (foo_object != null ? (FooDerived) Foo.downcastFoo(foo_object) : null);
    }

    catch (ClassCastException exc) {
      // Wasn't a FooDerived object, some other subclass of Foo
      return null;
    }
  }
}
</pre>
</div>
  <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>
  </li>
</ol>

<H2><a name="Java_odds_ends">25.12 Odds and ends</a></H2>


<H3><a name="Java_javadoc_comments">25.12.1 JavaDoc comments</a></H3>


<p>
The SWIG documentation system is currently deprecated. 
When it is resurrected JavaDoc comments will be fully supported. 
If you can't wait for the full documentation system a couple of workarounds are available. 
The <tt>%javamethodmodifiers</tt> feature can be used for adding proxy class method comments and module class method comments. 
The "javaimports" typemap can be hijacked for adding in proxy class JavaDoc comments. 
The <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. 
Here is an example adding in a proxy class and method comment:
</p>

<div class="code">
<pre>
%javamethodmodifiers Barmy::lose_marbles() "
  /**
    * Calling this method will make you mad.
    * Use with &lt;b&gt;utmost&lt;/b&gt; caution. 
    */
  public";

%typemap(javaimports) Barmy "
/** The crazy class. Use as a last resort. */"

class Barmy {
public:
  void lose_marbles() {}
};
</pre>
</div>

<p>
Note the "public" added at the end of the <tt>%javamethodmodifiers</tt> as this is the default for this feature. 
The generated proxy class with JavaDoc comments is then as follows:
</p>

<div class="code">
<pre>
/** The crazy class. Use as a last resort. */
public class Barmy {
...
  /**
    * Calling this method will make you mad.
    * Use with &lt;b&gt;utmost&lt;/b&gt; caution. 
    */
  public void lose_marbles() {
    ...
  }
...
}
</pre>
</div>



<H3><a name="Java_functional_interface">25.12.2 Functional interface without proxy classes</a></H3>


<p>
It is possible to run SWIG in a mode that does not produce proxy classes by using the -noproxy commandline option.
The interface is rather primitive when wrapping structures or classes and is accessed through function calls to the module class.
All the functions in the module class are wrapped by functions with identical names as those in the intermediary JNI class.
</p>

<p>
Consider the example we looked at when examining proxy classes:
</p>

<div class="code">
<pre>
class Foo {
public:
     int x;
     int spam(int num, Foo* foo);
};
</pre>
</div>

<p>
When using <tt>-noproxy</tt>, type wrapper classes are generated instead of proxy classes.
Access to all the functions and variables is through a C like set of functions where the first parameter passed is the pointer to the class, that is an instance of a type wrapper class.
Here is what the module class looks like:
</p>

<div class="code">
<pre>
public class example {
  public static void Foo_x_get(SWIGTYPE_p_Foo self, int x) {...}
  public static int Foo_x_get(SWIGTYPE_p_Foo self) {...}
  public static int Foo_spam(SWIGTYPE_p_Foo self, int num, SWIGTYPE_p_Foo foo) {...}
  public static SWIGTYPE_p_Foo new_Foo() {...}
  public static void delete_Foo(SWIGTYPE_p_Foo self) {...}
}
</pre>
</div>

<p>
This approach is not nearly as natural as using proxy classes as the functions need to be used like this:
</p>

<div class="code">
<pre>
SWIGTYPE_p_Foo foo = example.new_Foo();
example.Foo_x_set(foo, 10);
int var = example.Foo_x_get(foo);
example.Foo_spam(foo, 20, foo);
example.delete_Foo(foo);
</pre>
</div>

<p>
Unlike proxy classes, there is no attempt at tracking memory.
All destructors have to be called manually for example the <tt>delete_Foo(foo)</tt> call above.
</p>


<H3><a name="Java_using_own_jni_functions">25.12.3 Using your own JNI functions</a></H3>


<p>
You may have some hand written JNI functions that you want to use in addition to the SWIG generated JNI functions.
Adding these to your SWIG generated package is possible using the <tt>%native</tt> directive.
If you don't want SWIG to wrap your JNI function then of course you can simply use the <tt>%ignore</tt> directive.
However, if you want SWIG to generate just the Java code for a JNI function then use the <tt>%native</tt> directive.
The C types for the parameters and return type must be specified in place of the JNI types and the function name must be the native method name.
For example:
</p>

<div class="code"><pre>
%native (HandRolled) void HandRolled(int, char *);
%{
JNIEXPORT void JNICALL Java_packageName_moduleName_HandRolled(JNIEnv *, jclass,
                                                              jlong, jstring);
%}
</pre></div>

<p>
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:
</p>

<div class="code"><pre>
  public final static native void HandRolled(int jarg1, String jarg2);
</pre></div>

<p>
and as usual this function is wrapped by another which for a global C function would appear in the module class:
</p>

<div class="code"><pre>
  public static void HandRolled(int arg0, String arg1) {
    exampleJNI.HandRolled(arg0, arg1);
  }
</pre></div>

<p>
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.
You may have to add in some "jtype", "jstype", "javain" and "javaout" typemaps when wrapping some JNI types.
Here the default typemaps work for <tt>int</tt> and <tt>char *</tt>.
</p>

<p>
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.
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.
</p>


<H3><a name="Java_performance">25.12.4 Performance concerns and hints</a></H3>


<p>
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>.
Try and minimise the expensive JNI calls to C/C++ functions, perhaps by using temporary Java variables instead of accessing the information directly from the C/C++ object.
</p>

<p>
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: 
</p>

<div class="code"><pre>
%typemap(javafinalize) SWIGTYPE ""
</pre></div>

<p>
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. 
This method normally calls the C++ destructor or <tt>free()</tt> for C code.
</p>

<H3><a name="Java_debugging">25.12.5 Debugging</a></H3>


<p>
The generated code can be debugged using both a Java debugger and a C++ debugger using the usual debugging techniques.
Breakpoints can be set in either Java or C++ code and so both can be debugged simultaneously.
Most debuggers do not understand both Java and C++, with one noteable exception of Sun Studio, 
where it is possible to step from Java code into a JNI method within one environment.
</p>

<p>
Alternatively, debugging can involve placing debug printout statements in the JNI layer using the <tt>%exception</tt> directive.
See the <a href="Customization.html#Customization_exception_special_variables">special variables for %exception</a> section.
Many of the default typemaps can also be overridden and modified for adding in extra logging/debug display information.
</p>

<p>
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.
The -verbose:jni and -verbose:gc are also useful options for monitoring code behaviour.
</p>


<H2><a name="Java_examples">25.13 Java Examples</a></H2>


<p>
The directory Examples/java has a number of further examples. 
Take a look at these if you want to see some of the techniques described in action.
The Examples/index.html file in the parent directory contains the SWIG Examples Documentation and is a useful starting point. 
If your SWIG installation went well Unix users should be able to type <tt>make</tt> in each example directory, then <tt>java main</tt> to see them running.
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>.
There are also many regression tests in the Examples/test-suite directory.
Many of these have runtime tests in the java subdirectory.
</p>

</body>
</html>