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

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
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>SWIG and Java</title>
</head>
<body bgcolor="#FFFFFF">
<a name="n1"></a><H1>17 SWIG and Java</H1>
<!-- INDEX -->
<ul>
<li><a href="#n2">Overview</a>
<li><a href="#n3">Preliminaries</a>
<ul>
<li><a href="#n4">Running SWIG</a>
<li><a href="#n5">Additional Commandline Options</a>
<li><a href="#n6">Getting the right header files</a>
<li><a href="#n7">Compiling a dynamic module</a>
<li><a href="#n8">Using your module</a>
<li><a href="#n9">Dynamic linking problems</a>
<li><a href="#n10">Compilation problems and compiling with C++</a>
<li><a href="#n11">Building on Windows</a>
<ul>
<li><a href="#n12">Running SWIG from Visual Studio</a>
<li><a href="#n13">Using NMAKE</a>
</ul>
</ul>
<li><a href="#n14">A tour of basic C/C++ wrapping</a>
<ul>
<li><a href="#n15">Modules, packages and generated Java classes</a>
<li><a href="#n16">Functions</a>
<li><a href="#n17">Global variables</a>
<li><a href="#n18">Constants</a>
<li><a href="#n19">Enumerations</a>
<li><a href="#n20">Pointers</a>
<li><a href="#n21">Structures</a>
<li><a href="#n22">C++ classes</a>
<li><a href="#n23">C++ inheritance</a>
<li><a href="#n24">Pointers, references, arrays and pass by value</a>
<ul>
<li><a href="#n25">Null pointers</a>
</ul>
<li><a href="#n26">C++ overloaded functions</a>
<li><a href="#n27">C++ namespaces</a>
<li><a href="#n28">C++ templates</a>
<li><a href="#n29">C++ Smart Pointers</a>
</ul>
<li><a href="#n30">Further details on the generated Java classes</a>
<ul>
<li><a href="#n31">The intermediary JNI class</a>
<ul>
<li><a href="#n32">The intermediary JNI class pragmas</a>
</ul>
<li><a href="#n33">The Java module class</a>
<ul>
<li><a href="#n34">The Java module class pragmas</a>
</ul>
<li><a href="#n35">Java proxy classes</a>
<ul>
<li><a href="#n36">Memory management</a>
<li><a href="#n37">Inheritance</a>
<li><a href="#n38">Proxy classes and garbage collection</a>
</ul>
<li><a href="#n39">Type wrapper classes</a>
</ul>
<li><a href="#n40">Cross language polymorphism using directors (experimental)</a>
<ul>
<li><a href="#n41">Enabling directors</a>
<li><a href="#n42">Director classes</a>
<li><a href="#n43">Overhead and code bloat</a>
<li><a href="#n44">Simple directors example</a>
</ul>
<li><a href="#n45">Common customization features</a>
<ul>
<li><a href="#n46">C/C++ helper functions</a>
<li><a href="#n47">Class extension with %extend</a>
<li><a href="#n48">Exception handling with %exception</a>
<li><a href="#n49">Method access with %javamethodmodifiers</a>
</ul>
<li><a href="#n50">Tips and techniques</a>
<ul>
<li><a href="#n51">Input and output parameters using primitive pointers and references</a>
<li><a href="#n52">Simple pointers</a>
<li><a href="#n53">Wrapping C arrays with Java arrays</a>
<li><a href="#n54">Unbounded C Arrays</a>
</ul>
<li><a href="#n55">Java typemaps</a>
<ul>
<li><a href="#n56">Default primitive type mappings</a>
<li><a href="#n57">Sixty four bit JVMs</a>
<li><a href="#n58">What is a typemap?</a>
<li><a href="#n59">Typemaps for mapping C/C++ types to Java types</a>
<li><a href="#n60">Java special variables</a>
<li><a href="#n61">Typemaps for both C and C++ compilation</a>
<li><a href="#n62">Java code typemaps</a>
<li><a href="#n63">Director specific typemaps</a>
</ul>
<li><a href="#n64">Typemap Examples</a>
<ul>
<li><a href="#n65">Converting Java String arrays to char ** </a>
<li><a href="#n66">Expanding a Java object to multiple arguments</a>
<li><a href="#n67">Using typemaps to return arguments</a>
<li><a href="#n68">Adding Java downcasts to polymorphic return types</a>
<li><a href="#n69">Adding an equals method to the Java classes</a>
<li><a href="#n70">Void pointers and a common Java base class</a>
</ul>
<li><a href="#n71">Living with Java Directors</a>
<li><a href="#n72">Odds and ends</a>
<ul>
<li><a href="#n73">JavaDoc comments</a>
<li><a href="#n74">Functional interface without proxy classes</a>
<li><a href="#n75">Using your own JNI functions</a>
<li><a href="#n76">Performance concerns and hints</a>
</ul>
<li><a href="#n77">Examples</a>
</ul>
<!-- INDEX -->



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. 


<a name="overview"></a>
<a name="n2"></a><H2>17.1 Overview</H2>


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.

<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 Basics</a>" chapter will be a useful read in conjunction with this one.
<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.

<a name="preliminaries"></a>
<a name="n3"></a><H2>17.2 Preliminaries</H2>


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>

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>

<a name="running_swig"></a>
<a name="n4"></a><H3>17.2.1 Running SWIG</H3>


Suppose that you defined a SWIG module such as the following:

<blockquote>
<pre>
%module example
%{
#include "header.h"
%}
int fact(int n);
</pre>
</blockquote>


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

<blockquote><pre>%swig -java example.i
</pre></blockquote>
<p>

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

<p>
<blockquote><pre>$ swig -c++ -java example.i
</pre></blockquote>

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>
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#output">output directory </a> that the Java files are generated into using <tt>-outdir</tt>.

<a name="commandline"></a>
<a name="n5"></a><H3>17.2.2 Additional Commandline Options</H3>


The following table list the additional commandline options available for the Java module. They can also be seen by using: 
<blockquote><pre>swig -java -help 
</pre></blockquote>

<table>
<tr>
<th>Java specific options</th>
</tr>

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

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

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

<a name="getting_right_headers"></a>
<a name="n6"></a><H3>17.2.3 Getting the right header files</H3>


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>
<p>
<blockquote><pre>
/usr/java/include
/usr/java/include/&lt;operating_system&gt;
</pre></blockquote>
<p>

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

<a name="compiling_dynamic"></a>
<a name="n7"></a><H3>17.2.4 Compiling a dynamic module</H3>


The JNI code exists in a dynamic module or shared library (DLL on Windows) and gets loaded by the JVM. 
To build a shared library file, you need to compile your module in a manner similar to the following (shown for Solaris):<p>
<p>
<blockquote><pre>
$ swig -java example.i
$ gcc -c example_wrap.c  -I/usr/java/include -I/usr/java/include/solaris
$ ld -G example_wrap.o  -o libexample.so

</pre></blockquote>
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://swig.cs.uchicago.edu/cgi-bin/wiki.pl">SWIG Wiki</a> for
additional information.
<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="#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>
<p>

<a name="using_module"></a>
<a name="n8"></a><H3>17.2.5 Using your module</H3>


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

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

  public static void main(String argv[]) {
    System.out.println(example.fact(4));
  }
}
</pre></blockquote>
Compile all the Java files and run:

<blockquote><pre>
$ javac *.java
$ java main
24
$
</pre></blockquote>

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

<a name="dynamic_linking_problems"></a>
<a name="n9"></a><H3>17.2.6 Dynamic linking problems</H3>


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>
You may get an exception similar to this:
<blockquote><pre>
$ java main
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 main.<clinit>(main.java:5)
</pre></blockquote>

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>. 
If you are debugging using <tt> java -debug</tt>, then the native library must be called <i>name_g.dll</i> on Windows and <i>libname_g.so</i> on Unix.
<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>

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:

<blockquote><pre>
$ java main
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 main.<clinit>(main.java:5)
$
</pre></blockquote>

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

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://swig.cs.uchicago.edu/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.


<a name="compilation_problems_cpp"></a>
<a name="n10"></a><H3>17.2.7 Compilation problems and compiling with C++</H3>


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

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

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>
<blockquote><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></blockquote>

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:

<blockquote>
<pre>
$ ldd swig
        libstdc++-libc6.1-1.so.2 => /usr/lib/libstdc++-libc6.1-1.so.2 (0x40019000)
        libm.so.6 => /lib/libm.so.6 (0x4005b000)
        libc.so.6 => /lib/libc.so.6 (0x40077000)
        /lib/ld-linux.so.2 => /lib/ld-linux.so.2 (0x40000000)
$
</pre>
</blockquote>

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.


<a name="building_windows"></a>
<a name="n11"></a><H3>17.2.8 Building on Windows</H3>


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>

<a name="visual_studio"></a>
<a name="n12"></a><H4>17.2.8.1 Running SWIG from Visual Studio</H4>


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#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>
<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>
Now, assuming all went well, SWIG will be automatically invoked when you build your project.  
When doing a build, any changes made to the interface file will result in SWIG being automatically invoked to produce a new version of the wrapper file.  
The Java classes that SWIG output should also be compiled into .class files. 
To run the native code in the DLL (example.dll), make sure that it is in your path then run your Java program which uses it, as described in the previous section. 
If the library fails to load have a look at <a href="#dynamic_linking_problems">Dynamic linking problems</a>.

<a name="nmake"></a>
<a name="n13"></a><H4>17.2.8.2 Using NMAKE</H4>


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


<a name="java_basic_tour"></a>
<a name="n14"></a><H2>17.3 A tour of basic C/C++ wrapping</H2>


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.

<a name="module_packages_classes"></a>
<a name="n15"></a><H3>17.3.1 Modules, packages and generated Java classes</H3>


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 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.
Details of all these generated classes will unfold as you read this section.
<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>

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.

<blockquote><pre>
swig -java -package com.bloggs.swig -outdir com/bloggs/swig example.i
</pre></blockquote>

SWIG won't create the directory, so make sure it exists beforehand.

<a name="functions"></a>
<a name="n16"></a><H3>17.3.2 Functions</H3>


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>
<blockquote><pre>%module example
int fact(int n);

</pre></blockquote>

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

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


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

<blockquote><pre>
System.out.println(example.fact(4));
</pre></blockquote>


<a name="global_variables"></a>
<a name="n17"></a><H3>17.3.3 Global variables</H3>


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.

<blockquote><pre>
// SWIG interface file with global variables
%module example
...
extern int My_variable;
extern double density;
...
</pre></blockquote>

<p>

Now in Java :<p>
<p>

<blockquote><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></blockquote>

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:

<blockquote><pre>
%rename Clash RenamedClash;
float Clash;
int clash;
</pre></blockquote>

<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>
To make ordinary variables read-only, you can use the <tt>%immutable</tt> directive. For example:

<blockquote>
<pre>
%immutable;
extern char *path;
%mutable;
</pre>
</blockquote>

The <tt>%immutable</tt> directive stays in effect until it is explicitly disabled using
<tt>%mutable</tt>.

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

<blockquote>
<pre>
%immutable path;
...
extern char *path;      // Read-only (due to %immutable)
</pre>
</blockquote>


<a name="constants"></a>
<a name="n18"></a><H3>17.3.4 Constants</H3>


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:

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

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

<blockquote><pre>
public interface exampleConstants {
  // enums and constants
  public final static double PI = exampleJNI.get_PI();
  public final static String VERSION = exampleJNI.get_VERSION();
  public final static int FOO = exampleJNI.get_FOO();
  public final static String path = exampleJNI.get_path();
}
</pre></blockquote>

These are runtime constants. They are not compiler constants 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#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:

<blockquote><pre>
%javaconst(1);
%javaconst(0) BIG;
#define BIG 1000LL
#define EXPRESSION (0x100+5)
</pre></blockquote>

generates:

<blockquote><pre>
public interface exampleConstants {
  // enums and constants
  public final static long BIG = exampleJNI.get_BIG();
  public final static int EXPRESSION = (0x100+5);
}
</pre></blockquote>

Be careful using the <tt>%javaconst(1)</tt> directive as not all C code will compile as Java code. For example the 
<tt>1000LL</tt> value for the <tt>BIG</tt> constant above would not generate valid Java code. 
The example demonstrates how you can target particular constants (<tt>BIG</tt>) with <tt>%javaconst</tt>.

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

<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):
<blockquote><pre>
public class example implements exampleConstants {
}
</pre></blockquote>

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


<a name="enumerations"></a>
<a name="n19"></a><H3>17.3.5 Enumerations</H3>


Enumerations are wrapped as final static integers in Java and are also initialised using a JNI call. For example:

<blockquote>
<pre>
enum Beverage { ALE, LAGER=10, STOUT, PILSNER };
</pre>
</blockquote>

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

<blockquote><pre>
public interface exampleConstants {
  // enums and constants
  public final static int ALE = exampleJNI.get_ALE();
  public final static int LAGER = exampleJNI.get_LAGER();
  public final static int STOUT = exampleJNI.get_STOUT();
  public final static int PILSNER = exampleJNI.get_PILSNER();
}
</pre></blockquote>

The <tt>%javaconst(flag)</tt> directive introduced in the previous section on constants can also be used with enums,
thereby also allowing enum values to be used in Java switch statements. 
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.
Example usage:

<blockquote>
<pre>
%javaconst(1);
%javaconst(0) PILSNER;
enum Beverage { ALE, LAGER=10, STOUT, PILSNER };
</pre>
</blockquote>

generates:

<blockquote><pre>
public interface exampleConstants {
  // enums and constants
  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.get_PILSNER();
}
</pre></blockquote>

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>
For enums, make sure that the definition of the enumeration actually appears in a header
file or in the wrapper file somehow---if you just have an enum in a SWIG interface without
also telling the C compiler about it, the wrapper code won't compile.

<p>

<a name="pointers"></a>
<a name="n20"></a><H3>17.3.6 Pointers</H3>


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

<blockquote>
<pre>
%module example

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

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

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

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

<blockquote>
<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>
</blockquote>

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>

<a name="structures"></a>
<a name="n21"></a><H3>17.3.7 Structures</H3>


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>
<blockquote><pre>struct Vector {
	double x,y,z;
};

</pre></blockquote>

is used as follows:

<blockquote><pre>
Vector v = new Vector();
v.setX(3.5);
v.setY(7.2);
double x = v.getX();
double y = v.getY();
</pre></blockquote>
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>

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

<blockquote>
<pre>
struct Foo {
   ...
   %immutable;
   int x;        /* Read-only members */
   char *name;
   %mutable;
   ...
};
</pre>
</blockquote>

<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>
If a structure contains arrays, access to those arrays is managed through pointers.  For
example, consider this:

<blockquote>
<pre>
struct Bar {
    int  x[16];
};
</pre>
</blockquote>

If accessed in Java, you will see behavior like this:

<blockquote>
<pre>
Bar b = new Bar();
SWIGTYPE_p_int x = b.getX();
</pre>
</blockquote>

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:

<blockquote>
<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>
</blockquote>

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.
Array access can be changed from this default to use Java arrays and this is covered later.

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

<blockquote>
<pre>
struct Foo {
   int a;
};

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

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

<blockquote>
<pre>
Bar b = new Bar();
Foo x = b.getF();
</pre>
</blockquote>

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:

<blockquote>
<pre>
Bar b;
Foo *x = &b->f;       /* Points inside b */
</pre>
</blockquote>

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

<blockquote>
<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>
</blockquote>


<a name="classes"></a>
<a name="n22"></a><H3>17.3.8 C++ classes</H3>


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

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

you can use it in Java like this:

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

Class data members are accessed in the same manner as C structures.  

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

<blockquote>
<pre>
class Spam {
public:
   static void foo();
   static int bar;
};
</pre>
</blockquote>

The static members work like any other Java static member:

<blockquote>
<pre>
Spam.foo();
int bar = Spam.getBar();
</pre>
</blockquote>


<a name="inheritance"></a>
<a name="n23"></a><H3>17.3.9 C++ inheritance</H3>


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

<blockquote>
<pre>
class Foo {
...
};

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

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

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

will of course display:

<blockquote><pre>
Foo
</pre></blockquote>


Furthermore, if you have functions like this

<blockquote>
<pre>
void spam(Foo *f);
</pre>
</blockquote>

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

<a name="pointers_refs_arrays"></a>
<a name="n24"></a><H3>17.3.10 Pointers, references, arrays and pass by value</H3>


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

<blockquote>
<pre>
void spam1(Foo *x);      // Pass by pointer
void spam2(Foo &x);      // Pass by reference
void spam3(Foo x);       // Pass by value
void spam4(Foo x[]);     // Array of objects
</pre>
</blockquote>

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:

<blockquote>
<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>
</blockquote>

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

<blockquote>
<pre>
Foo *spam5();
Foo &spam6();
Foo  spam7();
</pre>
</blockquote>

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).

<a name="null_pointers"></a>
<a name="n25"></a><H4>17.3.10.1 Null pointers</H4>


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.

<blockquote>
<pre>
example.spam1(null);   // Pointer - ok
example.spam2(null);   // Reference - NullPointerException
example.spam3(null);   // Value - NullPointerException
example.spam4(null);   // Array - ok
</pre>
</blockquote>

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.

<a name="overloaded_functions"></a>
<a name="n26"></a><H3>17.3.11 C++ overloaded functions</H3>


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

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

You can use them in Java in a straightforward manner:

<blockquote>
<pre>
foo(3);           // foo(int)
foo("Hello");     // foo(char *c)
</pre>
</blockquote>

Similarly, if you have a class like this,

<blockquote>
<pre>
class Foo {
public:
    Foo();
    Foo(const Foo &);
    ...
};
</pre>
</blockquote>

you can write Java code like this:

<blockquote>
<pre>
Foo f = new Foo();        // Create a Foo
Foo g = new Foo(f);       // Copy f
</pre>
</blockquote>

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

<blockquote>
<pre>
void spam(int);
void spam(unsigned short);
</pre>
</blockquote>

Here both int and unsigned short map onto a Java int. 
Here is another example:

<blockquote>
<pre>
void foo(Bar *b);
void foo(Bar &b);
</pre>
</blockquote>

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

<blockquote>
<pre>
example.i:12: Warning(509): Overloaded spam(unsigned short) is shadowed by spam(int) at example.i:11.
</pre>
</blockquote>
The generated Java code will not compile either.

To fix this, you either need to ignore or rename one of the methods.  For example:

<blockquote>
<pre>
%rename(spam_short) spam(short);
...
void spam(int);    
void spam(short);   // Accessed as spam_short
</pre>
</blockquote>

or

<blockquote>
<pre>
%ignore spam(short);
...
void spam(int);    
void spam(short);   // Ignored
</pre>
</blockquote>

<P>

<a name="namespaces"></a>
<a name="n27"></a><H3>17.3.12 C++ namespaces</H3>


SWIG is aware of C++ namespaces, but 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,

<blockquote>
<pre>
%module example

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

it works in Java as follows:

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

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

<blockquote>
<pre>
%rename(Bar_spam) Bar::spam;

namespace Foo {
    int spam();
}

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

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

<a name="templates"></a>
<a name="n28"></a><H3>17.3.13 C++ templates</H3>


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:

<blockquote>
<pre>
%module example
%{
#include "pair.h"
%}

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&, const T2&);
  ~pair();
};

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

In Java:

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

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

<a name="smart_pointers"></a>
<a name="n29"></a><H3>17.3.14 C++ Smart Pointers</H3>


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->()</tt> like this:

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

Then, if you have a class like this,

<blockquote>
<pre>
class Foo {
public:
     int x;
     int bar();
};
</pre>
</blockquote>

A smart pointer would be used in C++ as follows:

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

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:

<blockquote>
<pre>
%module example
...
%template(SmartPtrFoo) SmartPtr&lt;Foo&gt;;
...
</pre>
</blockquote>

Now, in Java, everything should just "work":

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

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

<blockquote>
<pre>
Foo f = p.__deref__();               // Returns underlying Foo *
</pre>
</blockquote>

<a name="further_details"></a>
<a name="n30"></a><H2>17.4 Further details on the generated Java classes</H2>


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 programing 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.
First, the crucial intermediary JNI class is considered.

<a name="imclass"></a>
<a name="n31"></a><H3>17.4.1 The intermediary JNI class</H3>


In the <a href="SWIG.html">"SWIG basics"</a> and <a href="SWIGPlus.html">"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

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

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

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

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:

<blockquote>
<pre>
JNIEXPORT jlong JNICALL Java_exampleJNI_new_1Foo(JNIEnv *jenv, jclass jcls);
JNIEXPORT void JNICALL Java_exampleJNI_delete_1Foo(JNIEnv *jenv, jclass jcls, jlong jarg1);
JNIEXPORT void JNICALL Java_exampleJNI_set_1Foo_1x(JNIEnv *jenv, jclass jcls, jlong jarg1, jint jarg2);
JNIEXPORT jint JNICALL Java_exampleJNI_get_1Foo_1x(JNIEnv *jenv, jclass jcls, jlong jarg1);
JNIEXPORT jint JNICALL Java_exampleJNI_Foo_1spam(JNIEnv *jenv, jclass jcls, jlong jarg1, jint jarg2, jlong jarg3);
JNIEXPORT void JNICALL Java_exampleJNI_egg(JNIEnv *jenv, jclass jcls, jlong jarg1);
</pre>
</blockquote>

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

<blockquote>
<pre>
class exampleJNI {
  public final static native long new_Foo();
  public final static native void delete_Foo(long jarg1);
  public final static native void set_Foo_x(long jarg1, int jarg2);
  public final static native int get_Foo_x(long jarg1);
  public final static native int Foo_spam(long jarg1, int jarg2, long jarg3);
  public final static native void egg(long jarg1);
}
</pre>
</blockquote>

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="#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>

You may notice that SWIG uses a Java long wherever a pointer or class object needs traversing 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 uses Java code wherever possible as it is compiled into byte code which requires fewer string operations.

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

<blockquote>
<pre>
%module (jniclassname="name") modulename
</pre>
</blockquote>

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

<a name="imclass_pragmas"></a>
<a name="n32"></a><H4>17.4.1.1 The intermediary JNI class pragmas</H4>


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>
<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>jniclassclassmodifiers  </td> <td>Class modifiers 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:

<blockquote>
<pre>
[ jniclassimports pragma ]
[ jniclassmodifiers pragma ] class jniclassname extends [ jniclassbase pragma ] implements [ jniclassinterfaces pragma ] {
[ jniclasscode pragma ]
... SWIG generated native methods ...
}
</pre>
</blockquote>

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:

<blockquote>
<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>
</blockquote>

Pragmas will take either <tt>""</tt> or <tt>%{ %}</tt> as delimeters. 
For example, let's change the intermediary JNI class access attribute to public. 

<blockquote>
<pre>
%pragma(java) jniclassclassmodifiers="public"
</pre>
</blockquote>

All the methods in the intermediary JNI class will then be callable outside of the package as the method modifiers are public by default.

<a name="java_module_class"></a>
<a name="n33"></a><H3>17.4.2 The Java module class</H3>


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

<blockquote>
<pre>
public class example {
  public static void egg(Foo chips) {
    exampleJNI.egg(Foo.getCPtr(chips));
  }
}
</pre>
</blockquote>

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:

<blockquote>
<pre>
example.egg(new Foo());
</pre>
</blockquote>

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.

<a name="module_class_pragmas"></a>
<a name="n34"></a><H4>17.4.2.1 The Java module class pragmas</H4>


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

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

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


<a name="java_proxy_classes"></a>
<a name="n35"></a><H3>17.4.3 Java proxy classes</H3>


A Java proxy class is generated for each structure, union or C++ class that is wrapped.
The default proxy class for our previous example looks like this:

<blockquote>
<pre>
public class Foo {
  private long swigCPtr;
  protected boolean swigCMemOwn;

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

  protected void finalize() {
    delete();
  }

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

  protected static long getCPtr(Foo obj) {
    return obj.swigCPtr;
  }

  public void setX(int x) {
    exampleJNI.set_Foo_x(swigCPtr, x);
  }

  public int getX() {
    return exampleJNI.get_Foo_x(swigCPtr);
  }

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

  public Foo() {
    this(exampleJNI.new_Foo(), true);
  }
}
</pre>
</blockquote>


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:

<blockquote>
<pre>
Foo f = new Foo();
f.setX(3);
int y = f.spam(5, new Foo());
</pre>
</blockquote>

<a name="memory_management"></a>
<a name="n36"></a><H4>17.4.3.1 Memory management</H4>


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


<blockquote>
<pre>
class Foo {
public:
    Foo();
    Foo bar1();
    Foo &bar2();
    Foo *bar2();
};
</pre>
</blockquote>

In Java:

<blockquote>
<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>
</blockquote>

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

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

Now, consider the following Java code:

<blockquote>
<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>
</blockquote>

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>
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 is achieved using a typemap to add pure Java code to the proxy class and is detailed later in the section on typemaps.

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

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

If we call the factory function, then we have to manually delete the memory:

<blockquote>
<pre>
Obj obj = Factory.createObj();   // obj.swigCMemOwn = false
...
obj.delete();
</pre>
</blockquote>

Now add in the %newobject directive:

<blockquote>
<pre>
%newobject Factory::createObj();

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

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.

<blockquote>
<pre>
Obj obj = Factory.createObj();   // obj.swigCMemOwn = true;
...
</pre>
</blockquote>


<a name="inheritance_mirroring"></a>
<a name="n37"></a><H4>17.4.3.2 Inheritance</H4>


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

<blockquote><pre>
class Base {
public:
  virtual double foo();
};

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

The base class is generated much like any other proxy class seen so far:

<blockquote><pre>
public class Base {
  private long swigCPtr;
  protected boolean swigCMemOwn;

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

  protected void finalize() {
    delete();
  }

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

  protected static long getCPtr(Base obj) {
    return obj.swigCPtr;
  }

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

  public Base() {
    this(exampleJNI.new_Base(), true);
  }
}
</pre></blockquote>

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

<blockquote><pre>
public class Derived extends Base {
  private long swigCPtr;

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

  protected void finalize() {
    delete();
  }

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

  protected static long getCPtr(Derived obj) {
    return obj.swigCPtr;
  }

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

  public Derived() {
    this(exampleJNI.new_Derived(), true);
  }
}
</pre></blockquote>

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>SWIGDerivedToBase()</tt> call converts the pointer from a <tt>Derived *</tt> to a <tt>Base *</tt> as C++ compilers are free to implement 
pointers in the inheritance hierarchy with different values. 

<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>


<a name="proxy_classes_gc"></a>
<a name="n38"></a><H4>17.4.3.3 Proxy classes and garbage collection</H4>


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. 
The unfortunate thing is that Sun, in their wisdom, do not guarantee that the finalizers will be called. 
When a program exits, the garbage collector does not always call the finalizers. 
Depending on what the finalizers do and which operating system you use, this may or may not be a problem. 
<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>

Some not so ideal solutions are:
<ol>
<li start=1>
Call the <tt>System.runFinalizersOnExit(true)</tt> or <tt>Runtime.getRuntime().runFinalizersOnExit(true)</tt> to ensure the finalizers are called before the program exits. The catch is that this is a deprecated function call as the documenation says: 
<blockquote><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></blockquote> 
In many cases you will be lucky and find that it works, but it is not to be advocated. 
Have a look at <a href=http://java.sun.com>Sun's Java web site</a> and search for <tt>runFinalizersOnExit</tt>.
</li>
<p>
<li>
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: 
<blockquote><pre>
  static {
    Runtime.getRuntime().addShutdownHook( 
      new Thread() {
        public void run() { System.gc(); System.runFinalization(); }
      }
    );
  }
</pre></blockquote>
Although this usually works, the documentation doesn't guarantee that <tt>runFinalization()</tt> will actually call the finalizers. 
As the the shutdown hook is guaranteed you could also make a JNI call to clean up any resources that are being tracked by the C/C++ code.
</li>
<p>
<li>
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 inadvertantly used again a Java null pointer exception is thrown, the alternative would crash the JVM by using a null C pointer. 
For example given a SWIG generated class A:
<blockquote><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></blockquote>
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.
</li>

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

<a name="type_wrapper_classes"></a>
<a name="n39"></a><H3>17.4.4 Type wrapper classes</H3>


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

<blockquote><pre>
public class SWIGTYPE_p_int {
  private 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></blockquote>

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>
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>

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:

<blockquote>
<pre>
void spam(Snazzy *x, Snazzy &y, Snazzy z);
</pre>
</blockquote>

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:

<blockquote>
<pre>
public static void spam(SWIGTYPE_p_Snazzy x, SWIGTYPE_p_Snazzy y, SWIGTYPE_p_Snazzy z) { ... }
</pre>
</blockquote>

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


<blockquote>
<pre>
typedef int Snazzy;
void spam(Snazzy *x, Snazzy &y, Snazzy z);
</pre>
</blockquote>

Because the typedefs have been tracked the Java function generated is:
<blockquote>
<pre>
public static void spam(SWIGTYPE_p_int x, SWIGTYPE_p_int y, int z) { ... }
</pre>
</blockquote>

<p>

<a name="java_directors"></a>
<a name="n40"></a><H2>17.5 Cross language polymorphism using directors (experimental)</H2>


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>

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>

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.

<a name="java_enabling_directors"></a>
<a name="n41"></a><H3>17.5.1 Enabling directors</H3>


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:

<blockquote>
<pre>
%module(directors="1") modulename
</pre>
</blockquote>

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:

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

// genarate directors for all virtual methods in class Foo
%feature("director") Foo;      

// generate a director for just Foo::bar()
%feature("director") Foo::bar; 
</pre>
</blockquote>

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

<blockquote>
<pre>
%feature("director") Foo;
%feature("nodirector") Foo::bar;
</pre>
</blockquote>

will generate directors for all virtual methods of class Foo except bar().  
<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()):

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

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

<a name="java_directors_classes"></a>
<a name="n42"></a><H3>17.5.2 Director classes</H3>


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>

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>

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>


<a name="java_directors_overhead"></a>
<a name="n43"></a><H3>17.5.3 Overhead and code bloat</H3>


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>

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.


<a name="java_directors_example"></a>
<a name="n44"></a><H3>17.5.4 Simple directors example</H3>


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

<blockquote>
<pre>
%module(directors="1") example;

%feature("director") DirectorBase;

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

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

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 intermediate class marshall and convert arguments between C++ and Java when needed.
</p>

<blockquote>
<pre>
public class directorDerived extends DirectorBase {
  public directorDerived() {
  }

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

Running the following Java code

<blockquote>
<pre>
directorDerived director = new directorDerived();
example.callup(director);
</pre>
</blockquote>

will result in the following being output:

<blockquote>
<pre>
directorDerived::upcall_method() invoked.
</pre>
</blockquote>

<a name="common_customization"></a>
<a name="n45"></a><H2>17.6 Common customization features</H2>


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.

<a name="helper_functions"></a>
<a name="n46"></a><H3>17.6.1 C/C++ helper functions</H3>


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

<blockquote>
<pre>
typedef struct Image {...};
void set_transform(Image *im, double m[4][4]);
</pre>
</blockquote>

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:

<blockquote>
<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>
</blockquote>

From Java, you could then write code like this:

<blockquote>
<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>
</blockquote>

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.  

<a name="class_extension"></a>
<a name="n47"></a><H3>17.6.2 Class extension with %extend</H3>


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:

<blockquote>
<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->x,self->y,self->z);
       return tmp;
   }
   Vector(double x, double y, double z) {
       Vector *v = (Vector *) malloc(sizeof(Vector));
       v->x = x;
       v->y = y;
       v->z = z;
       return v;
   }
};
</pre>
</blockquote>

Now, in Java

<blockquote>
<pre>
Vector v = new Vector(2,3,4);
System.out.println(v);
</pre>
</blockquote>
will display

<blockquote>
<pre>
Vector(2,3,4)
</pre>
</blockquote>

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

<a name="exception_handling"></a>
<a name="n48"></a><H3>17.6.3 Exception handling with %exception</H3>


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.

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

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

In Java,

<blockquote>
<pre>
SWIGTYPE_p_void a = example.malloc(2000000000);
</pre>
</blockquote>

will produce a familiar looking Java exception:

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

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

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

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="#special_variables">Java special variables</a> for further explanation.

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

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

class Base {
public:
     Foo *getitem(int index);      // Exception handler added
     ...
};
</pre>
</blockquote>

The examples above first use the C JNI calling syntax then the C++ JNI calling syntax. The C++ calling syntax will not compile as C and also visa versa.
It is however possible to write JNI calls which will compile under both C and C++ and is covered in the <a href="#typemaps_for_c_and_c++">Typemaps for both C and C++ compilation</a> section. 

<p>
The language-independent <tt>exception.i</tt> library file can also be used
to raise exceptions.  See the <a href="Library.html">SWIG Library</a> chapter.

<a name="method_access"></a>
<a name="n49"></a><H3>17.6.4 Method access with %javamethodmodifiers</H3>


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:

<blockquote>
<pre>
%javamethodmodifiers protect_me() "protected";
void protect_me();
</pre>
</blockquote>

Will produce the method in the module class with protected access.

<blockquote>
<pre>
protected static void protect_me() {
  exampleJNI.protect_me();
}
</pre>
</blockquote>

<a name="tips_techniques"></a>
<a name="n50"></a><H2>17.7 Tips and techniques</H2>


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.

<a name="input_output_parameters"></a>
<a name="n51"></a><H3>17.7.1 Input and output parameters using primitive pointers and references</H3>


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

<blockquote>
<pre>
void add(int x, int y, int *result) {
   *result = x + y;
}
</pre>
</blockquote>

or perhaps

<blockquote>
<pre>
int sub(int *x, int *y) {
   return *x-*y;
}
</pre>
</blockquote>

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

<blockquote>
<pre>
%module example
%include "typemaps.i"

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

In Java, this allows you to pass simple values.  For example:

<blockquote>
<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>
</blockquote>

Which will display:
<blockquote> <pre>
7 - 4 = 3
3 + 4 = 7
</pre></blockquote>

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>
If you don't want to use the names <tt>INPUT</tt> or <tt>OUTPUT</tt>, use the <tt>%apply</tt>
directive.  For example:

<blockquote>
<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>
</blockquote>

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

<blockquote>
<pre>
void negate(int *x) {
   *x = -(*x);
}
</pre>
</blockquote>

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

<blockquote>
<pre>
%include "typemaps.i"
...
void negate(int *INOUT);
</pre>
</blockquote>

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:

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

And no prizes for guessing the output:
<blockquote><pre>
Negative of 3 = -3
</pre></blockquote>

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: 

<blockquote>
<pre>
void negate(int *INOUT);
</pre>
</blockquote>
or using a reference:
<blockquote>
<pre>
void negate(int &INOUT);
</pre>
</blockquote>

<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>
Be aware that the primary purpose of the <tt>typemaps.i</tt> file is to support primitive datatypes.
Writing a function like this

<blockquote>
<pre>
void foo(Bar *OUTPUT);
</pre>
</blockquote>

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

<a name="simple_pointers"></a>
<a name="n52"></a><H3>17.7.2 Simple pointers</H3>


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:

<blockquote>
<pre>
%module example
%include "cpointer.i"

extern void add(int x, int y, int *result);
%pointer_functions(int, intp);
</pre>
</blockquote>

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:

<blockquote>
<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>
</blockquote>

In Java, you would use the functions like this:

<blockquote>
<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>
</blockquote>

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

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

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

<a name="c_arrays"></a>
<a name="n53"></a><H3>17.7.3 Wrapping C arrays with Java arrays</H3>


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:

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

These one dimensional arrays can then be used as if they were Java arrays:

<blockquote>
<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>
</blockquote>

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:

<blockquote>
<pre>
array: 100 101 102 103
global_array: 100 101 102 103
</pre>
</blockquote>

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

<a name="unbounded_c_arrays"></a>
<a name="n54"></a><H3>17.7.4 Unbounded C Arrays</H3>


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

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

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:

<blockquote>
<pre>
%include "arrays_java.i"
%apply int[ANY] {int *};
</pre>
</blockquote>

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:

<blockquote>
<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>
</blockquote>

and the sum would be displayed:

<blockquote>
<pre>
Sum = 49995000
</pre>
</blockquote>

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:

<blockquote>
<pre>
%include "carrays.i"
%array_functions(int, intArray);
</pre>
</blockquote>

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:

<blockquote>
<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>
</blockquote>

In Java, you would use the functions like this:

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

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.

<blockquote>
<pre>
%include "carrays.i"
%array_class(int, intArray);
</pre>
</blockquote>

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:

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

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.

<a name="java_typemaps"></a>
<a name="n55"></a><H2>17.8 Java typemaps</H2>


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 the material in the "<a href="Typemaps.html">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.  </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.

<a name="default_primitive_type_mappings"></a>
<a name="n56"></a><H3>17.8.1 Default primitive type mappings</H3>


The following table lists the default type mapping from Java to C/C++.<p>
<table BORDER>
<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 & </td>
<td>boolean</td>
<td>jboolean</td>
</tr>

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

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

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

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

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

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

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

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

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

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

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

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

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

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

</table>
<br>
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>

Given the following C function:
<blockquote> <pre>
void func(unsigned short a, char *b, const long &c, unsigned long long d);
</blockquote> </pre>
The module class method would be:
<blockquote> <pre>
public static void func(int a, String b, int c, java.math.BigInteger d) {...}
</blockquote> </pre>
The intermediary JNI class would use the same types:
<blockquote> <pre>
public final static native void func(int jarg1, String jarg2, int jarg3, java.math.BigInteger jarg4);
</blockquote> </pre>
and the JNI function would look like this:
<blockquote> <pre>
JNIEXPORT void JNICALL Java_exampleJNI_func(JNIEnv *jenv, jclass jcls, jint jarg1, jstring jarg2, jint jarg3, jobject jarg4) {...}
</blockquote> </pre>
<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>

<a name="jvm64"></a>
<a name="n57"></a><H3>17.8.2 Sixty four bit JVMs</H3>


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.


<a name="what_is_typemap"></a>
<a name="n58"></a><H3>17.8.3 What is a typemap?</H3>


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>
<blockquote><pre>%module example

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

<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>

When this example is compiled into a Java module, it can be used as follows:<p>
<p>
<blockquote><pre>
System.out.println(example.fact(6));
</pre></blockquote>
and the output will be:
<blockquote><pre>
Received an integer : 6
720
</pre></blockquote>

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:

<blockquote><pre>
%module example

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

extern int fact(int nonnegative);
</pre></blockquote>

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

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

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

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>
Typemaps can also be defined for groups of consecutive arguments.  For example:

<blockquote>
<pre>
%typemap(in) (char *str, int len) {
...
};

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

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):

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

<a name="typemaps_c_to_java_types"></a>
<a name="n59"></a><H3>17.8.4 Typemaps for mapping C/C++ types to Java types</H3>


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:

<br>&nbsp;
<table BORDER>
<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 converts 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>

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

<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>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="#default_primitive_type_mappings">Default primitive type mappings</a>
covered earlier.
There are other type mapping typemaps in the Java library. 
These are listed below:
<br>&nbsp;
<table BORDER>
<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.</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>

</table>

<a name="special_variables"></a>
<a name="n60"></a><H3>17.8.5 Java special variables</H3>


The standard SWIG special variables are available for use within typemaps as described in the <a href=Typemaps.html>Typemaps documentation</a>, for example <tt>$1</tt>, <tt>$input</tt>,<tt>$result</tt> etc.

<p>
The Java module uses a few additional special variables:
<p>

<b><tt>$javaclassname</tt></b><br>
<tt>$javaclassname</tt> is similar to <tt>$1_type</tt>. It expands to the class name for use in Java. 
When wrapping a union, struct or class, it expands to the Java proxy class name.
Otherwise it expands to the type wrapper class name.
For example, <tt>$javaclassname</tt> is replaced by <tt>Foo</tt> when the wrapping a <tt>struct Foo</tt> or <tt>struct Foo *</tt> and 
<tt>SWIGTYPE_p_unsigned_short</tt> is used for <tt>unsigned short *</tt>.
<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:

<blockquote><pre>
%typemap(check) int * %{ 
  if (error) {
    SWIG_exception(SWIG_IndexError, "Array element error");
    return $null;
  }
%}
</pre></blockquote>

If the typemap gets put into a function with void as return, $null will expand to nothing:

<blockquote><pre>
JNIEXPORT void JNICALL Java_jnifn(...) {
    if (error) {
      SWIG_exception(SWIG_IndexError, "Array element error");
      return ;
    }
  ...
}
</pre></blockquote>

otherwise $null expands to NULL 

<blockquote><pre>
JNIEXPORT jobject JNICALL Java_jnifn(...) {
    if (error) {
      SWIG_exception(SWIG_IndexError, "Array element error");
      return NULL;
    }
  ...
}
</pre></blockquote>

<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>

Here is an example:

<blockquote><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></blockquote>

The generated proxy code is then:

<blockquote><pre>
public static Class bar(Class cls, int ush) {
  return new Class(exampleJNI.bar(Class.getCPtr(cls), ush), false);
}
</pre></blockquote>

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:

<blockquote><pre>
%newobject bar(Class cls, unsigned short ush);
</pre></blockquote>

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

<blockquote><pre>
public static Class bar(Class cls, int ush) {
  return new Class(exampleJNI.bar(Class.getCPtr(cls), ush), true);
}
</pre></blockquote>

<b><tt>$jniinput, $javacall and $packagepath</tt></b><br>
These special variables used in the directors typemaps. See <a href="#java_directors_typemaps">Director specific typemaps</a> for details.

<a name="typemaps_for_c_and_c++"></a>
<a name="n61"></a><H3>17.8.6 Typemaps for both C and C++ compilation</H3>


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

<blockquote><pre>
const jclass clazz = (*jenv)->FindClass(jenv, "java/lang/String");
</pre></blockquote>

whereas C++ code compilation of the same function call is a member function call using a class pointer like

<blockquote><pre>
const jclass clazz = jenv->FindClass("java/lang/String");
</pre></blockquote>

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

<blockquote><pre>
const jclass clazz = JCALL1(FindClass, jenv, "java/lang/String");
</pre></blockquote>

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>


<a name="java_code_typemaps"></a>
<a name="n62"></a><H3>17.8.7 Java code typemaps</H3>


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>

<tt>%typemap(javabase)</tt>
<blockquote>
base (extends) for Java class: empty default
</blockquote>

<tt>%typemap(javaclassmodifiers)</tt>
<blockquote>
class modifiers for the Java class: default is "public"
</blockquote>

<tt>%typemap(javacode)</tt>
<blockquote>
Java code is copied verbatim to the Java class: empty default
</blockquote>

<tt>%typemap(javadestruct, methodname="delete")</tt> <br>
<blockquote>
destructor wrapper - the <tt>delete()</tt> method (proxy classes only),
used for all 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.
</blockquote>

<tt>%typemap(javadestruct_derived, methodname="delete")</tt>
<blockquote>
destructor wrapper - the <tt>delete()</tt> method (proxy classes only),
same as "javadestruct" but only used for derived 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.
</blockquote>

<tt>%typemap(javaimports)</tt>
<blockquote>
import statements for Java class: empty default
</blockquote>

<tt>%typemap(javainterfaces)</tt>
<blockquote>
interfaces (extends) for Java class: empty default
</blockquote>

<tt>%typemap(javafinalize)</tt>
<blockquote>
the <tt>finalize()</tt> method (proxy classes only): default calls the <tt>delete()</tt> method
</blockquote>

<tt>%typemap(javagetcptr)</tt>
<blockquote>
the <tt>getCPtr()</tt> method: default returns the <tt>swigCPtr</tt> member variable
</blockquote>

<tt>%typemap(javaptrconstructormodifiers)</tt>
<blockquote>
method modifier for the constructors taking a C pointer and the memory ownership flag: default is "protected"
</blockquote>

In summary the contents of the typemaps make up a proxy class like this:

<blockquote>
<pre>
[ javaimports typemap ]
[ javamodifiers typemap ] class proxyclassname extends [ javabase typemap ] implements [ javainterfaces typemap ] {
[ javafinalize typemap ]
[ javaptrconstructormodifiers typemap ] proxyclassname(long cPtr, boolean cMemoryOwn) {...}
... Other SWIG generated constructors ...
public void <i>delete</i>() [ javadestruct OR javadestruct_derived typemap ]
[ javagetcptr typemap ]
[ javacode typemap ]
... proxy functions ...
}
</pre>
</blockquote>

Note the <tt><i>delete</i>()</tt> methodname is configurable, see "javadestruct" and "javadestruct_derived" typemaps above.
<p>

The type wrapper class is similar in construction:

<blockquote>
<pre>
[ javaimports typemap ]
[ javamodifiers typemap ] class typewrappername extends [ javabase typemap ] implements [ javainterfaces typemap ] {
[ javaptrconstructormodifiers typemap ] proxyclassname(long cPtr, boolean bFutureUse) {...}
... Other SWIG generated constructors ...
[ javagetcptr typemap ]
[ javacode typemap ]
}
</pre>
</blockquote>

The defaults can be overridden to tailor these classes and are often used to hide or expose the C/C++ pointer. Here is an example which will change the <tt>getCPtr()</tt> method from the default protected access to public access. 

<blockquote>
<pre>
%typemap(javagetcptr) SWIGTYPE %{
  public static long getCPtr($javaclassname obj) {
    return (obj == null) ? 0 : obj.swigCPtr;
  }
%}
</pre>
</blockquote>

Note that <tt>SWIGTYPE</tt> will target all proxy classes, but not all type wrapper classes. For the typemap to be used in all type wrapper classes, all the different types that type wrapper classes could be used for should be targeted:

<blockquote>
<pre>
%typemap(javagetcptr) SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE [], SWIGTYPE (CLASS::*) %{
  public static long getCPtr($javaclassname obj) {
    return obj.swigCPtr;
  }
%}
</pre>
</blockquote>

<p>

<a name="java_directors_typemaps"></a>
<a name="n63"></a><H3>17.8.8 Director specific typemaps</H3>


The Java directors feature requires the "javadirectorin", "javadirectorout" and the "directorin" 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.
<p>

<tt>%typemap(directorin)</tt>
<blockquote>


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:

<blockquote>
<pre>
%typemap(directorin,descriptor="I") int "$input = (jint) $1;"
</pre>
</blockquote>

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

<blockquote>
<pre>
%typemap(directorin,descriptor="Ljava/lang/String;") char *
  %{ $input = jenv-&gt;NewStringUTF($1); %}
</pre>
</blockquote>


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.

</blockquote>


<tt>%typemap(javadirectorin)</tt>
<blockquote>

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.

For primitive types, this typemap is usually specified as:
<blockquote>
<pre>
%typemap(javadirectorin) int "$jniinput"
</pre>
</blockquote>

The <code>$jniinput</code> special variable is analogous to <code>$javainput</code> special variable.
It is replaced by the input parameter name.

</blockquote>


<tt>%typemap(javadirectorout)</tt>
<blockquote>
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.

For primitive types, this typemap is usually specified as:
<blockquote>
<pre>
%typemap(javadirectorout) int "$javacall"
</pre>
</blockquote>

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.

</blockquote>

<tt>%typemap(javapackage)</tt>
<blockquote>


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.
For example:

<blockquote>
<pre>
// class Foo is handled in a different interface file:
%import "Foo.i"

%feature("director") Example;

%inline {
  class Bar { };

  class Example {
  public:
    virtual ~Example();
    void     ping(Foo *arg1, Bar *arg2);
  };
}
</pre>
</blockquote>

Assume that the Foo class is part of the Java package <i>wombat.foo</i> but the above interface file is part of the Java package <i>wombat.example</i>.
Without the "javapackage" typemap, SWIG will assume that the Foo class belongs to <i>wombat.example</i> class.
The corrected interface file looks like:

<blockquote>
<pre>
// class Foo is handled in a different interface file:
%import "Foo.i"
%typemap("javapackage") Foo "wombat.foo";
%feature("director") Example;

%inline {
  class Bar { };

  class Example {
  public:
    virtual ~Example();
    void     ping(Foo *arg1, Bar *arg2);
  };
}
</pre>
</blockquote>

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

<blockquote>
<pre>
%typemap("javapackage") SWIGTYPE, SWIGTYPE *, SWIGTYPE &amp; "package.for.most.classes";

%typemap("javapackage") Package_2_class_one "package.for.other.classes";
%typemap("javapackage") Package_3_class_two "package.for.another.set";
/* etc */
</pre>
</blockquote>

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>

</blockquote>

<a name="typemap_examples"></a>
<a name="n64"></a><H2>17.9 Typemap Examples</H2>


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.


<a name="converting_java_string_arrays"></a>
<a name="n65"></a><H3>17.9.1 Converting Java String arrays to char ** </H3>


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>
<p>
<blockquote><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(const 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 visa 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 &values[0];
}

%}
</pre></blockquote>

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>
<p>
<blockquote><pre>
// File main.java

public class main {

  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></blockquote>
When compiled and run we get:
<blockquote><pre>
$ java main
argv[0] = Cat
argv[1] = Dog
argv[2] = Cow
argv[3] = Goat
0:Dave
1:Mike
2:Susan
3:John
4:Michelle
</pre></blockquote>

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.

<a name="expanding_java_object"></a>
<a name="n66"></a><H3>17.9.2 Expanding a Java object to multiple arguments</H3>


Suppose that you had a collection of C functions with arguments
such as the following:

<blockquote>
<pre>
int foo(int argc, char **argv);
</pre>
</blockquote>

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:

<blockquote>
<pre>
example.foo(4, new String[]{"red", "green", "blue", "white"});
</pre>
</blockquote>

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:

<blockquote>
<pre>
%typemap(in) (int argc, char **argv) {
    int i = 0;
    $1 = (*jenv)->GetArrayLength(jenv, $input);
    $2 = (char **) malloc(($1+1)*sizeof(char *));
    /* make a copy of each string */
    for (i = 0; i<$1; i++) {
        jstring j_string = (jstring)(*jenv)->GetObjectArrayElement(jenv, $input, i);
        const char * c_string = (*jenv)->GetStringUTFChars(jenv, j_string, 0);
        $2[i] = malloc(strlen((c_string)+1)*sizeof(const char *));
        strcpy($2[i], c_string);
        (*jenv)->ReleaseStringUTFChars(jenv, j_string, c_string);
        (*jenv)->DeleteLocalRef(jenv, j_string);
    }
    $2[i] = 0;
}

%typemap(freearg) (int argc, char **argv) {
    int i;
    for (i=0; i<$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>
</blockquote>

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

<blockquote>
<pre>
example.foo(new String[]{"red", "green", "blue", "white"});
</pre>
</blockquote>


<a name="using_typemaps_return_arguments"></a>
<a name="n67"></a><H3>17.9.3 Using typemaps to return arguments</H3>


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>

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. 
Here is our example function:

<blockquote><pre>
/* Returns a status value and two values in out1 and out2 */
int spam(double a, double b, double *out1, double *out2);
</pre></blockquote>

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:
<blockquote><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->FindClass("MyDouble");
    jfieldID fid = jenv->GetFieldID(clazz, "swigCPtr", "J");
    jlong cPtr = jenv->GetLongField($input, fid);
    MyDouble *pMyDouble = NULL;
    *(MyDouble *)&pMyDouble = *(MyDouble *)&cPtr;
    $1 = &pMyDouble->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></blockquote>

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>

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:
<blockquote><pre>
// File: main.java

public class main {

  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></blockquote>

When compiled and run we get:
<blockquote><pre>
$ java main
1 12.0  340.0
</pre></blockquote>

<a name="adding_downcasts"></a>
<a name="n68"></a><H3>17.9.4 Adding Java downcasts to polymorphic return types</H3>


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 follow code:

<blockquote><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 << "Ambulance started" << endl;
    }
    void sound_siren() {
        cout << vol << " siren sounded!" << endl;
    }
...
};

Vehicle *vehicle_factory() {
    return new Ambulance("Very loud");
}
</pre></blockquote>

If we execute the following Java code:

<blockquote><pre>
Vehicle vehicle = example.vehicle_factory();
vehicle.start();

Ambulance ambulance = (Ambulance)vehicle;
ambulance.sound_siren();
</pre></blockquote>

We get:

<blockquote><pre>
Ambulance started
java.lang.ClassCastException
        at main.main(main.java:16)
</pre></blockquote>

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>

The first is not to use a Java cast but a call to C++ to make the cast. Add this to your code:
<blockquote><pre>
%exception Ambulance::dynamic_cast(Vehicle *vehicle) {
    $action
    if (!result) {
        jclass excep = jenv->FindClass("java/lang/ClassCastException");
        if (excep) {
            jenv->ThrowNew(excep, "dynamic_cast exception");
        }
    }
}
%extend Ambulance {
    static Ambulance *dynamic_cast(Vehicle *vehicle) {
        return dynamic_cast&lt;Ambulance *&gt;(vehicle);
    }
};
</pre></blockquote>

It would then be used from Java like this

<blockquote><pre>
Ambulance ambulance = Ambulance.dynamic_cast(vehicle);
ambulance.sound_siren();
</pre></blockquote>
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>:

<blockquote><pre>
%typemap(out) Vehicle * {
    Ambulance *downcast = dynamic_cast&lt;Ambulance *&gt;($1);
    *(Ambulance **)&$result = downcast;
}

%typemap(javaout) Vehicle * {
    return new Ambulance($jnicall, $owner);
  }
</pre></blockquote>

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:

<blockquote><pre>
class FireEngine : public Vehicle {
public:
    FireEngine() {}
    virtual void start() {
        cout << "FireEngine started" << endl;
    }
    void roll_out_hose() {
        cout << "Hose rolled out" << endl;
    }
 ...
};
Vehicle *vehicle_factory(int vehicle_number) {
    if (vehicle_number == 0)
        return new Ambulance("Very loud");
    else
        return new FireEngine();
}
</pre></blockquote>

To be able to downcast with this sort of Java code:

<blockquote><pre>
FireEngine fireengine = (FireEngine)example.vehicle_factory(1);
fireengine.roll_out_hose();
Ambulance ambulance = (Ambulance)example.vehicle_factory(0);
ambulance.sound_siren();
</pre></blockquote>

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.

<blockquote><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->FindClass("Ambulance");
        if (clazz) {
            jmethodID mid = jenv->GetMethodID(clazz, "<init>", "(JZ)V");
            if (mid) {
                jlong cptr = 0;
                *(Ambulance **)&cptr = ambulance; 
                $result = jenv->NewObject(clazz, mid, cptr, false);
            }
        }
    } else if (fireengine) {
        // call the FireEngine(long cPtr, boolean cMemoryOwn) constructor
        jclass clazz = jenv->FindClass("FireEngine");
        if (clazz) {
            jmethodID mid = jenv->GetMethodID(clazz, "<init>", "(JZ)V");
            if (mid) {
                jlong cptr = 0;
                *(FireEngine **)&cptr = fireengine; 
                $result = jenv->NewObject(clazz, mid, cptr, false);
            }
        }
    }
    else {
        cout << "Unexpected type " << endl;
    }

    if (!$result)
        cout << "Failed to create new java object" << endl;
}
</pre></blockquote>

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.

<a name="adding_equals_method"></a>
<a name="n69"></a><H3>17.9.5 Adding an equals method to the Java classes</H3>


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.
An equals method is easily added to all proxy classes. For example:

<blockquote>
<pre>
%typemap(javacode) SWIGTYPE %{
  public boolean equals(Object obj) {
    boolean equal = false;
    if (obj instanceof $javaclassname)
      equal = ((($javaclassname)obj).swigCPtr == this.swigCPtr);
    return equal;
  }
%}

class Foo { };
Foo* returnFoo(Foo *foo) { return foo; }
</pre>
</blockquote>

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

<blockquote>
<pre>
Foo foo1 = new Foo();
Foo foo2 = example.returnFoo(foo1);
System.out.println("foo1? " + foo1.equals(foo2));
</pre>
</blockquote>


<a name="void_pointers"></a>
<a name="n70"></a><H3>17.9.6 Void pointers and a common Java base class</H3>


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:

<blockquote>
<pre>
%typemap(javabase) SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE [], SWIGTYPE (CLASS::*) "SWIG"

%typemap(javacode) SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE [], SWIGTYPE (CLASS::*) %{
  protected long getPointer() {
    return swigCPtr;
  }
%}
</pre>
</blockquote>

<p>
Define new base class called SWIG:

<blockquote>
<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>
</blockquote>

This example contains some useful functionality which you may want in your code. 
<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>

<a name="java_directors_faq"></a>
<a name="n71"></a><H2>17.10 Living with Java Directors</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></li>

  <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><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></li>
  <p>
  Use the template's renamed name as the argument to the "javapackage" typemap:
  <br>
<blockquote>
<pre>
%typemap(javapackage)  std::vector<int>  "your.package.here"
%template(VectorOfInt) std::vector<int>;
</pre>
</blockquote>
  </p>

  <li><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></li>
  <p>
  Normally, a non-director generated Java proxy class creates temporary Java objects as follows:
<blockquote>
<pre>
public static void MyClass_method_upcall(MyClass self, long jarg1)
{
  Foo darg1 = new Foo(jarg1, false);

  self.method_upcall(darg1);
}
</pre>
</blockquote>
  <br>
  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 somthing like:

<blockquote>
<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>
</blockquote>

  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 compicated 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:

<blockquote>
<pre>
  public static Foo javaObjectFoo(Foo obj);
</pre>
</blockquote>

  From your code, this method is invoked as follows:

<blockquote>
<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>
</blockquote>

  An good approach for managing downcasting is placing a static method in each derived class that performs the downcast from the superclass, e.g.,
<blockquote>
<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 sublcass of Foo
      return null;
    }
  }
}
</pre>
</blockquote>

  Then change the code in MyClassDerived as follows:

<blockquote>
<pre>
public class MyClassDerived extends MyClass {
  /* ... */
  public void method_upcall(Foo foo_object)
  {
    FooDerived    derived = FooDerived.downcastFooDerived(foo_object) : null);
    /* rest of your code here */
  }
}
</pre>
</blockquote>

  <p>

  <li><i>Why isn't the proxy class declared abstract? Why aren't the director
  upcall methods in the proxy class declared abstract?</i></li>
  <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:

<blockquote>
<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 sublcass of Foo
      return null;
    }
  }
}
</pre>
</blockquote>
  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>
</ol>

<a name="odds_ends"></a>
<a name="n72"></a><H2>17.11 Odds and ends</H2>


<a name="javadoc_comments"></a>
<a name="n73"></a><H3>17.11.1 JavaDoc comments</H3>


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:

<blockquote>
<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>
</blockquote>

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



<a name="functional_interface"></a>
<a name="n74"></a><H3>17.11.2 Functional interface without proxy classes</H3>


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>

Consider the example we looked at when examining proxy classes:
<blockquote>
<pre>
class Foo {
public:
     int x;
     int spam(int num, Foo* foo);
};
</pre>
</blockquote>

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:

<blockquote>
<pre>
public class example {
  public static void set_Foo_x(SWIGTYPE_p_Foo self, int x) {...}
  public static int get_Foo_x(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>
</blockquote>

This approach is not nearly as natural as using proxy classes as the functions need to be used like this:

<blockquote>
<pre>
SWIGTYPE_p_Foo foo = example.new_Foo();
example.set_Foo_x(foo, 10);
int var = example.get_Foo_x(foo);
example.Foo_spam(foo, 20, foo);
example.delete_Foo(foo);
</pre>
</blockquote>

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.


<a name="using_own_jni_functions"></a>
<a name="n75"></a><H3>17.11.3 Using your own JNI functions</H3>


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:

<blockquote><pre>
%native (HandRolled) void HandRolled(int, char *);
%{
JNIEXPORT void JNICALL Java_packageName_moduleName_HandRolled(JNIEnv *, jclass, jlong, jstring);
%}
</pre></blockquote>

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:

<blockquote><pre>
  public final static native void HandRolled(int jarg1, String jarg2);
</pre></blockquote>

and as usual this function is wrapped by another which for a global C function would appear in the module class:

<blockquote><pre>
  public static void HandRolled(int arg0, String arg1) {
    exampleJNI.HandRolled(arg0, arg1);
  }
</pre></blockquote>

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 for <tt>int</tt> and <tt>char *</tt>.
<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.


<a name="performance"></a>
<a name="n76"></a><H3>17.11.4 Performance concerns and hints</H3>


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>

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: 

<blockquote><pre>
%typemap(javafinalize) SWIGTYPE ""
</pre></blockquote>

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 calls the C++ destructor or <tt>free()</tt> for C code.
<p>


<a name="java_examples"></a>
<a name="n77"></a><H2>17.12 Examples</H2>


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#examples">Windows Examples</a>.

</body>
</html>