File: SWIGDocumentation.html

package info (click to toggle)
swig 4.0.2-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 42,876 kB
  • sloc: cpp: 61,013; ansic: 27,612; java: 14,670; python: 10,632; cs: 8,103; makefile: 6,287; yacc: 6,197; sh: 5,247; ruby: 5,172; perl: 3,541; php: 2,069; ml: 2,066; lisp: 1,894; javascript: 1,300; tcl: 1,091; xml: 115
file content (61980 lines) | stat: -rw-r--r-- 2,370,678 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775
12776
12777
12778
12779
12780
12781
12782
12783
12784
12785
12786
12787
12788
12789
12790
12791
12792
12793
12794
12795
12796
12797
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
12808
12809
12810
12811
12812
12813
12814
12815
12816
12817
12818
12819
12820
12821
12822
12823
12824
12825
12826
12827
12828
12829
12830
12831
12832
12833
12834
12835
12836
12837
12838
12839
12840
12841
12842
12843
12844
12845
12846
12847
12848
12849
12850
12851
12852
12853
12854
12855
12856
12857
12858
12859
12860
12861
12862
12863
12864
12865
12866
12867
12868
12869
12870
12871
12872
12873
12874
12875
12876
12877
12878
12879
12880
12881
12882
12883
12884
12885
12886
12887
12888
12889
12890
12891
12892
12893
12894
12895
12896
12897
12898
12899
12900
12901
12902
12903
12904
12905
12906
12907
12908
12909
12910
12911
12912
12913
12914
12915
12916
12917
12918
12919
12920
12921
12922
12923
12924
12925
12926
12927
12928
12929
12930
12931
12932
12933
12934
12935
12936
12937
12938
12939
12940
12941
12942
12943
12944
12945
12946
12947
12948
12949
12950
12951
12952
12953
12954
12955
12956
12957
12958
12959
12960
12961
12962
12963
12964
12965
12966
12967
12968
12969
12970
12971
12972
12973
12974
12975
12976
12977
12978
12979
12980
12981
12982
12983
12984
12985
12986
12987
12988
12989
12990
12991
12992
12993
12994
12995
12996
12997
12998
12999
13000
13001
13002
13003
13004
13005
13006
13007
13008
13009
13010
13011
13012
13013
13014
13015
13016
13017
13018
13019
13020
13021
13022
13023
13024
13025
13026
13027
13028
13029
13030
13031
13032
13033
13034
13035
13036
13037
13038
13039
13040
13041
13042
13043
13044
13045
13046
13047
13048
13049
13050
13051
13052
13053
13054
13055
13056
13057
13058
13059
13060
13061
13062
13063
13064
13065
13066
13067
13068
13069
13070
13071
13072
13073
13074
13075
13076
13077
13078
13079
13080
13081
13082
13083
13084
13085
13086
13087
13088
13089
13090
13091
13092
13093
13094
13095
13096
13097
13098
13099
13100
13101
13102
13103
13104
13105
13106
13107
13108
13109
13110
13111
13112
13113
13114
13115
13116
13117
13118
13119
13120
13121
13122
13123
13124
13125
13126
13127
13128
13129
13130
13131
13132
13133
13134
13135
13136
13137
13138
13139
13140
13141
13142
13143
13144
13145
13146
13147
13148
13149
13150
13151
13152
13153
13154
13155
13156
13157
13158
13159
13160
13161
13162
13163
13164
13165
13166
13167
13168
13169
13170
13171
13172
13173
13174
13175
13176
13177
13178
13179
13180
13181
13182
13183
13184
13185
13186
13187
13188
13189
13190
13191
13192
13193
13194
13195
13196
13197
13198
13199
13200
13201
13202
13203
13204
13205
13206
13207
13208
13209
13210
13211
13212
13213
13214
13215
13216
13217
13218
13219
13220
13221
13222
13223
13224
13225
13226
13227
13228
13229
13230
13231
13232
13233
13234
13235
13236
13237
13238
13239
13240
13241
13242
13243
13244
13245
13246
13247
13248
13249
13250
13251
13252
13253
13254
13255
13256
13257
13258
13259
13260
13261
13262
13263
13264
13265
13266
13267
13268
13269
13270
13271
13272
13273
13274
13275
13276
13277
13278
13279
13280
13281
13282
13283
13284
13285
13286
13287
13288
13289
13290
13291
13292
13293
13294
13295
13296
13297
13298
13299
13300
13301
13302
13303
13304
13305
13306
13307
13308
13309
13310
13311
13312
13313
13314
13315
13316
13317
13318
13319
13320
13321
13322
13323
13324
13325
13326
13327
13328
13329
13330
13331
13332
13333
13334
13335
13336
13337
13338
13339
13340
13341
13342
13343
13344
13345
13346
13347
13348
13349
13350
13351
13352
13353
13354
13355
13356
13357
13358
13359
13360
13361
13362
13363
13364
13365
13366
13367
13368
13369
13370
13371
13372
13373
13374
13375
13376
13377
13378
13379
13380
13381
13382
13383
13384
13385
13386
13387
13388
13389
13390
13391
13392
13393
13394
13395
13396
13397
13398
13399
13400
13401
13402
13403
13404
13405
13406
13407
13408
13409
13410
13411
13412
13413
13414
13415
13416
13417
13418
13419
13420
13421
13422
13423
13424
13425
13426
13427
13428
13429
13430
13431
13432
13433
13434
13435
13436
13437
13438
13439
13440
13441
13442
13443
13444
13445
13446
13447
13448
13449
13450
13451
13452
13453
13454
13455
13456
13457
13458
13459
13460
13461
13462
13463
13464
13465
13466
13467
13468
13469
13470
13471
13472
13473
13474
13475
13476
13477
13478
13479
13480
13481
13482
13483
13484
13485
13486
13487
13488
13489
13490
13491
13492
13493
13494
13495
13496
13497
13498
13499
13500
13501
13502
13503
13504
13505
13506
13507
13508
13509
13510
13511
13512
13513
13514
13515
13516
13517
13518
13519
13520
13521
13522
13523
13524
13525
13526
13527
13528
13529
13530
13531
13532
13533
13534
13535
13536
13537
13538
13539
13540
13541
13542
13543
13544
13545
13546
13547
13548
13549
13550
13551
13552
13553
13554
13555
13556
13557
13558
13559
13560
13561
13562
13563
13564
13565
13566
13567
13568
13569
13570
13571
13572
13573
13574
13575
13576
13577
13578
13579
13580
13581
13582
13583
13584
13585
13586
13587
13588
13589
13590
13591
13592
13593
13594
13595
13596
13597
13598
13599
13600
13601
13602
13603
13604
13605
13606
13607
13608
13609
13610
13611
13612
13613
13614
13615
13616
13617
13618
13619
13620
13621
13622
13623
13624
13625
13626
13627
13628
13629
13630
13631
13632
13633
13634
13635
13636
13637
13638
13639
13640
13641
13642
13643
13644
13645
13646
13647
13648
13649
13650
13651
13652
13653
13654
13655
13656
13657
13658
13659
13660
13661
13662
13663
13664
13665
13666
13667
13668
13669
13670
13671
13672
13673
13674
13675
13676
13677
13678
13679
13680
13681
13682
13683
13684
13685
13686
13687
13688
13689
13690
13691
13692
13693
13694
13695
13696
13697
13698
13699
13700
13701
13702
13703
13704
13705
13706
13707
13708
13709
13710
13711
13712
13713
13714
13715
13716
13717
13718
13719
13720
13721
13722
13723
13724
13725
13726
13727
13728
13729
13730
13731
13732
13733
13734
13735
13736
13737
13738
13739
13740
13741
13742
13743
13744
13745
13746
13747
13748
13749
13750
13751
13752
13753
13754
13755
13756
13757
13758
13759
13760
13761
13762
13763
13764
13765
13766
13767
13768
13769
13770
13771
13772
13773
13774
13775
13776
13777
13778
13779
13780
13781
13782
13783
13784
13785
13786
13787
13788
13789
13790
13791
13792
13793
13794
13795
13796
13797
13798
13799
13800
13801
13802
13803
13804
13805
13806
13807
13808
13809
13810
13811
13812
13813
13814
13815
13816
13817
13818
13819
13820
13821
13822
13823
13824
13825
13826
13827
13828
13829
13830
13831
13832
13833
13834
13835
13836
13837
13838
13839
13840
13841
13842
13843
13844
13845
13846
13847
13848
13849
13850
13851
13852
13853
13854
13855
13856
13857
13858
13859
13860
13861
13862
13863
13864
13865
13866
13867
13868
13869
13870
13871
13872
13873
13874
13875
13876
13877
13878
13879
13880
13881
13882
13883
13884
13885
13886
13887
13888
13889
13890
13891
13892
13893
13894
13895
13896
13897
13898
13899
13900
13901
13902
13903
13904
13905
13906
13907
13908
13909
13910
13911
13912
13913
13914
13915
13916
13917
13918
13919
13920
13921
13922
13923
13924
13925
13926
13927
13928
13929
13930
13931
13932
13933
13934
13935
13936
13937
13938
13939
13940
13941
13942
13943
13944
13945
13946
13947
13948
13949
13950
13951
13952
13953
13954
13955
13956
13957
13958
13959
13960
13961
13962
13963
13964
13965
13966
13967
13968
13969
13970
13971
13972
13973
13974
13975
13976
13977
13978
13979
13980
13981
13982
13983
13984
13985
13986
13987
13988
13989
13990
13991
13992
13993
13994
13995
13996
13997
13998
13999
14000
14001
14002
14003
14004
14005
14006
14007
14008
14009
14010
14011
14012
14013
14014
14015
14016
14017
14018
14019
14020
14021
14022
14023
14024
14025
14026
14027
14028
14029
14030
14031
14032
14033
14034
14035
14036
14037
14038
14039
14040
14041
14042
14043
14044
14045
14046
14047
14048
14049
14050
14051
14052
14053
14054
14055
14056
14057
14058
14059
14060
14061
14062
14063
14064
14065
14066
14067
14068
14069
14070
14071
14072
14073
14074
14075
14076
14077
14078
14079
14080
14081
14082
14083
14084
14085
14086
14087
14088
14089
14090
14091
14092
14093
14094
14095
14096
14097
14098
14099
14100
14101
14102
14103
14104
14105
14106
14107
14108
14109
14110
14111
14112
14113
14114
14115
14116
14117
14118
14119
14120
14121
14122
14123
14124
14125
14126
14127
14128
14129
14130
14131
14132
14133
14134
14135
14136
14137
14138
14139
14140
14141
14142
14143
14144
14145
14146
14147
14148
14149
14150
14151
14152
14153
14154
14155
14156
14157
14158
14159
14160
14161
14162
14163
14164
14165
14166
14167
14168
14169
14170
14171
14172
14173
14174
14175
14176
14177
14178
14179
14180
14181
14182
14183
14184
14185
14186
14187
14188
14189
14190
14191
14192
14193
14194
14195
14196
14197
14198
14199
14200
14201
14202
14203
14204
14205
14206
14207
14208
14209
14210
14211
14212
14213
14214
14215
14216
14217
14218
14219
14220
14221
14222
14223
14224
14225
14226
14227
14228
14229
14230
14231
14232
14233
14234
14235
14236
14237
14238
14239
14240
14241
14242
14243
14244
14245
14246
14247
14248
14249
14250
14251
14252
14253
14254
14255
14256
14257
14258
14259
14260
14261
14262
14263
14264
14265
14266
14267
14268
14269
14270
14271
14272
14273
14274
14275
14276
14277
14278
14279
14280
14281
14282
14283
14284
14285
14286
14287
14288
14289
14290
14291
14292
14293
14294
14295
14296
14297
14298
14299
14300
14301
14302
14303
14304
14305
14306
14307
14308
14309
14310
14311
14312
14313
14314
14315
14316
14317
14318
14319
14320
14321
14322
14323
14324
14325
14326
14327
14328
14329
14330
14331
14332
14333
14334
14335
14336
14337
14338
14339
14340
14341
14342
14343
14344
14345
14346
14347
14348
14349
14350
14351
14352
14353
14354
14355
14356
14357
14358
14359
14360
14361
14362
14363
14364
14365
14366
14367
14368
14369
14370
14371
14372
14373
14374
14375
14376
14377
14378
14379
14380
14381
14382
14383
14384
14385
14386
14387
14388
14389
14390
14391
14392
14393
14394
14395
14396
14397
14398
14399
14400
14401
14402
14403
14404
14405
14406
14407
14408
14409
14410
14411
14412
14413
14414
14415
14416
14417
14418
14419
14420
14421
14422
14423
14424
14425
14426
14427
14428
14429
14430
14431
14432
14433
14434
14435
14436
14437
14438
14439
14440
14441
14442
14443
14444
14445
14446
14447
14448
14449
14450
14451
14452
14453
14454
14455
14456
14457
14458
14459
14460
14461
14462
14463
14464
14465
14466
14467
14468
14469
14470
14471
14472
14473
14474
14475
14476
14477
14478
14479
14480
14481
14482
14483
14484
14485
14486
14487
14488
14489
14490
14491
14492
14493
14494
14495
14496
14497
14498
14499
14500
14501
14502
14503
14504
14505
14506
14507
14508
14509
14510
14511
14512
14513
14514
14515
14516
14517
14518
14519
14520
14521
14522
14523
14524
14525
14526
14527
14528
14529
14530
14531
14532
14533
14534
14535
14536
14537
14538
14539
14540
14541
14542
14543
14544
14545
14546
14547
14548
14549
14550
14551
14552
14553
14554
14555
14556
14557
14558
14559
14560
14561
14562
14563
14564
14565
14566
14567
14568
14569
14570
14571
14572
14573
14574
14575
14576
14577
14578
14579
14580
14581
14582
14583
14584
14585
14586
14587
14588
14589
14590
14591
14592
14593
14594
14595
14596
14597
14598
14599
14600
14601
14602
14603
14604
14605
14606
14607
14608
14609
14610
14611
14612
14613
14614
14615
14616
14617
14618
14619
14620
14621
14622
14623
14624
14625
14626
14627
14628
14629
14630
14631
14632
14633
14634
14635
14636
14637
14638
14639
14640
14641
14642
14643
14644
14645
14646
14647
14648
14649
14650
14651
14652
14653
14654
14655
14656
14657
14658
14659
14660
14661
14662
14663
14664
14665
14666
14667
14668
14669
14670
14671
14672
14673
14674
14675
14676
14677
14678
14679
14680
14681
14682
14683
14684
14685
14686
14687
14688
14689
14690
14691
14692
14693
14694
14695
14696
14697
14698
14699
14700
14701
14702
14703
14704
14705
14706
14707
14708
14709
14710
14711
14712
14713
14714
14715
14716
14717
14718
14719
14720
14721
14722
14723
14724
14725
14726
14727
14728
14729
14730
14731
14732
14733
14734
14735
14736
14737
14738
14739
14740
14741
14742
14743
14744
14745
14746
14747
14748
14749
14750
14751
14752
14753
14754
14755
14756
14757
14758
14759
14760
14761
14762
14763
14764
14765
14766
14767
14768
14769
14770
14771
14772
14773
14774
14775
14776
14777
14778
14779
14780
14781
14782
14783
14784
14785
14786
14787
14788
14789
14790
14791
14792
14793
14794
14795
14796
14797
14798
14799
14800
14801
14802
14803
14804
14805
14806
14807
14808
14809
14810
14811
14812
14813
14814
14815
14816
14817
14818
14819
14820
14821
14822
14823
14824
14825
14826
14827
14828
14829
14830
14831
14832
14833
14834
14835
14836
14837
14838
14839
14840
14841
14842
14843
14844
14845
14846
14847
14848
14849
14850
14851
14852
14853
14854
14855
14856
14857
14858
14859
14860
14861
14862
14863
14864
14865
14866
14867
14868
14869
14870
14871
14872
14873
14874
14875
14876
14877
14878
14879
14880
14881
14882
14883
14884
14885
14886
14887
14888
14889
14890
14891
14892
14893
14894
14895
14896
14897
14898
14899
14900
14901
14902
14903
14904
14905
14906
14907
14908
14909
14910
14911
14912
14913
14914
14915
14916
14917
14918
14919
14920
14921
14922
14923
14924
14925
14926
14927
14928
14929
14930
14931
14932
14933
14934
14935
14936
14937
14938
14939
14940
14941
14942
14943
14944
14945
14946
14947
14948
14949
14950
14951
14952
14953
14954
14955
14956
14957
14958
14959
14960
14961
14962
14963
14964
14965
14966
14967
14968
14969
14970
14971
14972
14973
14974
14975
14976
14977
14978
14979
14980
14981
14982
14983
14984
14985
14986
14987
14988
14989
14990
14991
14992
14993
14994
14995
14996
14997
14998
14999
15000
15001
15002
15003
15004
15005
15006
15007
15008
15009
15010
15011
15012
15013
15014
15015
15016
15017
15018
15019
15020
15021
15022
15023
15024
15025
15026
15027
15028
15029
15030
15031
15032
15033
15034
15035
15036
15037
15038
15039
15040
15041
15042
15043
15044
15045
15046
15047
15048
15049
15050
15051
15052
15053
15054
15055
15056
15057
15058
15059
15060
15061
15062
15063
15064
15065
15066
15067
15068
15069
15070
15071
15072
15073
15074
15075
15076
15077
15078
15079
15080
15081
15082
15083
15084
15085
15086
15087
15088
15089
15090
15091
15092
15093
15094
15095
15096
15097
15098
15099
15100
15101
15102
15103
15104
15105
15106
15107
15108
15109
15110
15111
15112
15113
15114
15115
15116
15117
15118
15119
15120
15121
15122
15123
15124
15125
15126
15127
15128
15129
15130
15131
15132
15133
15134
15135
15136
15137
15138
15139
15140
15141
15142
15143
15144
15145
15146
15147
15148
15149
15150
15151
15152
15153
15154
15155
15156
15157
15158
15159
15160
15161
15162
15163
15164
15165
15166
15167
15168
15169
15170
15171
15172
15173
15174
15175
15176
15177
15178
15179
15180
15181
15182
15183
15184
15185
15186
15187
15188
15189
15190
15191
15192
15193
15194
15195
15196
15197
15198
15199
15200
15201
15202
15203
15204
15205
15206
15207
15208
15209
15210
15211
15212
15213
15214
15215
15216
15217
15218
15219
15220
15221
15222
15223
15224
15225
15226
15227
15228
15229
15230
15231
15232
15233
15234
15235
15236
15237
15238
15239
15240
15241
15242
15243
15244
15245
15246
15247
15248
15249
15250
15251
15252
15253
15254
15255
15256
15257
15258
15259
15260
15261
15262
15263
15264
15265
15266
15267
15268
15269
15270
15271
15272
15273
15274
15275
15276
15277
15278
15279
15280
15281
15282
15283
15284
15285
15286
15287
15288
15289
15290
15291
15292
15293
15294
15295
15296
15297
15298
15299
15300
15301
15302
15303
15304
15305
15306
15307
15308
15309
15310
15311
15312
15313
15314
15315
15316
15317
15318
15319
15320
15321
15322
15323
15324
15325
15326
15327
15328
15329
15330
15331
15332
15333
15334
15335
15336
15337
15338
15339
15340
15341
15342
15343
15344
15345
15346
15347
15348
15349
15350
15351
15352
15353
15354
15355
15356
15357
15358
15359
15360
15361
15362
15363
15364
15365
15366
15367
15368
15369
15370
15371
15372
15373
15374
15375
15376
15377
15378
15379
15380
15381
15382
15383
15384
15385
15386
15387
15388
15389
15390
15391
15392
15393
15394
15395
15396
15397
15398
15399
15400
15401
15402
15403
15404
15405
15406
15407
15408
15409
15410
15411
15412
15413
15414
15415
15416
15417
15418
15419
15420
15421
15422
15423
15424
15425
15426
15427
15428
15429
15430
15431
15432
15433
15434
15435
15436
15437
15438
15439
15440
15441
15442
15443
15444
15445
15446
15447
15448
15449
15450
15451
15452
15453
15454
15455
15456
15457
15458
15459
15460
15461
15462
15463
15464
15465
15466
15467
15468
15469
15470
15471
15472
15473
15474
15475
15476
15477
15478
15479
15480
15481
15482
15483
15484
15485
15486
15487
15488
15489
15490
15491
15492
15493
15494
15495
15496
15497
15498
15499
15500
15501
15502
15503
15504
15505
15506
15507
15508
15509
15510
15511
15512
15513
15514
15515
15516
15517
15518
15519
15520
15521
15522
15523
15524
15525
15526
15527
15528
15529
15530
15531
15532
15533
15534
15535
15536
15537
15538
15539
15540
15541
15542
15543
15544
15545
15546
15547
15548
15549
15550
15551
15552
15553
15554
15555
15556
15557
15558
15559
15560
15561
15562
15563
15564
15565
15566
15567
15568
15569
15570
15571
15572
15573
15574
15575
15576
15577
15578
15579
15580
15581
15582
15583
15584
15585
15586
15587
15588
15589
15590
15591
15592
15593
15594
15595
15596
15597
15598
15599
15600
15601
15602
15603
15604
15605
15606
15607
15608
15609
15610
15611
15612
15613
15614
15615
15616
15617
15618
15619
15620
15621
15622
15623
15624
15625
15626
15627
15628
15629
15630
15631
15632
15633
15634
15635
15636
15637
15638
15639
15640
15641
15642
15643
15644
15645
15646
15647
15648
15649
15650
15651
15652
15653
15654
15655
15656
15657
15658
15659
15660
15661
15662
15663
15664
15665
15666
15667
15668
15669
15670
15671
15672
15673
15674
15675
15676
15677
15678
15679
15680
15681
15682
15683
15684
15685
15686
15687
15688
15689
15690
15691
15692
15693
15694
15695
15696
15697
15698
15699
15700
15701
15702
15703
15704
15705
15706
15707
15708
15709
15710
15711
15712
15713
15714
15715
15716
15717
15718
15719
15720
15721
15722
15723
15724
15725
15726
15727
15728
15729
15730
15731
15732
15733
15734
15735
15736
15737
15738
15739
15740
15741
15742
15743
15744
15745
15746
15747
15748
15749
15750
15751
15752
15753
15754
15755
15756
15757
15758
15759
15760
15761
15762
15763
15764
15765
15766
15767
15768
15769
15770
15771
15772
15773
15774
15775
15776
15777
15778
15779
15780
15781
15782
15783
15784
15785
15786
15787
15788
15789
15790
15791
15792
15793
15794
15795
15796
15797
15798
15799
15800
15801
15802
15803
15804
15805
15806
15807
15808
15809
15810
15811
15812
15813
15814
15815
15816
15817
15818
15819
15820
15821
15822
15823
15824
15825
15826
15827
15828
15829
15830
15831
15832
15833
15834
15835
15836
15837
15838
15839
15840
15841
15842
15843
15844
15845
15846
15847
15848
15849
15850
15851
15852
15853
15854
15855
15856
15857
15858
15859
15860
15861
15862
15863
15864
15865
15866
15867
15868
15869
15870
15871
15872
15873
15874
15875
15876
15877
15878
15879
15880
15881
15882
15883
15884
15885
15886
15887
15888
15889
15890
15891
15892
15893
15894
15895
15896
15897
15898
15899
15900
15901
15902
15903
15904
15905
15906
15907
15908
15909
15910
15911
15912
15913
15914
15915
15916
15917
15918
15919
15920
15921
15922
15923
15924
15925
15926
15927
15928
15929
15930
15931
15932
15933
15934
15935
15936
15937
15938
15939
15940
15941
15942
15943
15944
15945
15946
15947
15948
15949
15950
15951
15952
15953
15954
15955
15956
15957
15958
15959
15960
15961
15962
15963
15964
15965
15966
15967
15968
15969
15970
15971
15972
15973
15974
15975
15976
15977
15978
15979
15980
15981
15982
15983
15984
15985
15986
15987
15988
15989
15990
15991
15992
15993
15994
15995
15996
15997
15998
15999
16000
16001
16002
16003
16004
16005
16006
16007
16008
16009
16010
16011
16012
16013
16014
16015
16016
16017
16018
16019
16020
16021
16022
16023
16024
16025
16026
16027
16028
16029
16030
16031
16032
16033
16034
16035
16036
16037
16038
16039
16040
16041
16042
16043
16044
16045
16046
16047
16048
16049
16050
16051
16052
16053
16054
16055
16056
16057
16058
16059
16060
16061
16062
16063
16064
16065
16066
16067
16068
16069
16070
16071
16072
16073
16074
16075
16076
16077
16078
16079
16080
16081
16082
16083
16084
16085
16086
16087
16088
16089
16090
16091
16092
16093
16094
16095
16096
16097
16098
16099
16100
16101
16102
16103
16104
16105
16106
16107
16108
16109
16110
16111
16112
16113
16114
16115
16116
16117
16118
16119
16120
16121
16122
16123
16124
16125
16126
16127
16128
16129
16130
16131
16132
16133
16134
16135
16136
16137
16138
16139
16140
16141
16142
16143
16144
16145
16146
16147
16148
16149
16150
16151
16152
16153
16154
16155
16156
16157
16158
16159
16160
16161
16162
16163
16164
16165
16166
16167
16168
16169
16170
16171
16172
16173
16174
16175
16176
16177
16178
16179
16180
16181
16182
16183
16184
16185
16186
16187
16188
16189
16190
16191
16192
16193
16194
16195
16196
16197
16198
16199
16200
16201
16202
16203
16204
16205
16206
16207
16208
16209
16210
16211
16212
16213
16214
16215
16216
16217
16218
16219
16220
16221
16222
16223
16224
16225
16226
16227
16228
16229
16230
16231
16232
16233
16234
16235
16236
16237
16238
16239
16240
16241
16242
16243
16244
16245
16246
16247
16248
16249
16250
16251
16252
16253
16254
16255
16256
16257
16258
16259
16260
16261
16262
16263
16264
16265
16266
16267
16268
16269
16270
16271
16272
16273
16274
16275
16276
16277
16278
16279
16280
16281
16282
16283
16284
16285
16286
16287
16288
16289
16290
16291
16292
16293
16294
16295
16296
16297
16298
16299
16300
16301
16302
16303
16304
16305
16306
16307
16308
16309
16310
16311
16312
16313
16314
16315
16316
16317
16318
16319
16320
16321
16322
16323
16324
16325
16326
16327
16328
16329
16330
16331
16332
16333
16334
16335
16336
16337
16338
16339
16340
16341
16342
16343
16344
16345
16346
16347
16348
16349
16350
16351
16352
16353
16354
16355
16356
16357
16358
16359
16360
16361
16362
16363
16364
16365
16366
16367
16368
16369
16370
16371
16372
16373
16374
16375
16376
16377
16378
16379
16380
16381
16382
16383
16384
16385
16386
16387
16388
16389
16390
16391
16392
16393
16394
16395
16396
16397
16398
16399
16400
16401
16402
16403
16404
16405
16406
16407
16408
16409
16410
16411
16412
16413
16414
16415
16416
16417
16418
16419
16420
16421
16422
16423
16424
16425
16426
16427
16428
16429
16430
16431
16432
16433
16434
16435
16436
16437
16438
16439
16440
16441
16442
16443
16444
16445
16446
16447
16448
16449
16450
16451
16452
16453
16454
16455
16456
16457
16458
16459
16460
16461
16462
16463
16464
16465
16466
16467
16468
16469
16470
16471
16472
16473
16474
16475
16476
16477
16478
16479
16480
16481
16482
16483
16484
16485
16486
16487
16488
16489
16490
16491
16492
16493
16494
16495
16496
16497
16498
16499
16500
16501
16502
16503
16504
16505
16506
16507
16508
16509
16510
16511
16512
16513
16514
16515
16516
16517
16518
16519
16520
16521
16522
16523
16524
16525
16526
16527
16528
16529
16530
16531
16532
16533
16534
16535
16536
16537
16538
16539
16540
16541
16542
16543
16544
16545
16546
16547
16548
16549
16550
16551
16552
16553
16554
16555
16556
16557
16558
16559
16560
16561
16562
16563
16564
16565
16566
16567
16568
16569
16570
16571
16572
16573
16574
16575
16576
16577
16578
16579
16580
16581
16582
16583
16584
16585
16586
16587
16588
16589
16590
16591
16592
16593
16594
16595
16596
16597
16598
16599
16600
16601
16602
16603
16604
16605
16606
16607
16608
16609
16610
16611
16612
16613
16614
16615
16616
16617
16618
16619
16620
16621
16622
16623
16624
16625
16626
16627
16628
16629
16630
16631
16632
16633
16634
16635
16636
16637
16638
16639
16640
16641
16642
16643
16644
16645
16646
16647
16648
16649
16650
16651
16652
16653
16654
16655
16656
16657
16658
16659
16660
16661
16662
16663
16664
16665
16666
16667
16668
16669
16670
16671
16672
16673
16674
16675
16676
16677
16678
16679
16680
16681
16682
16683
16684
16685
16686
16687
16688
16689
16690
16691
16692
16693
16694
16695
16696
16697
16698
16699
16700
16701
16702
16703
16704
16705
16706
16707
16708
16709
16710
16711
16712
16713
16714
16715
16716
16717
16718
16719
16720
16721
16722
16723
16724
16725
16726
16727
16728
16729
16730
16731
16732
16733
16734
16735
16736
16737
16738
16739
16740
16741
16742
16743
16744
16745
16746
16747
16748
16749
16750
16751
16752
16753
16754
16755
16756
16757
16758
16759
16760
16761
16762
16763
16764
16765
16766
16767
16768
16769
16770
16771
16772
16773
16774
16775
16776
16777
16778
16779
16780
16781
16782
16783
16784
16785
16786
16787
16788
16789
16790
16791
16792
16793
16794
16795
16796
16797
16798
16799
16800
16801
16802
16803
16804
16805
16806
16807
16808
16809
16810
16811
16812
16813
16814
16815
16816
16817
16818
16819
16820
16821
16822
16823
16824
16825
16826
16827
16828
16829
16830
16831
16832
16833
16834
16835
16836
16837
16838
16839
16840
16841
16842
16843
16844
16845
16846
16847
16848
16849
16850
16851
16852
16853
16854
16855
16856
16857
16858
16859
16860
16861
16862
16863
16864
16865
16866
16867
16868
16869
16870
16871
16872
16873
16874
16875
16876
16877
16878
16879
16880
16881
16882
16883
16884
16885
16886
16887
16888
16889
16890
16891
16892
16893
16894
16895
16896
16897
16898
16899
16900
16901
16902
16903
16904
16905
16906
16907
16908
16909
16910
16911
16912
16913
16914
16915
16916
16917
16918
16919
16920
16921
16922
16923
16924
16925
16926
16927
16928
16929
16930
16931
16932
16933
16934
16935
16936
16937
16938
16939
16940
16941
16942
16943
16944
16945
16946
16947
16948
16949
16950
16951
16952
16953
16954
16955
16956
16957
16958
16959
16960
16961
16962
16963
16964
16965
16966
16967
16968
16969
16970
16971
16972
16973
16974
16975
16976
16977
16978
16979
16980
16981
16982
16983
16984
16985
16986
16987
16988
16989
16990
16991
16992
16993
16994
16995
16996
16997
16998
16999
17000
17001
17002
17003
17004
17005
17006
17007
17008
17009
17010
17011
17012
17013
17014
17015
17016
17017
17018
17019
17020
17021
17022
17023
17024
17025
17026
17027
17028
17029
17030
17031
17032
17033
17034
17035
17036
17037
17038
17039
17040
17041
17042
17043
17044
17045
17046
17047
17048
17049
17050
17051
17052
17053
17054
17055
17056
17057
17058
17059
17060
17061
17062
17063
17064
17065
17066
17067
17068
17069
17070
17071
17072
17073
17074
17075
17076
17077
17078
17079
17080
17081
17082
17083
17084
17085
17086
17087
17088
17089
17090
17091
17092
17093
17094
17095
17096
17097
17098
17099
17100
17101
17102
17103
17104
17105
17106
17107
17108
17109
17110
17111
17112
17113
17114
17115
17116
17117
17118
17119
17120
17121
17122
17123
17124
17125
17126
17127
17128
17129
17130
17131
17132
17133
17134
17135
17136
17137
17138
17139
17140
17141
17142
17143
17144
17145
17146
17147
17148
17149
17150
17151
17152
17153
17154
17155
17156
17157
17158
17159
17160
17161
17162
17163
17164
17165
17166
17167
17168
17169
17170
17171
17172
17173
17174
17175
17176
17177
17178
17179
17180
17181
17182
17183
17184
17185
17186
17187
17188
17189
17190
17191
17192
17193
17194
17195
17196
17197
17198
17199
17200
17201
17202
17203
17204
17205
17206
17207
17208
17209
17210
17211
17212
17213
17214
17215
17216
17217
17218
17219
17220
17221
17222
17223
17224
17225
17226
17227
17228
17229
17230
17231
17232
17233
17234
17235
17236
17237
17238
17239
17240
17241
17242
17243
17244
17245
17246
17247
17248
17249
17250
17251
17252
17253
17254
17255
17256
17257
17258
17259
17260
17261
17262
17263
17264
17265
17266
17267
17268
17269
17270
17271
17272
17273
17274
17275
17276
17277
17278
17279
17280
17281
17282
17283
17284
17285
17286
17287
17288
17289
17290
17291
17292
17293
17294
17295
17296
17297
17298
17299
17300
17301
17302
17303
17304
17305
17306
17307
17308
17309
17310
17311
17312
17313
17314
17315
17316
17317
17318
17319
17320
17321
17322
17323
17324
17325
17326
17327
17328
17329
17330
17331
17332
17333
17334
17335
17336
17337
17338
17339
17340
17341
17342
17343
17344
17345
17346
17347
17348
17349
17350
17351
17352
17353
17354
17355
17356
17357
17358
17359
17360
17361
17362
17363
17364
17365
17366
17367
17368
17369
17370
17371
17372
17373
17374
17375
17376
17377
17378
17379
17380
17381
17382
17383
17384
17385
17386
17387
17388
17389
17390
17391
17392
17393
17394
17395
17396
17397
17398
17399
17400
17401
17402
17403
17404
17405
17406
17407
17408
17409
17410
17411
17412
17413
17414
17415
17416
17417
17418
17419
17420
17421
17422
17423
17424
17425
17426
17427
17428
17429
17430
17431
17432
17433
17434
17435
17436
17437
17438
17439
17440
17441
17442
17443
17444
17445
17446
17447
17448
17449
17450
17451
17452
17453
17454
17455
17456
17457
17458
17459
17460
17461
17462
17463
17464
17465
17466
17467
17468
17469
17470
17471
17472
17473
17474
17475
17476
17477
17478
17479
17480
17481
17482
17483
17484
17485
17486
17487
17488
17489
17490
17491
17492
17493
17494
17495
17496
17497
17498
17499
17500
17501
17502
17503
17504
17505
17506
17507
17508
17509
17510
17511
17512
17513
17514
17515
17516
17517
17518
17519
17520
17521
17522
17523
17524
17525
17526
17527
17528
17529
17530
17531
17532
17533
17534
17535
17536
17537
17538
17539
17540
17541
17542
17543
17544
17545
17546
17547
17548
17549
17550
17551
17552
17553
17554
17555
17556
17557
17558
17559
17560
17561
17562
17563
17564
17565
17566
17567
17568
17569
17570
17571
17572
17573
17574
17575
17576
17577
17578
17579
17580
17581
17582
17583
17584
17585
17586
17587
17588
17589
17590
17591
17592
17593
17594
17595
17596
17597
17598
17599
17600
17601
17602
17603
17604
17605
17606
17607
17608
17609
17610
17611
17612
17613
17614
17615
17616
17617
17618
17619
17620
17621
17622
17623
17624
17625
17626
17627
17628
17629
17630
17631
17632
17633
17634
17635
17636
17637
17638
17639
17640
17641
17642
17643
17644
17645
17646
17647
17648
17649
17650
17651
17652
17653
17654
17655
17656
17657
17658
17659
17660
17661
17662
17663
17664
17665
17666
17667
17668
17669
17670
17671
17672
17673
17674
17675
17676
17677
17678
17679
17680
17681
17682
17683
17684
17685
17686
17687
17688
17689
17690
17691
17692
17693
17694
17695
17696
17697
17698
17699
17700
17701
17702
17703
17704
17705
17706
17707
17708
17709
17710
17711
17712
17713
17714
17715
17716
17717
17718
17719
17720
17721
17722
17723
17724
17725
17726
17727
17728
17729
17730
17731
17732
17733
17734
17735
17736
17737
17738
17739
17740
17741
17742
17743
17744
17745
17746
17747
17748
17749
17750
17751
17752
17753
17754
17755
17756
17757
17758
17759
17760
17761
17762
17763
17764
17765
17766
17767
17768
17769
17770
17771
17772
17773
17774
17775
17776
17777
17778
17779
17780
17781
17782
17783
17784
17785
17786
17787
17788
17789
17790
17791
17792
17793
17794
17795
17796
17797
17798
17799
17800
17801
17802
17803
17804
17805
17806
17807
17808
17809
17810
17811
17812
17813
17814
17815
17816
17817
17818
17819
17820
17821
17822
17823
17824
17825
17826
17827
17828
17829
17830
17831
17832
17833
17834
17835
17836
17837
17838
17839
17840
17841
17842
17843
17844
17845
17846
17847
17848
17849
17850
17851
17852
17853
17854
17855
17856
17857
17858
17859
17860
17861
17862
17863
17864
17865
17866
17867
17868
17869
17870
17871
17872
17873
17874
17875
17876
17877
17878
17879
17880
17881
17882
17883
17884
17885
17886
17887
17888
17889
17890
17891
17892
17893
17894
17895
17896
17897
17898
17899
17900
17901
17902
17903
17904
17905
17906
17907
17908
17909
17910
17911
17912
17913
17914
17915
17916
17917
17918
17919
17920
17921
17922
17923
17924
17925
17926
17927
17928
17929
17930
17931
17932
17933
17934
17935
17936
17937
17938
17939
17940
17941
17942
17943
17944
17945
17946
17947
17948
17949
17950
17951
17952
17953
17954
17955
17956
17957
17958
17959
17960
17961
17962
17963
17964
17965
17966
17967
17968
17969
17970
17971
17972
17973
17974
17975
17976
17977
17978
17979
17980
17981
17982
17983
17984
17985
17986
17987
17988
17989
17990
17991
17992
17993
17994
17995
17996
17997
17998
17999
18000
18001
18002
18003
18004
18005
18006
18007
18008
18009
18010
18011
18012
18013
18014
18015
18016
18017
18018
18019
18020
18021
18022
18023
18024
18025
18026
18027
18028
18029
18030
18031
18032
18033
18034
18035
18036
18037
18038
18039
18040
18041
18042
18043
18044
18045
18046
18047
18048
18049
18050
18051
18052
18053
18054
18055
18056
18057
18058
18059
18060
18061
18062
18063
18064
18065
18066
18067
18068
18069
18070
18071
18072
18073
18074
18075
18076
18077
18078
18079
18080
18081
18082
18083
18084
18085
18086
18087
18088
18089
18090
18091
18092
18093
18094
18095
18096
18097
18098
18099
18100
18101
18102
18103
18104
18105
18106
18107
18108
18109
18110
18111
18112
18113
18114
18115
18116
18117
18118
18119
18120
18121
18122
18123
18124
18125
18126
18127
18128
18129
18130
18131
18132
18133
18134
18135
18136
18137
18138
18139
18140
18141
18142
18143
18144
18145
18146
18147
18148
18149
18150
18151
18152
18153
18154
18155
18156
18157
18158
18159
18160
18161
18162
18163
18164
18165
18166
18167
18168
18169
18170
18171
18172
18173
18174
18175
18176
18177
18178
18179
18180
18181
18182
18183
18184
18185
18186
18187
18188
18189
18190
18191
18192
18193
18194
18195
18196
18197
18198
18199
18200
18201
18202
18203
18204
18205
18206
18207
18208
18209
18210
18211
18212
18213
18214
18215
18216
18217
18218
18219
18220
18221
18222
18223
18224
18225
18226
18227
18228
18229
18230
18231
18232
18233
18234
18235
18236
18237
18238
18239
18240
18241
18242
18243
18244
18245
18246
18247
18248
18249
18250
18251
18252
18253
18254
18255
18256
18257
18258
18259
18260
18261
18262
18263
18264
18265
18266
18267
18268
18269
18270
18271
18272
18273
18274
18275
18276
18277
18278
18279
18280
18281
18282
18283
18284
18285
18286
18287
18288
18289
18290
18291
18292
18293
18294
18295
18296
18297
18298
18299
18300
18301
18302
18303
18304
18305
18306
18307
18308
18309
18310
18311
18312
18313
18314
18315
18316
18317
18318
18319
18320
18321
18322
18323
18324
18325
18326
18327
18328
18329
18330
18331
18332
18333
18334
18335
18336
18337
18338
18339
18340
18341
18342
18343
18344
18345
18346
18347
18348
18349
18350
18351
18352
18353
18354
18355
18356
18357
18358
18359
18360
18361
18362
18363
18364
18365
18366
18367
18368
18369
18370
18371
18372
18373
18374
18375
18376
18377
18378
18379
18380
18381
18382
18383
18384
18385
18386
18387
18388
18389
18390
18391
18392
18393
18394
18395
18396
18397
18398
18399
18400
18401
18402
18403
18404
18405
18406
18407
18408
18409
18410
18411
18412
18413
18414
18415
18416
18417
18418
18419
18420
18421
18422
18423
18424
18425
18426
18427
18428
18429
18430
18431
18432
18433
18434
18435
18436
18437
18438
18439
18440
18441
18442
18443
18444
18445
18446
18447
18448
18449
18450
18451
18452
18453
18454
18455
18456
18457
18458
18459
18460
18461
18462
18463
18464
18465
18466
18467
18468
18469
18470
18471
18472
18473
18474
18475
18476
18477
18478
18479
18480
18481
18482
18483
18484
18485
18486
18487
18488
18489
18490
18491
18492
18493
18494
18495
18496
18497
18498
18499
18500
18501
18502
18503
18504
18505
18506
18507
18508
18509
18510
18511
18512
18513
18514
18515
18516
18517
18518
18519
18520
18521
18522
18523
18524
18525
18526
18527
18528
18529
18530
18531
18532
18533
18534
18535
18536
18537
18538
18539
18540
18541
18542
18543
18544
18545
18546
18547
18548
18549
18550
18551
18552
18553
18554
18555
18556
18557
18558
18559
18560
18561
18562
18563
18564
18565
18566
18567
18568
18569
18570
18571
18572
18573
18574
18575
18576
18577
18578
18579
18580
18581
18582
18583
18584
18585
18586
18587
18588
18589
18590
18591
18592
18593
18594
18595
18596
18597
18598
18599
18600
18601
18602
18603
18604
18605
18606
18607
18608
18609
18610
18611
18612
18613
18614
18615
18616
18617
18618
18619
18620
18621
18622
18623
18624
18625
18626
18627
18628
18629
18630
18631
18632
18633
18634
18635
18636
18637
18638
18639
18640
18641
18642
18643
18644
18645
18646
18647
18648
18649
18650
18651
18652
18653
18654
18655
18656
18657
18658
18659
18660
18661
18662
18663
18664
18665
18666
18667
18668
18669
18670
18671
18672
18673
18674
18675
18676
18677
18678
18679
18680
18681
18682
18683
18684
18685
18686
18687
18688
18689
18690
18691
18692
18693
18694
18695
18696
18697
18698
18699
18700
18701
18702
18703
18704
18705
18706
18707
18708
18709
18710
18711
18712
18713
18714
18715
18716
18717
18718
18719
18720
18721
18722
18723
18724
18725
18726
18727
18728
18729
18730
18731
18732
18733
18734
18735
18736
18737
18738
18739
18740
18741
18742
18743
18744
18745
18746
18747
18748
18749
18750
18751
18752
18753
18754
18755
18756
18757
18758
18759
18760
18761
18762
18763
18764
18765
18766
18767
18768
18769
18770
18771
18772
18773
18774
18775
18776
18777
18778
18779
18780
18781
18782
18783
18784
18785
18786
18787
18788
18789
18790
18791
18792
18793
18794
18795
18796
18797
18798
18799
18800
18801
18802
18803
18804
18805
18806
18807
18808
18809
18810
18811
18812
18813
18814
18815
18816
18817
18818
18819
18820
18821
18822
18823
18824
18825
18826
18827
18828
18829
18830
18831
18832
18833
18834
18835
18836
18837
18838
18839
18840
18841
18842
18843
18844
18845
18846
18847
18848
18849
18850
18851
18852
18853
18854
18855
18856
18857
18858
18859
18860
18861
18862
18863
18864
18865
18866
18867
18868
18869
18870
18871
18872
18873
18874
18875
18876
18877
18878
18879
18880
18881
18882
18883
18884
18885
18886
18887
18888
18889
18890
18891
18892
18893
18894
18895
18896
18897
18898
18899
18900
18901
18902
18903
18904
18905
18906
18907
18908
18909
18910
18911
18912
18913
18914
18915
18916
18917
18918
18919
18920
18921
18922
18923
18924
18925
18926
18927
18928
18929
18930
18931
18932
18933
18934
18935
18936
18937
18938
18939
18940
18941
18942
18943
18944
18945
18946
18947
18948
18949
18950
18951
18952
18953
18954
18955
18956
18957
18958
18959
18960
18961
18962
18963
18964
18965
18966
18967
18968
18969
18970
18971
18972
18973
18974
18975
18976
18977
18978
18979
18980
18981
18982
18983
18984
18985
18986
18987
18988
18989
18990
18991
18992
18993
18994
18995
18996
18997
18998
18999
19000
19001
19002
19003
19004
19005
19006
19007
19008
19009
19010
19011
19012
19013
19014
19015
19016
19017
19018
19019
19020
19021
19022
19023
19024
19025
19026
19027
19028
19029
19030
19031
19032
19033
19034
19035
19036
19037
19038
19039
19040
19041
19042
19043
19044
19045
19046
19047
19048
19049
19050
19051
19052
19053
19054
19055
19056
19057
19058
19059
19060
19061
19062
19063
19064
19065
19066
19067
19068
19069
19070
19071
19072
19073
19074
19075
19076
19077
19078
19079
19080
19081
19082
19083
19084
19085
19086
19087
19088
19089
19090
19091
19092
19093
19094
19095
19096
19097
19098
19099
19100
19101
19102
19103
19104
19105
19106
19107
19108
19109
19110
19111
19112
19113
19114
19115
19116
19117
19118
19119
19120
19121
19122
19123
19124
19125
19126
19127
19128
19129
19130
19131
19132
19133
19134
19135
19136
19137
19138
19139
19140
19141
19142
19143
19144
19145
19146
19147
19148
19149
19150
19151
19152
19153
19154
19155
19156
19157
19158
19159
19160
19161
19162
19163
19164
19165
19166
19167
19168
19169
19170
19171
19172
19173
19174
19175
19176
19177
19178
19179
19180
19181
19182
19183
19184
19185
19186
19187
19188
19189
19190
19191
19192
19193
19194
19195
19196
19197
19198
19199
19200
19201
19202
19203
19204
19205
19206
19207
19208
19209
19210
19211
19212
19213
19214
19215
19216
19217
19218
19219
19220
19221
19222
19223
19224
19225
19226
19227
19228
19229
19230
19231
19232
19233
19234
19235
19236
19237
19238
19239
19240
19241
19242
19243
19244
19245
19246
19247
19248
19249
19250
19251
19252
19253
19254
19255
19256
19257
19258
19259
19260
19261
19262
19263
19264
19265
19266
19267
19268
19269
19270
19271
19272
19273
19274
19275
19276
19277
19278
19279
19280
19281
19282
19283
19284
19285
19286
19287
19288
19289
19290
19291
19292
19293
19294
19295
19296
19297
19298
19299
19300
19301
19302
19303
19304
19305
19306
19307
19308
19309
19310
19311
19312
19313
19314
19315
19316
19317
19318
19319
19320
19321
19322
19323
19324
19325
19326
19327
19328
19329
19330
19331
19332
19333
19334
19335
19336
19337
19338
19339
19340
19341
19342
19343
19344
19345
19346
19347
19348
19349
19350
19351
19352
19353
19354
19355
19356
19357
19358
19359
19360
19361
19362
19363
19364
19365
19366
19367
19368
19369
19370
19371
19372
19373
19374
19375
19376
19377
19378
19379
19380
19381
19382
19383
19384
19385
19386
19387
19388
19389
19390
19391
19392
19393
19394
19395
19396
19397
19398
19399
19400
19401
19402
19403
19404
19405
19406
19407
19408
19409
19410
19411
19412
19413
19414
19415
19416
19417
19418
19419
19420
19421
19422
19423
19424
19425
19426
19427
19428
19429
19430
19431
19432
19433
19434
19435
19436
19437
19438
19439
19440
19441
19442
19443
19444
19445
19446
19447
19448
19449
19450
19451
19452
19453
19454
19455
19456
19457
19458
19459
19460
19461
19462
19463
19464
19465
19466
19467
19468
19469
19470
19471
19472
19473
19474
19475
19476
19477
19478
19479
19480
19481
19482
19483
19484
19485
19486
19487
19488
19489
19490
19491
19492
19493
19494
19495
19496
19497
19498
19499
19500
19501
19502
19503
19504
19505
19506
19507
19508
19509
19510
19511
19512
19513
19514
19515
19516
19517
19518
19519
19520
19521
19522
19523
19524
19525
19526
19527
19528
19529
19530
19531
19532
19533
19534
19535
19536
19537
19538
19539
19540
19541
19542
19543
19544
19545
19546
19547
19548
19549
19550
19551
19552
19553
19554
19555
19556
19557
19558
19559
19560
19561
19562
19563
19564
19565
19566
19567
19568
19569
19570
19571
19572
19573
19574
19575
19576
19577
19578
19579
19580
19581
19582
19583
19584
19585
19586
19587
19588
19589
19590
19591
19592
19593
19594
19595
19596
19597
19598
19599
19600
19601
19602
19603
19604
19605
19606
19607
19608
19609
19610
19611
19612
19613
19614
19615
19616
19617
19618
19619
19620
19621
19622
19623
19624
19625
19626
19627
19628
19629
19630
19631
19632
19633
19634
19635
19636
19637
19638
19639
19640
19641
19642
19643
19644
19645
19646
19647
19648
19649
19650
19651
19652
19653
19654
19655
19656
19657
19658
19659
19660
19661
19662
19663
19664
19665
19666
19667
19668
19669
19670
19671
19672
19673
19674
19675
19676
19677
19678
19679
19680
19681
19682
19683
19684
19685
19686
19687
19688
19689
19690
19691
19692
19693
19694
19695
19696
19697
19698
19699
19700
19701
19702
19703
19704
19705
19706
19707
19708
19709
19710
19711
19712
19713
19714
19715
19716
19717
19718
19719
19720
19721
19722
19723
19724
19725
19726
19727
19728
19729
19730
19731
19732
19733
19734
19735
19736
19737
19738
19739
19740
19741
19742
19743
19744
19745
19746
19747
19748
19749
19750
19751
19752
19753
19754
19755
19756
19757
19758
19759
19760
19761
19762
19763
19764
19765
19766
19767
19768
19769
19770
19771
19772
19773
19774
19775
19776
19777
19778
19779
19780
19781
19782
19783
19784
19785
19786
19787
19788
19789
19790
19791
19792
19793
19794
19795
19796
19797
19798
19799
19800
19801
19802
19803
19804
19805
19806
19807
19808
19809
19810
19811
19812
19813
19814
19815
19816
19817
19818
19819
19820
19821
19822
19823
19824
19825
19826
19827
19828
19829
19830
19831
19832
19833
19834
19835
19836
19837
19838
19839
19840
19841
19842
19843
19844
19845
19846
19847
19848
19849
19850
19851
19852
19853
19854
19855
19856
19857
19858
19859
19860
19861
19862
19863
19864
19865
19866
19867
19868
19869
19870
19871
19872
19873
19874
19875
19876
19877
19878
19879
19880
19881
19882
19883
19884
19885
19886
19887
19888
19889
19890
19891
19892
19893
19894
19895
19896
19897
19898
19899
19900
19901
19902
19903
19904
19905
19906
19907
19908
19909
19910
19911
19912
19913
19914
19915
19916
19917
19918
19919
19920
19921
19922
19923
19924
19925
19926
19927
19928
19929
19930
19931
19932
19933
19934
19935
19936
19937
19938
19939
19940
19941
19942
19943
19944
19945
19946
19947
19948
19949
19950
19951
19952
19953
19954
19955
19956
19957
19958
19959
19960
19961
19962
19963
19964
19965
19966
19967
19968
19969
19970
19971
19972
19973
19974
19975
19976
19977
19978
19979
19980
19981
19982
19983
19984
19985
19986
19987
19988
19989
19990
19991
19992
19993
19994
19995
19996
19997
19998
19999
20000
20001
20002
20003
20004
20005
20006
20007
20008
20009
20010
20011
20012
20013
20014
20015
20016
20017
20018
20019
20020
20021
20022
20023
20024
20025
20026
20027
20028
20029
20030
20031
20032
20033
20034
20035
20036
20037
20038
20039
20040
20041
20042
20043
20044
20045
20046
20047
20048
20049
20050
20051
20052
20053
20054
20055
20056
20057
20058
20059
20060
20061
20062
20063
20064
20065
20066
20067
20068
20069
20070
20071
20072
20073
20074
20075
20076
20077
20078
20079
20080
20081
20082
20083
20084
20085
20086
20087
20088
20089
20090
20091
20092
20093
20094
20095
20096
20097
20098
20099
20100
20101
20102
20103
20104
20105
20106
20107
20108
20109
20110
20111
20112
20113
20114
20115
20116
20117
20118
20119
20120
20121
20122
20123
20124
20125
20126
20127
20128
20129
20130
20131
20132
20133
20134
20135
20136
20137
20138
20139
20140
20141
20142
20143
20144
20145
20146
20147
20148
20149
20150
20151
20152
20153
20154
20155
20156
20157
20158
20159
20160
20161
20162
20163
20164
20165
20166
20167
20168
20169
20170
20171
20172
20173
20174
20175
20176
20177
20178
20179
20180
20181
20182
20183
20184
20185
20186
20187
20188
20189
20190
20191
20192
20193
20194
20195
20196
20197
20198
20199
20200
20201
20202
20203
20204
20205
20206
20207
20208
20209
20210
20211
20212
20213
20214
20215
20216
20217
20218
20219
20220
20221
20222
20223
20224
20225
20226
20227
20228
20229
20230
20231
20232
20233
20234
20235
20236
20237
20238
20239
20240
20241
20242
20243
20244
20245
20246
20247
20248
20249
20250
20251
20252
20253
20254
20255
20256
20257
20258
20259
20260
20261
20262
20263
20264
20265
20266
20267
20268
20269
20270
20271
20272
20273
20274
20275
20276
20277
20278
20279
20280
20281
20282
20283
20284
20285
20286
20287
20288
20289
20290
20291
20292
20293
20294
20295
20296
20297
20298
20299
20300
20301
20302
20303
20304
20305
20306
20307
20308
20309
20310
20311
20312
20313
20314
20315
20316
20317
20318
20319
20320
20321
20322
20323
20324
20325
20326
20327
20328
20329
20330
20331
20332
20333
20334
20335
20336
20337
20338
20339
20340
20341
20342
20343
20344
20345
20346
20347
20348
20349
20350
20351
20352
20353
20354
20355
20356
20357
20358
20359
20360
20361
20362
20363
20364
20365
20366
20367
20368
20369
20370
20371
20372
20373
20374
20375
20376
20377
20378
20379
20380
20381
20382
20383
20384
20385
20386
20387
20388
20389
20390
20391
20392
20393
20394
20395
20396
20397
20398
20399
20400
20401
20402
20403
20404
20405
20406
20407
20408
20409
20410
20411
20412
20413
20414
20415
20416
20417
20418
20419
20420
20421
20422
20423
20424
20425
20426
20427
20428
20429
20430
20431
20432
20433
20434
20435
20436
20437
20438
20439
20440
20441
20442
20443
20444
20445
20446
20447
20448
20449
20450
20451
20452
20453
20454
20455
20456
20457
20458
20459
20460
20461
20462
20463
20464
20465
20466
20467
20468
20469
20470
20471
20472
20473
20474
20475
20476
20477
20478
20479
20480
20481
20482
20483
20484
20485
20486
20487
20488
20489
20490
20491
20492
20493
20494
20495
20496
20497
20498
20499
20500
20501
20502
20503
20504
20505
20506
20507
20508
20509
20510
20511
20512
20513
20514
20515
20516
20517
20518
20519
20520
20521
20522
20523
20524
20525
20526
20527
20528
20529
20530
20531
20532
20533
20534
20535
20536
20537
20538
20539
20540
20541
20542
20543
20544
20545
20546
20547
20548
20549
20550
20551
20552
20553
20554
20555
20556
20557
20558
20559
20560
20561
20562
20563
20564
20565
20566
20567
20568
20569
20570
20571
20572
20573
20574
20575
20576
20577
20578
20579
20580
20581
20582
20583
20584
20585
20586
20587
20588
20589
20590
20591
20592
20593
20594
20595
20596
20597
20598
20599
20600
20601
20602
20603
20604
20605
20606
20607
20608
20609
20610
20611
20612
20613
20614
20615
20616
20617
20618
20619
20620
20621
20622
20623
20624
20625
20626
20627
20628
20629
20630
20631
20632
20633
20634
20635
20636
20637
20638
20639
20640
20641
20642
20643
20644
20645
20646
20647
20648
20649
20650
20651
20652
20653
20654
20655
20656
20657
20658
20659
20660
20661
20662
20663
20664
20665
20666
20667
20668
20669
20670
20671
20672
20673
20674
20675
20676
20677
20678
20679
20680
20681
20682
20683
20684
20685
20686
20687
20688
20689
20690
20691
20692
20693
20694
20695
20696
20697
20698
20699
20700
20701
20702
20703
20704
20705
20706
20707
20708
20709
20710
20711
20712
20713
20714
20715
20716
20717
20718
20719
20720
20721
20722
20723
20724
20725
20726
20727
20728
20729
20730
20731
20732
20733
20734
20735
20736
20737
20738
20739
20740
20741
20742
20743
20744
20745
20746
20747
20748
20749
20750
20751
20752
20753
20754
20755
20756
20757
20758
20759
20760
20761
20762
20763
20764
20765
20766
20767
20768
20769
20770
20771
20772
20773
20774
20775
20776
20777
20778
20779
20780
20781
20782
20783
20784
20785
20786
20787
20788
20789
20790
20791
20792
20793
20794
20795
20796
20797
20798
20799
20800
20801
20802
20803
20804
20805
20806
20807
20808
20809
20810
20811
20812
20813
20814
20815
20816
20817
20818
20819
20820
20821
20822
20823
20824
20825
20826
20827
20828
20829
20830
20831
20832
20833
20834
20835
20836
20837
20838
20839
20840
20841
20842
20843
20844
20845
20846
20847
20848
20849
20850
20851
20852
20853
20854
20855
20856
20857
20858
20859
20860
20861
20862
20863
20864
20865
20866
20867
20868
20869
20870
20871
20872
20873
20874
20875
20876
20877
20878
20879
20880
20881
20882
20883
20884
20885
20886
20887
20888
20889
20890
20891
20892
20893
20894
20895
20896
20897
20898
20899
20900
20901
20902
20903
20904
20905
20906
20907
20908
20909
20910
20911
20912
20913
20914
20915
20916
20917
20918
20919
20920
20921
20922
20923
20924
20925
20926
20927
20928
20929
20930
20931
20932
20933
20934
20935
20936
20937
20938
20939
20940
20941
20942
20943
20944
20945
20946
20947
20948
20949
20950
20951
20952
20953
20954
20955
20956
20957
20958
20959
20960
20961
20962
20963
20964
20965
20966
20967
20968
20969
20970
20971
20972
20973
20974
20975
20976
20977
20978
20979
20980
20981
20982
20983
20984
20985
20986
20987
20988
20989
20990
20991
20992
20993
20994
20995
20996
20997
20998
20999
21000
21001
21002
21003
21004
21005
21006
21007
21008
21009
21010
21011
21012
21013
21014
21015
21016
21017
21018
21019
21020
21021
21022
21023
21024
21025
21026
21027
21028
21029
21030
21031
21032
21033
21034
21035
21036
21037
21038
21039
21040
21041
21042
21043
21044
21045
21046
21047
21048
21049
21050
21051
21052
21053
21054
21055
21056
21057
21058
21059
21060
21061
21062
21063
21064
21065
21066
21067
21068
21069
21070
21071
21072
21073
21074
21075
21076
21077
21078
21079
21080
21081
21082
21083
21084
21085
21086
21087
21088
21089
21090
21091
21092
21093
21094
21095
21096
21097
21098
21099
21100
21101
21102
21103
21104
21105
21106
21107
21108
21109
21110
21111
21112
21113
21114
21115
21116
21117
21118
21119
21120
21121
21122
21123
21124
21125
21126
21127
21128
21129
21130
21131
21132
21133
21134
21135
21136
21137
21138
21139
21140
21141
21142
21143
21144
21145
21146
21147
21148
21149
21150
21151
21152
21153
21154
21155
21156
21157
21158
21159
21160
21161
21162
21163
21164
21165
21166
21167
21168
21169
21170
21171
21172
21173
21174
21175
21176
21177
21178
21179
21180
21181
21182
21183
21184
21185
21186
21187
21188
21189
21190
21191
21192
21193
21194
21195
21196
21197
21198
21199
21200
21201
21202
21203
21204
21205
21206
21207
21208
21209
21210
21211
21212
21213
21214
21215
21216
21217
21218
21219
21220
21221
21222
21223
21224
21225
21226
21227
21228
21229
21230
21231
21232
21233
21234
21235
21236
21237
21238
21239
21240
21241
21242
21243
21244
21245
21246
21247
21248
21249
21250
21251
21252
21253
21254
21255
21256
21257
21258
21259
21260
21261
21262
21263
21264
21265
21266
21267
21268
21269
21270
21271
21272
21273
21274
21275
21276
21277
21278
21279
21280
21281
21282
21283
21284
21285
21286
21287
21288
21289
21290
21291
21292
21293
21294
21295
21296
21297
21298
21299
21300
21301
21302
21303
21304
21305
21306
21307
21308
21309
21310
21311
21312
21313
21314
21315
21316
21317
21318
21319
21320
21321
21322
21323
21324
21325
21326
21327
21328
21329
21330
21331
21332
21333
21334
21335
21336
21337
21338
21339
21340
21341
21342
21343
21344
21345
21346
21347
21348
21349
21350
21351
21352
21353
21354
21355
21356
21357
21358
21359
21360
21361
21362
21363
21364
21365
21366
21367
21368
21369
21370
21371
21372
21373
21374
21375
21376
21377
21378
21379
21380
21381
21382
21383
21384
21385
21386
21387
21388
21389
21390
21391
21392
21393
21394
21395
21396
21397
21398
21399
21400
21401
21402
21403
21404
21405
21406
21407
21408
21409
21410
21411
21412
21413
21414
21415
21416
21417
21418
21419
21420
21421
21422
21423
21424
21425
21426
21427
21428
21429
21430
21431
21432
21433
21434
21435
21436
21437
21438
21439
21440
21441
21442
21443
21444
21445
21446
21447
21448
21449
21450
21451
21452
21453
21454
21455
21456
21457
21458
21459
21460
21461
21462
21463
21464
21465
21466
21467
21468
21469
21470
21471
21472
21473
21474
21475
21476
21477
21478
21479
21480
21481
21482
21483
21484
21485
21486
21487
21488
21489
21490
21491
21492
21493
21494
21495
21496
21497
21498
21499
21500
21501
21502
21503
21504
21505
21506
21507
21508
21509
21510
21511
21512
21513
21514
21515
21516
21517
21518
21519
21520
21521
21522
21523
21524
21525
21526
21527
21528
21529
21530
21531
21532
21533
21534
21535
21536
21537
21538
21539
21540
21541
21542
21543
21544
21545
21546
21547
21548
21549
21550
21551
21552
21553
21554
21555
21556
21557
21558
21559
21560
21561
21562
21563
21564
21565
21566
21567
21568
21569
21570
21571
21572
21573
21574
21575
21576
21577
21578
21579
21580
21581
21582
21583
21584
21585
21586
21587
21588
21589
21590
21591
21592
21593
21594
21595
21596
21597
21598
21599
21600
21601
21602
21603
21604
21605
21606
21607
21608
21609
21610
21611
21612
21613
21614
21615
21616
21617
21618
21619
21620
21621
21622
21623
21624
21625
21626
21627
21628
21629
21630
21631
21632
21633
21634
21635
21636
21637
21638
21639
21640
21641
21642
21643
21644
21645
21646
21647
21648
21649
21650
21651
21652
21653
21654
21655
21656
21657
21658
21659
21660
21661
21662
21663
21664
21665
21666
21667
21668
21669
21670
21671
21672
21673
21674
21675
21676
21677
21678
21679
21680
21681
21682
21683
21684
21685
21686
21687
21688
21689
21690
21691
21692
21693
21694
21695
21696
21697
21698
21699
21700
21701
21702
21703
21704
21705
21706
21707
21708
21709
21710
21711
21712
21713
21714
21715
21716
21717
21718
21719
21720
21721
21722
21723
21724
21725
21726
21727
21728
21729
21730
21731
21732
21733
21734
21735
21736
21737
21738
21739
21740
21741
21742
21743
21744
21745
21746
21747
21748
21749
21750
21751
21752
21753
21754
21755
21756
21757
21758
21759
21760
21761
21762
21763
21764
21765
21766
21767
21768
21769
21770
21771
21772
21773
21774
21775
21776
21777
21778
21779
21780
21781
21782
21783
21784
21785
21786
21787
21788
21789
21790
21791
21792
21793
21794
21795
21796
21797
21798
21799
21800
21801
21802
21803
21804
21805
21806
21807
21808
21809
21810
21811
21812
21813
21814
21815
21816
21817
21818
21819
21820
21821
21822
21823
21824
21825
21826
21827
21828
21829
21830
21831
21832
21833
21834
21835
21836
21837
21838
21839
21840
21841
21842
21843
21844
21845
21846
21847
21848
21849
21850
21851
21852
21853
21854
21855
21856
21857
21858
21859
21860
21861
21862
21863
21864
21865
21866
21867
21868
21869
21870
21871
21872
21873
21874
21875
21876
21877
21878
21879
21880
21881
21882
21883
21884
21885
21886
21887
21888
21889
21890
21891
21892
21893
21894
21895
21896
21897
21898
21899
21900
21901
21902
21903
21904
21905
21906
21907
21908
21909
21910
21911
21912
21913
21914
21915
21916
21917
21918
21919
21920
21921
21922
21923
21924
21925
21926
21927
21928
21929
21930
21931
21932
21933
21934
21935
21936
21937
21938
21939
21940
21941
21942
21943
21944
21945
21946
21947
21948
21949
21950
21951
21952
21953
21954
21955
21956
21957
21958
21959
21960
21961
21962
21963
21964
21965
21966
21967
21968
21969
21970
21971
21972
21973
21974
21975
21976
21977
21978
21979
21980
21981
21982
21983
21984
21985
21986
21987
21988
21989
21990
21991
21992
21993
21994
21995
21996
21997
21998
21999
22000
22001
22002
22003
22004
22005
22006
22007
22008
22009
22010
22011
22012
22013
22014
22015
22016
22017
22018
22019
22020
22021
22022
22023
22024
22025
22026
22027
22028
22029
22030
22031
22032
22033
22034
22035
22036
22037
22038
22039
22040
22041
22042
22043
22044
22045
22046
22047
22048
22049
22050
22051
22052
22053
22054
22055
22056
22057
22058
22059
22060
22061
22062
22063
22064
22065
22066
22067
22068
22069
22070
22071
22072
22073
22074
22075
22076
22077
22078
22079
22080
22081
22082
22083
22084
22085
22086
22087
22088
22089
22090
22091
22092
22093
22094
22095
22096
22097
22098
22099
22100
22101
22102
22103
22104
22105
22106
22107
22108
22109
22110
22111
22112
22113
22114
22115
22116
22117
22118
22119
22120
22121
22122
22123
22124
22125
22126
22127
22128
22129
22130
22131
22132
22133
22134
22135
22136
22137
22138
22139
22140
22141
22142
22143
22144
22145
22146
22147
22148
22149
22150
22151
22152
22153
22154
22155
22156
22157
22158
22159
22160
22161
22162
22163
22164
22165
22166
22167
22168
22169
22170
22171
22172
22173
22174
22175
22176
22177
22178
22179
22180
22181
22182
22183
22184
22185
22186
22187
22188
22189
22190
22191
22192
22193
22194
22195
22196
22197
22198
22199
22200
22201
22202
22203
22204
22205
22206
22207
22208
22209
22210
22211
22212
22213
22214
22215
22216
22217
22218
22219
22220
22221
22222
22223
22224
22225
22226
22227
22228
22229
22230
22231
22232
22233
22234
22235
22236
22237
22238
22239
22240
22241
22242
22243
22244
22245
22246
22247
22248
22249
22250
22251
22252
22253
22254
22255
22256
22257
22258
22259
22260
22261
22262
22263
22264
22265
22266
22267
22268
22269
22270
22271
22272
22273
22274
22275
22276
22277
22278
22279
22280
22281
22282
22283
22284
22285
22286
22287
22288
22289
22290
22291
22292
22293
22294
22295
22296
22297
22298
22299
22300
22301
22302
22303
22304
22305
22306
22307
22308
22309
22310
22311
22312
22313
22314
22315
22316
22317
22318
22319
22320
22321
22322
22323
22324
22325
22326
22327
22328
22329
22330
22331
22332
22333
22334
22335
22336
22337
22338
22339
22340
22341
22342
22343
22344
22345
22346
22347
22348
22349
22350
22351
22352
22353
22354
22355
22356
22357
22358
22359
22360
22361
22362
22363
22364
22365
22366
22367
22368
22369
22370
22371
22372
22373
22374
22375
22376
22377
22378
22379
22380
22381
22382
22383
22384
22385
22386
22387
22388
22389
22390
22391
22392
22393
22394
22395
22396
22397
22398
22399
22400
22401
22402
22403
22404
22405
22406
22407
22408
22409
22410
22411
22412
22413
22414
22415
22416
22417
22418
22419
22420
22421
22422
22423
22424
22425
22426
22427
22428
22429
22430
22431
22432
22433
22434
22435
22436
22437
22438
22439
22440
22441
22442
22443
22444
22445
22446
22447
22448
22449
22450
22451
22452
22453
22454
22455
22456
22457
22458
22459
22460
22461
22462
22463
22464
22465
22466
22467
22468
22469
22470
22471
22472
22473
22474
22475
22476
22477
22478
22479
22480
22481
22482
22483
22484
22485
22486
22487
22488
22489
22490
22491
22492
22493
22494
22495
22496
22497
22498
22499
22500
22501
22502
22503
22504
22505
22506
22507
22508
22509
22510
22511
22512
22513
22514
22515
22516
22517
22518
22519
22520
22521
22522
22523
22524
22525
22526
22527
22528
22529
22530
22531
22532
22533
22534
22535
22536
22537
22538
22539
22540
22541
22542
22543
22544
22545
22546
22547
22548
22549
22550
22551
22552
22553
22554
22555
22556
22557
22558
22559
22560
22561
22562
22563
22564
22565
22566
22567
22568
22569
22570
22571
22572
22573
22574
22575
22576
22577
22578
22579
22580
22581
22582
22583
22584
22585
22586
22587
22588
22589
22590
22591
22592
22593
22594
22595
22596
22597
22598
22599
22600
22601
22602
22603
22604
22605
22606
22607
22608
22609
22610
22611
22612
22613
22614
22615
22616
22617
22618
22619
22620
22621
22622
22623
22624
22625
22626
22627
22628
22629
22630
22631
22632
22633
22634
22635
22636
22637
22638
22639
22640
22641
22642
22643
22644
22645
22646
22647
22648
22649
22650
22651
22652
22653
22654
22655
22656
22657
22658
22659
22660
22661
22662
22663
22664
22665
22666
22667
22668
22669
22670
22671
22672
22673
22674
22675
22676
22677
22678
22679
22680
22681
22682
22683
22684
22685
22686
22687
22688
22689
22690
22691
22692
22693
22694
22695
22696
22697
22698
22699
22700
22701
22702
22703
22704
22705
22706
22707
22708
22709
22710
22711
22712
22713
22714
22715
22716
22717
22718
22719
22720
22721
22722
22723
22724
22725
22726
22727
22728
22729
22730
22731
22732
22733
22734
22735
22736
22737
22738
22739
22740
22741
22742
22743
22744
22745
22746
22747
22748
22749
22750
22751
22752
22753
22754
22755
22756
22757
22758
22759
22760
22761
22762
22763
22764
22765
22766
22767
22768
22769
22770
22771
22772
22773
22774
22775
22776
22777
22778
22779
22780
22781
22782
22783
22784
22785
22786
22787
22788
22789
22790
22791
22792
22793
22794
22795
22796
22797
22798
22799
22800
22801
22802
22803
22804
22805
22806
22807
22808
22809
22810
22811
22812
22813
22814
22815
22816
22817
22818
22819
22820
22821
22822
22823
22824
22825
22826
22827
22828
22829
22830
22831
22832
22833
22834
22835
22836
22837
22838
22839
22840
22841
22842
22843
22844
22845
22846
22847
22848
22849
22850
22851
22852
22853
22854
22855
22856
22857
22858
22859
22860
22861
22862
22863
22864
22865
22866
22867
22868
22869
22870
22871
22872
22873
22874
22875
22876
22877
22878
22879
22880
22881
22882
22883
22884
22885
22886
22887
22888
22889
22890
22891
22892
22893
22894
22895
22896
22897
22898
22899
22900
22901
22902
22903
22904
22905
22906
22907
22908
22909
22910
22911
22912
22913
22914
22915
22916
22917
22918
22919
22920
22921
22922
22923
22924
22925
22926
22927
22928
22929
22930
22931
22932
22933
22934
22935
22936
22937
22938
22939
22940
22941
22942
22943
22944
22945
22946
22947
22948
22949
22950
22951
22952
22953
22954
22955
22956
22957
22958
22959
22960
22961
22962
22963
22964
22965
22966
22967
22968
22969
22970
22971
22972
22973
22974
22975
22976
22977
22978
22979
22980
22981
22982
22983
22984
22985
22986
22987
22988
22989
22990
22991
22992
22993
22994
22995
22996
22997
22998
22999
23000
23001
23002
23003
23004
23005
23006
23007
23008
23009
23010
23011
23012
23013
23014
23015
23016
23017
23018
23019
23020
23021
23022
23023
23024
23025
23026
23027
23028
23029
23030
23031
23032
23033
23034
23035
23036
23037
23038
23039
23040
23041
23042
23043
23044
23045
23046
23047
23048
23049
23050
23051
23052
23053
23054
23055
23056
23057
23058
23059
23060
23061
23062
23063
23064
23065
23066
23067
23068
23069
23070
23071
23072
23073
23074
23075
23076
23077
23078
23079
23080
23081
23082
23083
23084
23085
23086
23087
23088
23089
23090
23091
23092
23093
23094
23095
23096
23097
23098
23099
23100
23101
23102
23103
23104
23105
23106
23107
23108
23109
23110
23111
23112
23113
23114
23115
23116
23117
23118
23119
23120
23121
23122
23123
23124
23125
23126
23127
23128
23129
23130
23131
23132
23133
23134
23135
23136
23137
23138
23139
23140
23141
23142
23143
23144
23145
23146
23147
23148
23149
23150
23151
23152
23153
23154
23155
23156
23157
23158
23159
23160
23161
23162
23163
23164
23165
23166
23167
23168
23169
23170
23171
23172
23173
23174
23175
23176
23177
23178
23179
23180
23181
23182
23183
23184
23185
23186
23187
23188
23189
23190
23191
23192
23193
23194
23195
23196
23197
23198
23199
23200
23201
23202
23203
23204
23205
23206
23207
23208
23209
23210
23211
23212
23213
23214
23215
23216
23217
23218
23219
23220
23221
23222
23223
23224
23225
23226
23227
23228
23229
23230
23231
23232
23233
23234
23235
23236
23237
23238
23239
23240
23241
23242
23243
23244
23245
23246
23247
23248
23249
23250
23251
23252
23253
23254
23255
23256
23257
23258
23259
23260
23261
23262
23263
23264
23265
23266
23267
23268
23269
23270
23271
23272
23273
23274
23275
23276
23277
23278
23279
23280
23281
23282
23283
23284
23285
23286
23287
23288
23289
23290
23291
23292
23293
23294
23295
23296
23297
23298
23299
23300
23301
23302
23303
23304
23305
23306
23307
23308
23309
23310
23311
23312
23313
23314
23315
23316
23317
23318
23319
23320
23321
23322
23323
23324
23325
23326
23327
23328
23329
23330
23331
23332
23333
23334
23335
23336
23337
23338
23339
23340
23341
23342
23343
23344
23345
23346
23347
23348
23349
23350
23351
23352
23353
23354
23355
23356
23357
23358
23359
23360
23361
23362
23363
23364
23365
23366
23367
23368
23369
23370
23371
23372
23373
23374
23375
23376
23377
23378
23379
23380
23381
23382
23383
23384
23385
23386
23387
23388
23389
23390
23391
23392
23393
23394
23395
23396
23397
23398
23399
23400
23401
23402
23403
23404
23405
23406
23407
23408
23409
23410
23411
23412
23413
23414
23415
23416
23417
23418
23419
23420
23421
23422
23423
23424
23425
23426
23427
23428
23429
23430
23431
23432
23433
23434
23435
23436
23437
23438
23439
23440
23441
23442
23443
23444
23445
23446
23447
23448
23449
23450
23451
23452
23453
23454
23455
23456
23457
23458
23459
23460
23461
23462
23463
23464
23465
23466
23467
23468
23469
23470
23471
23472
23473
23474
23475
23476
23477
23478
23479
23480
23481
23482
23483
23484
23485
23486
23487
23488
23489
23490
23491
23492
23493
23494
23495
23496
23497
23498
23499
23500
23501
23502
23503
23504
23505
23506
23507
23508
23509
23510
23511
23512
23513
23514
23515
23516
23517
23518
23519
23520
23521
23522
23523
23524
23525
23526
23527
23528
23529
23530
23531
23532
23533
23534
23535
23536
23537
23538
23539
23540
23541
23542
23543
23544
23545
23546
23547
23548
23549
23550
23551
23552
23553
23554
23555
23556
23557
23558
23559
23560
23561
23562
23563
23564
23565
23566
23567
23568
23569
23570
23571
23572
23573
23574
23575
23576
23577
23578
23579
23580
23581
23582
23583
23584
23585
23586
23587
23588
23589
23590
23591
23592
23593
23594
23595
23596
23597
23598
23599
23600
23601
23602
23603
23604
23605
23606
23607
23608
23609
23610
23611
23612
23613
23614
23615
23616
23617
23618
23619
23620
23621
23622
23623
23624
23625
23626
23627
23628
23629
23630
23631
23632
23633
23634
23635
23636
23637
23638
23639
23640
23641
23642
23643
23644
23645
23646
23647
23648
23649
23650
23651
23652
23653
23654
23655
23656
23657
23658
23659
23660
23661
23662
23663
23664
23665
23666
23667
23668
23669
23670
23671
23672
23673
23674
23675
23676
23677
23678
23679
23680
23681
23682
23683
23684
23685
23686
23687
23688
23689
23690
23691
23692
23693
23694
23695
23696
23697
23698
23699
23700
23701
23702
23703
23704
23705
23706
23707
23708
23709
23710
23711
23712
23713
23714
23715
23716
23717
23718
23719
23720
23721
23722
23723
23724
23725
23726
23727
23728
23729
23730
23731
23732
23733
23734
23735
23736
23737
23738
23739
23740
23741
23742
23743
23744
23745
23746
23747
23748
23749
23750
23751
23752
23753
23754
23755
23756
23757
23758
23759
23760
23761
23762
23763
23764
23765
23766
23767
23768
23769
23770
23771
23772
23773
23774
23775
23776
23777
23778
23779
23780
23781
23782
23783
23784
23785
23786
23787
23788
23789
23790
23791
23792
23793
23794
23795
23796
23797
23798
23799
23800
23801
23802
23803
23804
23805
23806
23807
23808
23809
23810
23811
23812
23813
23814
23815
23816
23817
23818
23819
23820
23821
23822
23823
23824
23825
23826
23827
23828
23829
23830
23831
23832
23833
23834
23835
23836
23837
23838
23839
23840
23841
23842
23843
23844
23845
23846
23847
23848
23849
23850
23851
23852
23853
23854
23855
23856
23857
23858
23859
23860
23861
23862
23863
23864
23865
23866
23867
23868
23869
23870
23871
23872
23873
23874
23875
23876
23877
23878
23879
23880
23881
23882
23883
23884
23885
23886
23887
23888
23889
23890
23891
23892
23893
23894
23895
23896
23897
23898
23899
23900
23901
23902
23903
23904
23905
23906
23907
23908
23909
23910
23911
23912
23913
23914
23915
23916
23917
23918
23919
23920
23921
23922
23923
23924
23925
23926
23927
23928
23929
23930
23931
23932
23933
23934
23935
23936
23937
23938
23939
23940
23941
23942
23943
23944
23945
23946
23947
23948
23949
23950
23951
23952
23953
23954
23955
23956
23957
23958
23959
23960
23961
23962
23963
23964
23965
23966
23967
23968
23969
23970
23971
23972
23973
23974
23975
23976
23977
23978
23979
23980
23981
23982
23983
23984
23985
23986
23987
23988
23989
23990
23991
23992
23993
23994
23995
23996
23997
23998
23999
24000
24001
24002
24003
24004
24005
24006
24007
24008
24009
24010
24011
24012
24013
24014
24015
24016
24017
24018
24019
24020
24021
24022
24023
24024
24025
24026
24027
24028
24029
24030
24031
24032
24033
24034
24035
24036
24037
24038
24039
24040
24041
24042
24043
24044
24045
24046
24047
24048
24049
24050
24051
24052
24053
24054
24055
24056
24057
24058
24059
24060
24061
24062
24063
24064
24065
24066
24067
24068
24069
24070
24071
24072
24073
24074
24075
24076
24077
24078
24079
24080
24081
24082
24083
24084
24085
24086
24087
24088
24089
24090
24091
24092
24093
24094
24095
24096
24097
24098
24099
24100
24101
24102
24103
24104
24105
24106
24107
24108
24109
24110
24111
24112
24113
24114
24115
24116
24117
24118
24119
24120
24121
24122
24123
24124
24125
24126
24127
24128
24129
24130
24131
24132
24133
24134
24135
24136
24137
24138
24139
24140
24141
24142
24143
24144
24145
24146
24147
24148
24149
24150
24151
24152
24153
24154
24155
24156
24157
24158
24159
24160
24161
24162
24163
24164
24165
24166
24167
24168
24169
24170
24171
24172
24173
24174
24175
24176
24177
24178
24179
24180
24181
24182
24183
24184
24185
24186
24187
24188
24189
24190
24191
24192
24193
24194
24195
24196
24197
24198
24199
24200
24201
24202
24203
24204
24205
24206
24207
24208
24209
24210
24211
24212
24213
24214
24215
24216
24217
24218
24219
24220
24221
24222
24223
24224
24225
24226
24227
24228
24229
24230
24231
24232
24233
24234
24235
24236
24237
24238
24239
24240
24241
24242
24243
24244
24245
24246
24247
24248
24249
24250
24251
24252
24253
24254
24255
24256
24257
24258
24259
24260
24261
24262
24263
24264
24265
24266
24267
24268
24269
24270
24271
24272
24273
24274
24275
24276
24277
24278
24279
24280
24281
24282
24283
24284
24285
24286
24287
24288
24289
24290
24291
24292
24293
24294
24295
24296
24297
24298
24299
24300
24301
24302
24303
24304
24305
24306
24307
24308
24309
24310
24311
24312
24313
24314
24315
24316
24317
24318
24319
24320
24321
24322
24323
24324
24325
24326
24327
24328
24329
24330
24331
24332
24333
24334
24335
24336
24337
24338
24339
24340
24341
24342
24343
24344
24345
24346
24347
24348
24349
24350
24351
24352
24353
24354
24355
24356
24357
24358
24359
24360
24361
24362
24363
24364
24365
24366
24367
24368
24369
24370
24371
24372
24373
24374
24375
24376
24377
24378
24379
24380
24381
24382
24383
24384
24385
24386
24387
24388
24389
24390
24391
24392
24393
24394
24395
24396
24397
24398
24399
24400
24401
24402
24403
24404
24405
24406
24407
24408
24409
24410
24411
24412
24413
24414
24415
24416
24417
24418
24419
24420
24421
24422
24423
24424
24425
24426
24427
24428
24429
24430
24431
24432
24433
24434
24435
24436
24437
24438
24439
24440
24441
24442
24443
24444
24445
24446
24447
24448
24449
24450
24451
24452
24453
24454
24455
24456
24457
24458
24459
24460
24461
24462
24463
24464
24465
24466
24467
24468
24469
24470
24471
24472
24473
24474
24475
24476
24477
24478
24479
24480
24481
24482
24483
24484
24485
24486
24487
24488
24489
24490
24491
24492
24493
24494
24495
24496
24497
24498
24499
24500
24501
24502
24503
24504
24505
24506
24507
24508
24509
24510
24511
24512
24513
24514
24515
24516
24517
24518
24519
24520
24521
24522
24523
24524
24525
24526
24527
24528
24529
24530
24531
24532
24533
24534
24535
24536
24537
24538
24539
24540
24541
24542
24543
24544
24545
24546
24547
24548
24549
24550
24551
24552
24553
24554
24555
24556
24557
24558
24559
24560
24561
24562
24563
24564
24565
24566
24567
24568
24569
24570
24571
24572
24573
24574
24575
24576
24577
24578
24579
24580
24581
24582
24583
24584
24585
24586
24587
24588
24589
24590
24591
24592
24593
24594
24595
24596
24597
24598
24599
24600
24601
24602
24603
24604
24605
24606
24607
24608
24609
24610
24611
24612
24613
24614
24615
24616
24617
24618
24619
24620
24621
24622
24623
24624
24625
24626
24627
24628
24629
24630
24631
24632
24633
24634
24635
24636
24637
24638
24639
24640
24641
24642
24643
24644
24645
24646
24647
24648
24649
24650
24651
24652
24653
24654
24655
24656
24657
24658
24659
24660
24661
24662
24663
24664
24665
24666
24667
24668
24669
24670
24671
24672
24673
24674
24675
24676
24677
24678
24679
24680
24681
24682
24683
24684
24685
24686
24687
24688
24689
24690
24691
24692
24693
24694
24695
24696
24697
24698
24699
24700
24701
24702
24703
24704
24705
24706
24707
24708
24709
24710
24711
24712
24713
24714
24715
24716
24717
24718
24719
24720
24721
24722
24723
24724
24725
24726
24727
24728
24729
24730
24731
24732
24733
24734
24735
24736
24737
24738
24739
24740
24741
24742
24743
24744
24745
24746
24747
24748
24749
24750
24751
24752
24753
24754
24755
24756
24757
24758
24759
24760
24761
24762
24763
24764
24765
24766
24767
24768
24769
24770
24771
24772
24773
24774
24775
24776
24777
24778
24779
24780
24781
24782
24783
24784
24785
24786
24787
24788
24789
24790
24791
24792
24793
24794
24795
24796
24797
24798
24799
24800
24801
24802
24803
24804
24805
24806
24807
24808
24809
24810
24811
24812
24813
24814
24815
24816
24817
24818
24819
24820
24821
24822
24823
24824
24825
24826
24827
24828
24829
24830
24831
24832
24833
24834
24835
24836
24837
24838
24839
24840
24841
24842
24843
24844
24845
24846
24847
24848
24849
24850
24851
24852
24853
24854
24855
24856
24857
24858
24859
24860
24861
24862
24863
24864
24865
24866
24867
24868
24869
24870
24871
24872
24873
24874
24875
24876
24877
24878
24879
24880
24881
24882
24883
24884
24885
24886
24887
24888
24889
24890
24891
24892
24893
24894
24895
24896
24897
24898
24899
24900
24901
24902
24903
24904
24905
24906
24907
24908
24909
24910
24911
24912
24913
24914
24915
24916
24917
24918
24919
24920
24921
24922
24923
24924
24925
24926
24927
24928
24929
24930
24931
24932
24933
24934
24935
24936
24937
24938
24939
24940
24941
24942
24943
24944
24945
24946
24947
24948
24949
24950
24951
24952
24953
24954
24955
24956
24957
24958
24959
24960
24961
24962
24963
24964
24965
24966
24967
24968
24969
24970
24971
24972
24973
24974
24975
24976
24977
24978
24979
24980
24981
24982
24983
24984
24985
24986
24987
24988
24989
24990
24991
24992
24993
24994
24995
24996
24997
24998
24999
25000
25001
25002
25003
25004
25005
25006
25007
25008
25009
25010
25011
25012
25013
25014
25015
25016
25017
25018
25019
25020
25021
25022
25023
25024
25025
25026
25027
25028
25029
25030
25031
25032
25033
25034
25035
25036
25037
25038
25039
25040
25041
25042
25043
25044
25045
25046
25047
25048
25049
25050
25051
25052
25053
25054
25055
25056
25057
25058
25059
25060
25061
25062
25063
25064
25065
25066
25067
25068
25069
25070
25071
25072
25073
25074
25075
25076
25077
25078
25079
25080
25081
25082
25083
25084
25085
25086
25087
25088
25089
25090
25091
25092
25093
25094
25095
25096
25097
25098
25099
25100
25101
25102
25103
25104
25105
25106
25107
25108
25109
25110
25111
25112
25113
25114
25115
25116
25117
25118
25119
25120
25121
25122
25123
25124
25125
25126
25127
25128
25129
25130
25131
25132
25133
25134
25135
25136
25137
25138
25139
25140
25141
25142
25143
25144
25145
25146
25147
25148
25149
25150
25151
25152
25153
25154
25155
25156
25157
25158
25159
25160
25161
25162
25163
25164
25165
25166
25167
25168
25169
25170
25171
25172
25173
25174
25175
25176
25177
25178
25179
25180
25181
25182
25183
25184
25185
25186
25187
25188
25189
25190
25191
25192
25193
25194
25195
25196
25197
25198
25199
25200
25201
25202
25203
25204
25205
25206
25207
25208
25209
25210
25211
25212
25213
25214
25215
25216
25217
25218
25219
25220
25221
25222
25223
25224
25225
25226
25227
25228
25229
25230
25231
25232
25233
25234
25235
25236
25237
25238
25239
25240
25241
25242
25243
25244
25245
25246
25247
25248
25249
25250
25251
25252
25253
25254
25255
25256
25257
25258
25259
25260
25261
25262
25263
25264
25265
25266
25267
25268
25269
25270
25271
25272
25273
25274
25275
25276
25277
25278
25279
25280
25281
25282
25283
25284
25285
25286
25287
25288
25289
25290
25291
25292
25293
25294
25295
25296
25297
25298
25299
25300
25301
25302
25303
25304
25305
25306
25307
25308
25309
25310
25311
25312
25313
25314
25315
25316
25317
25318
25319
25320
25321
25322
25323
25324
25325
25326
25327
25328
25329
25330
25331
25332
25333
25334
25335
25336
25337
25338
25339
25340
25341
25342
25343
25344
25345
25346
25347
25348
25349
25350
25351
25352
25353
25354
25355
25356
25357
25358
25359
25360
25361
25362
25363
25364
25365
25366
25367
25368
25369
25370
25371
25372
25373
25374
25375
25376
25377
25378
25379
25380
25381
25382
25383
25384
25385
25386
25387
25388
25389
25390
25391
25392
25393
25394
25395
25396
25397
25398
25399
25400
25401
25402
25403
25404
25405
25406
25407
25408
25409
25410
25411
25412
25413
25414
25415
25416
25417
25418
25419
25420
25421
25422
25423
25424
25425
25426
25427
25428
25429
25430
25431
25432
25433
25434
25435
25436
25437
25438
25439
25440
25441
25442
25443
25444
25445
25446
25447
25448
25449
25450
25451
25452
25453
25454
25455
25456
25457
25458
25459
25460
25461
25462
25463
25464
25465
25466
25467
25468
25469
25470
25471
25472
25473
25474
25475
25476
25477
25478
25479
25480
25481
25482
25483
25484
25485
25486
25487
25488
25489
25490
25491
25492
25493
25494
25495
25496
25497
25498
25499
25500
25501
25502
25503
25504
25505
25506
25507
25508
25509
25510
25511
25512
25513
25514
25515
25516
25517
25518
25519
25520
25521
25522
25523
25524
25525
25526
25527
25528
25529
25530
25531
25532
25533
25534
25535
25536
25537
25538
25539
25540
25541
25542
25543
25544
25545
25546
25547
25548
25549
25550
25551
25552
25553
25554
25555
25556
25557
25558
25559
25560
25561
25562
25563
25564
25565
25566
25567
25568
25569
25570
25571
25572
25573
25574
25575
25576
25577
25578
25579
25580
25581
25582
25583
25584
25585
25586
25587
25588
25589
25590
25591
25592
25593
25594
25595
25596
25597
25598
25599
25600
25601
25602
25603
25604
25605
25606
25607
25608
25609
25610
25611
25612
25613
25614
25615
25616
25617
25618
25619
25620
25621
25622
25623
25624
25625
25626
25627
25628
25629
25630
25631
25632
25633
25634
25635
25636
25637
25638
25639
25640
25641
25642
25643
25644
25645
25646
25647
25648
25649
25650
25651
25652
25653
25654
25655
25656
25657
25658
25659
25660
25661
25662
25663
25664
25665
25666
25667
25668
25669
25670
25671
25672
25673
25674
25675
25676
25677
25678
25679
25680
25681
25682
25683
25684
25685
25686
25687
25688
25689
25690
25691
25692
25693
25694
25695
25696
25697
25698
25699
25700
25701
25702
25703
25704
25705
25706
25707
25708
25709
25710
25711
25712
25713
25714
25715
25716
25717
25718
25719
25720
25721
25722
25723
25724
25725
25726
25727
25728
25729
25730
25731
25732
25733
25734
25735
25736
25737
25738
25739
25740
25741
25742
25743
25744
25745
25746
25747
25748
25749
25750
25751
25752
25753
25754
25755
25756
25757
25758
25759
25760
25761
25762
25763
25764
25765
25766
25767
25768
25769
25770
25771
25772
25773
25774
25775
25776
25777
25778
25779
25780
25781
25782
25783
25784
25785
25786
25787
25788
25789
25790
25791
25792
25793
25794
25795
25796
25797
25798
25799
25800
25801
25802
25803
25804
25805
25806
25807
25808
25809
25810
25811
25812
25813
25814
25815
25816
25817
25818
25819
25820
25821
25822
25823
25824
25825
25826
25827
25828
25829
25830
25831
25832
25833
25834
25835
25836
25837
25838
25839
25840
25841
25842
25843
25844
25845
25846
25847
25848
25849
25850
25851
25852
25853
25854
25855
25856
25857
25858
25859
25860
25861
25862
25863
25864
25865
25866
25867
25868
25869
25870
25871
25872
25873
25874
25875
25876
25877
25878
25879
25880
25881
25882
25883
25884
25885
25886
25887
25888
25889
25890
25891
25892
25893
25894
25895
25896
25897
25898
25899
25900
25901
25902
25903
25904
25905
25906
25907
25908
25909
25910
25911
25912
25913
25914
25915
25916
25917
25918
25919
25920
25921
25922
25923
25924
25925
25926
25927
25928
25929
25930
25931
25932
25933
25934
25935
25936
25937
25938
25939
25940
25941
25942
25943
25944
25945
25946
25947
25948
25949
25950
25951
25952
25953
25954
25955
25956
25957
25958
25959
25960
25961
25962
25963
25964
25965
25966
25967
25968
25969
25970
25971
25972
25973
25974
25975
25976
25977
25978
25979
25980
25981
25982
25983
25984
25985
25986
25987
25988
25989
25990
25991
25992
25993
25994
25995
25996
25997
25998
25999
26000
26001
26002
26003
26004
26005
26006
26007
26008
26009
26010
26011
26012
26013
26014
26015
26016
26017
26018
26019
26020
26021
26022
26023
26024
26025
26026
26027
26028
26029
26030
26031
26032
26033
26034
26035
26036
26037
26038
26039
26040
26041
26042
26043
26044
26045
26046
26047
26048
26049
26050
26051
26052
26053
26054
26055
26056
26057
26058
26059
26060
26061
26062
26063
26064
26065
26066
26067
26068
26069
26070
26071
26072
26073
26074
26075
26076
26077
26078
26079
26080
26081
26082
26083
26084
26085
26086
26087
26088
26089
26090
26091
26092
26093
26094
26095
26096
26097
26098
26099
26100
26101
26102
26103
26104
26105
26106
26107
26108
26109
26110
26111
26112
26113
26114
26115
26116
26117
26118
26119
26120
26121
26122
26123
26124
26125
26126
26127
26128
26129
26130
26131
26132
26133
26134
26135
26136
26137
26138
26139
26140
26141
26142
26143
26144
26145
26146
26147
26148
26149
26150
26151
26152
26153
26154
26155
26156
26157
26158
26159
26160
26161
26162
26163
26164
26165
26166
26167
26168
26169
26170
26171
26172
26173
26174
26175
26176
26177
26178
26179
26180
26181
26182
26183
26184
26185
26186
26187
26188
26189
26190
26191
26192
26193
26194
26195
26196
26197
26198
26199
26200
26201
26202
26203
26204
26205
26206
26207
26208
26209
26210
26211
26212
26213
26214
26215
26216
26217
26218
26219
26220
26221
26222
26223
26224
26225
26226
26227
26228
26229
26230
26231
26232
26233
26234
26235
26236
26237
26238
26239
26240
26241
26242
26243
26244
26245
26246
26247
26248
26249
26250
26251
26252
26253
26254
26255
26256
26257
26258
26259
26260
26261
26262
26263
26264
26265
26266
26267
26268
26269
26270
26271
26272
26273
26274
26275
26276
26277
26278
26279
26280
26281
26282
26283
26284
26285
26286
26287
26288
26289
26290
26291
26292
26293
26294
26295
26296
26297
26298
26299
26300
26301
26302
26303
26304
26305
26306
26307
26308
26309
26310
26311
26312
26313
26314
26315
26316
26317
26318
26319
26320
26321
26322
26323
26324
26325
26326
26327
26328
26329
26330
26331
26332
26333
26334
26335
26336
26337
26338
26339
26340
26341
26342
26343
26344
26345
26346
26347
26348
26349
26350
26351
26352
26353
26354
26355
26356
26357
26358
26359
26360
26361
26362
26363
26364
26365
26366
26367
26368
26369
26370
26371
26372
26373
26374
26375
26376
26377
26378
26379
26380
26381
26382
26383
26384
26385
26386
26387
26388
26389
26390
26391
26392
26393
26394
26395
26396
26397
26398
26399
26400
26401
26402
26403
26404
26405
26406
26407
26408
26409
26410
26411
26412
26413
26414
26415
26416
26417
26418
26419
26420
26421
26422
26423
26424
26425
26426
26427
26428
26429
26430
26431
26432
26433
26434
26435
26436
26437
26438
26439
26440
26441
26442
26443
26444
26445
26446
26447
26448
26449
26450
26451
26452
26453
26454
26455
26456
26457
26458
26459
26460
26461
26462
26463
26464
26465
26466
26467
26468
26469
26470
26471
26472
26473
26474
26475
26476
26477
26478
26479
26480
26481
26482
26483
26484
26485
26486
26487
26488
26489
26490
26491
26492
26493
26494
26495
26496
26497
26498
26499
26500
26501
26502
26503
26504
26505
26506
26507
26508
26509
26510
26511
26512
26513
26514
26515
26516
26517
26518
26519
26520
26521
26522
26523
26524
26525
26526
26527
26528
26529
26530
26531
26532
26533
26534
26535
26536
26537
26538
26539
26540
26541
26542
26543
26544
26545
26546
26547
26548
26549
26550
26551
26552
26553
26554
26555
26556
26557
26558
26559
26560
26561
26562
26563
26564
26565
26566
26567
26568
26569
26570
26571
26572
26573
26574
26575
26576
26577
26578
26579
26580
26581
26582
26583
26584
26585
26586
26587
26588
26589
26590
26591
26592
26593
26594
26595
26596
26597
26598
26599
26600
26601
26602
26603
26604
26605
26606
26607
26608
26609
26610
26611
26612
26613
26614
26615
26616
26617
26618
26619
26620
26621
26622
26623
26624
26625
26626
26627
26628
26629
26630
26631
26632
26633
26634
26635
26636
26637
26638
26639
26640
26641
26642
26643
26644
26645
26646
26647
26648
26649
26650
26651
26652
26653
26654
26655
26656
26657
26658
26659
26660
26661
26662
26663
26664
26665
26666
26667
26668
26669
26670
26671
26672
26673
26674
26675
26676
26677
26678
26679
26680
26681
26682
26683
26684
26685
26686
26687
26688
26689
26690
26691
26692
26693
26694
26695
26696
26697
26698
26699
26700
26701
26702
26703
26704
26705
26706
26707
26708
26709
26710
26711
26712
26713
26714
26715
26716
26717
26718
26719
26720
26721
26722
26723
26724
26725
26726
26727
26728
26729
26730
26731
26732
26733
26734
26735
26736
26737
26738
26739
26740
26741
26742
26743
26744
26745
26746
26747
26748
26749
26750
26751
26752
26753
26754
26755
26756
26757
26758
26759
26760
26761
26762
26763
26764
26765
26766
26767
26768
26769
26770
26771
26772
26773
26774
26775
26776
26777
26778
26779
26780
26781
26782
26783
26784
26785
26786
26787
26788
26789
26790
26791
26792
26793
26794
26795
26796
26797
26798
26799
26800
26801
26802
26803
26804
26805
26806
26807
26808
26809
26810
26811
26812
26813
26814
26815
26816
26817
26818
26819
26820
26821
26822
26823
26824
26825
26826
26827
26828
26829
26830
26831
26832
26833
26834
26835
26836
26837
26838
26839
26840
26841
26842
26843
26844
26845
26846
26847
26848
26849
26850
26851
26852
26853
26854
26855
26856
26857
26858
26859
26860
26861
26862
26863
26864
26865
26866
26867
26868
26869
26870
26871
26872
26873
26874
26875
26876
26877
26878
26879
26880
26881
26882
26883
26884
26885
26886
26887
26888
26889
26890
26891
26892
26893
26894
26895
26896
26897
26898
26899
26900
26901
26902
26903
26904
26905
26906
26907
26908
26909
26910
26911
26912
26913
26914
26915
26916
26917
26918
26919
26920
26921
26922
26923
26924
26925
26926
26927
26928
26929
26930
26931
26932
26933
26934
26935
26936
26937
26938
26939
26940
26941
26942
26943
26944
26945
26946
26947
26948
26949
26950
26951
26952
26953
26954
26955
26956
26957
26958
26959
26960
26961
26962
26963
26964
26965
26966
26967
26968
26969
26970
26971
26972
26973
26974
26975
26976
26977
26978
26979
26980
26981
26982
26983
26984
26985
26986
26987
26988
26989
26990
26991
26992
26993
26994
26995
26996
26997
26998
26999
27000
27001
27002
27003
27004
27005
27006
27007
27008
27009
27010
27011
27012
27013
27014
27015
27016
27017
27018
27019
27020
27021
27022
27023
27024
27025
27026
27027
27028
27029
27030
27031
27032
27033
27034
27035
27036
27037
27038
27039
27040
27041
27042
27043
27044
27045
27046
27047
27048
27049
27050
27051
27052
27053
27054
27055
27056
27057
27058
27059
27060
27061
27062
27063
27064
27065
27066
27067
27068
27069
27070
27071
27072
27073
27074
27075
27076
27077
27078
27079
27080
27081
27082
27083
27084
27085
27086
27087
27088
27089
27090
27091
27092
27093
27094
27095
27096
27097
27098
27099
27100
27101
27102
27103
27104
27105
27106
27107
27108
27109
27110
27111
27112
27113
27114
27115
27116
27117
27118
27119
27120
27121
27122
27123
27124
27125
27126
27127
27128
27129
27130
27131
27132
27133
27134
27135
27136
27137
27138
27139
27140
27141
27142
27143
27144
27145
27146
27147
27148
27149
27150
27151
27152
27153
27154
27155
27156
27157
27158
27159
27160
27161
27162
27163
27164
27165
27166
27167
27168
27169
27170
27171
27172
27173
27174
27175
27176
27177
27178
27179
27180
27181
27182
27183
27184
27185
27186
27187
27188
27189
27190
27191
27192
27193
27194
27195
27196
27197
27198
27199
27200
27201
27202
27203
27204
27205
27206
27207
27208
27209
27210
27211
27212
27213
27214
27215
27216
27217
27218
27219
27220
27221
27222
27223
27224
27225
27226
27227
27228
27229
27230
27231
27232
27233
27234
27235
27236
27237
27238
27239
27240
27241
27242
27243
27244
27245
27246
27247
27248
27249
27250
27251
27252
27253
27254
27255
27256
27257
27258
27259
27260
27261
27262
27263
27264
27265
27266
27267
27268
27269
27270
27271
27272
27273
27274
27275
27276
27277
27278
27279
27280
27281
27282
27283
27284
27285
27286
27287
27288
27289
27290
27291
27292
27293
27294
27295
27296
27297
27298
27299
27300
27301
27302
27303
27304
27305
27306
27307
27308
27309
27310
27311
27312
27313
27314
27315
27316
27317
27318
27319
27320
27321
27322
27323
27324
27325
27326
27327
27328
27329
27330
27331
27332
27333
27334
27335
27336
27337
27338
27339
27340
27341
27342
27343
27344
27345
27346
27347
27348
27349
27350
27351
27352
27353
27354
27355
27356
27357
27358
27359
27360
27361
27362
27363
27364
27365
27366
27367
27368
27369
27370
27371
27372
27373
27374
27375
27376
27377
27378
27379
27380
27381
27382
27383
27384
27385
27386
27387
27388
27389
27390
27391
27392
27393
27394
27395
27396
27397
27398
27399
27400
27401
27402
27403
27404
27405
27406
27407
27408
27409
27410
27411
27412
27413
27414
27415
27416
27417
27418
27419
27420
27421
27422
27423
27424
27425
27426
27427
27428
27429
27430
27431
27432
27433
27434
27435
27436
27437
27438
27439
27440
27441
27442
27443
27444
27445
27446
27447
27448
27449
27450
27451
27452
27453
27454
27455
27456
27457
27458
27459
27460
27461
27462
27463
27464
27465
27466
27467
27468
27469
27470
27471
27472
27473
27474
27475
27476
27477
27478
27479
27480
27481
27482
27483
27484
27485
27486
27487
27488
27489
27490
27491
27492
27493
27494
27495
27496
27497
27498
27499
27500
27501
27502
27503
27504
27505
27506
27507
27508
27509
27510
27511
27512
27513
27514
27515
27516
27517
27518
27519
27520
27521
27522
27523
27524
27525
27526
27527
27528
27529
27530
27531
27532
27533
27534
27535
27536
27537
27538
27539
27540
27541
27542
27543
27544
27545
27546
27547
27548
27549
27550
27551
27552
27553
27554
27555
27556
27557
27558
27559
27560
27561
27562
27563
27564
27565
27566
27567
27568
27569
27570
27571
27572
27573
27574
27575
27576
27577
27578
27579
27580
27581
27582
27583
27584
27585
27586
27587
27588
27589
27590
27591
27592
27593
27594
27595
27596
27597
27598
27599
27600
27601
27602
27603
27604
27605
27606
27607
27608
27609
27610
27611
27612
27613
27614
27615
27616
27617
27618
27619
27620
27621
27622
27623
27624
27625
27626
27627
27628
27629
27630
27631
27632
27633
27634
27635
27636
27637
27638
27639
27640
27641
27642
27643
27644
27645
27646
27647
27648
27649
27650
27651
27652
27653
27654
27655
27656
27657
27658
27659
27660
27661
27662
27663
27664
27665
27666
27667
27668
27669
27670
27671
27672
27673
27674
27675
27676
27677
27678
27679
27680
27681
27682
27683
27684
27685
27686
27687
27688
27689
27690
27691
27692
27693
27694
27695
27696
27697
27698
27699
27700
27701
27702
27703
27704
27705
27706
27707
27708
27709
27710
27711
27712
27713
27714
27715
27716
27717
27718
27719
27720
27721
27722
27723
27724
27725
27726
27727
27728
27729
27730
27731
27732
27733
27734
27735
27736
27737
27738
27739
27740
27741
27742
27743
27744
27745
27746
27747
27748
27749
27750
27751
27752
27753
27754
27755
27756
27757
27758
27759
27760
27761
27762
27763
27764
27765
27766
27767
27768
27769
27770
27771
27772
27773
27774
27775
27776
27777
27778
27779
27780
27781
27782
27783
27784
27785
27786
27787
27788
27789
27790
27791
27792
27793
27794
27795
27796
27797
27798
27799
27800
27801
27802
27803
27804
27805
27806
27807
27808
27809
27810
27811
27812
27813
27814
27815
27816
27817
27818
27819
27820
27821
27822
27823
27824
27825
27826
27827
27828
27829
27830
27831
27832
27833
27834
27835
27836
27837
27838
27839
27840
27841
27842
27843
27844
27845
27846
27847
27848
27849
27850
27851
27852
27853
27854
27855
27856
27857
27858
27859
27860
27861
27862
27863
27864
27865
27866
27867
27868
27869
27870
27871
27872
27873
27874
27875
27876
27877
27878
27879
27880
27881
27882
27883
27884
27885
27886
27887
27888
27889
27890
27891
27892
27893
27894
27895
27896
27897
27898
27899
27900
27901
27902
27903
27904
27905
27906
27907
27908
27909
27910
27911
27912
27913
27914
27915
27916
27917
27918
27919
27920
27921
27922
27923
27924
27925
27926
27927
27928
27929
27930
27931
27932
27933
27934
27935
27936
27937
27938
27939
27940
27941
27942
27943
27944
27945
27946
27947
27948
27949
27950
27951
27952
27953
27954
27955
27956
27957
27958
27959
27960
27961
27962
27963
27964
27965
27966
27967
27968
27969
27970
27971
27972
27973
27974
27975
27976
27977
27978
27979
27980
27981
27982
27983
27984
27985
27986
27987
27988
27989
27990
27991
27992
27993
27994
27995
27996
27997
27998
27999
28000
28001
28002
28003
28004
28005
28006
28007
28008
28009
28010
28011
28012
28013
28014
28015
28016
28017
28018
28019
28020
28021
28022
28023
28024
28025
28026
28027
28028
28029
28030
28031
28032
28033
28034
28035
28036
28037
28038
28039
28040
28041
28042
28043
28044
28045
28046
28047
28048
28049
28050
28051
28052
28053
28054
28055
28056
28057
28058
28059
28060
28061
28062
28063
28064
28065
28066
28067
28068
28069
28070
28071
28072
28073
28074
28075
28076
28077
28078
28079
28080
28081
28082
28083
28084
28085
28086
28087
28088
28089
28090
28091
28092
28093
28094
28095
28096
28097
28098
28099
28100
28101
28102
28103
28104
28105
28106
28107
28108
28109
28110
28111
28112
28113
28114
28115
28116
28117
28118
28119
28120
28121
28122
28123
28124
28125
28126
28127
28128
28129
28130
28131
28132
28133
28134
28135
28136
28137
28138
28139
28140
28141
28142
28143
28144
28145
28146
28147
28148
28149
28150
28151
28152
28153
28154
28155
28156
28157
28158
28159
28160
28161
28162
28163
28164
28165
28166
28167
28168
28169
28170
28171
28172
28173
28174
28175
28176
28177
28178
28179
28180
28181
28182
28183
28184
28185
28186
28187
28188
28189
28190
28191
28192
28193
28194
28195
28196
28197
28198
28199
28200
28201
28202
28203
28204
28205
28206
28207
28208
28209
28210
28211
28212
28213
28214
28215
28216
28217
28218
28219
28220
28221
28222
28223
28224
28225
28226
28227
28228
28229
28230
28231
28232
28233
28234
28235
28236
28237
28238
28239
28240
28241
28242
28243
28244
28245
28246
28247
28248
28249
28250
28251
28252
28253
28254
28255
28256
28257
28258
28259
28260
28261
28262
28263
28264
28265
28266
28267
28268
28269
28270
28271
28272
28273
28274
28275
28276
28277
28278
28279
28280
28281
28282
28283
28284
28285
28286
28287
28288
28289
28290
28291
28292
28293
28294
28295
28296
28297
28298
28299
28300
28301
28302
28303
28304
28305
28306
28307
28308
28309
28310
28311
28312
28313
28314
28315
28316
28317
28318
28319
28320
28321
28322
28323
28324
28325
28326
28327
28328
28329
28330
28331
28332
28333
28334
28335
28336
28337
28338
28339
28340
28341
28342
28343
28344
28345
28346
28347
28348
28349
28350
28351
28352
28353
28354
28355
28356
28357
28358
28359
28360
28361
28362
28363
28364
28365
28366
28367
28368
28369
28370
28371
28372
28373
28374
28375
28376
28377
28378
28379
28380
28381
28382
28383
28384
28385
28386
28387
28388
28389
28390
28391
28392
28393
28394
28395
28396
28397
28398
28399
28400
28401
28402
28403
28404
28405
28406
28407
28408
28409
28410
28411
28412
28413
28414
28415
28416
28417
28418
28419
28420
28421
28422
28423
28424
28425
28426
28427
28428
28429
28430
28431
28432
28433
28434
28435
28436
28437
28438
28439
28440
28441
28442
28443
28444
28445
28446
28447
28448
28449
28450
28451
28452
28453
28454
28455
28456
28457
28458
28459
28460
28461
28462
28463
28464
28465
28466
28467
28468
28469
28470
28471
28472
28473
28474
28475
28476
28477
28478
28479
28480
28481
28482
28483
28484
28485
28486
28487
28488
28489
28490
28491
28492
28493
28494
28495
28496
28497
28498
28499
28500
28501
28502
28503
28504
28505
28506
28507
28508
28509
28510
28511
28512
28513
28514
28515
28516
28517
28518
28519
28520
28521
28522
28523
28524
28525
28526
28527
28528
28529
28530
28531
28532
28533
28534
28535
28536
28537
28538
28539
28540
28541
28542
28543
28544
28545
28546
28547
28548
28549
28550
28551
28552
28553
28554
28555
28556
28557
28558
28559
28560
28561
28562
28563
28564
28565
28566
28567
28568
28569
28570
28571
28572
28573
28574
28575
28576
28577
28578
28579
28580
28581
28582
28583
28584
28585
28586
28587
28588
28589
28590
28591
28592
28593
28594
28595
28596
28597
28598
28599
28600
28601
28602
28603
28604
28605
28606
28607
28608
28609
28610
28611
28612
28613
28614
28615
28616
28617
28618
28619
28620
28621
28622
28623
28624
28625
28626
28627
28628
28629
28630
28631
28632
28633
28634
28635
28636
28637
28638
28639
28640
28641
28642
28643
28644
28645
28646
28647
28648
28649
28650
28651
28652
28653
28654
28655
28656
28657
28658
28659
28660
28661
28662
28663
28664
28665
28666
28667
28668
28669
28670
28671
28672
28673
28674
28675
28676
28677
28678
28679
28680
28681
28682
28683
28684
28685
28686
28687
28688
28689
28690
28691
28692
28693
28694
28695
28696
28697
28698
28699
28700
28701
28702
28703
28704
28705
28706
28707
28708
28709
28710
28711
28712
28713
28714
28715
28716
28717
28718
28719
28720
28721
28722
28723
28724
28725
28726
28727
28728
28729
28730
28731
28732
28733
28734
28735
28736
28737
28738
28739
28740
28741
28742
28743
28744
28745
28746
28747
28748
28749
28750
28751
28752
28753
28754
28755
28756
28757
28758
28759
28760
28761
28762
28763
28764
28765
28766
28767
28768
28769
28770
28771
28772
28773
28774
28775
28776
28777
28778
28779
28780
28781
28782
28783
28784
28785
28786
28787
28788
28789
28790
28791
28792
28793
28794
28795
28796
28797
28798
28799
28800
28801
28802
28803
28804
28805
28806
28807
28808
28809
28810
28811
28812
28813
28814
28815
28816
28817
28818
28819
28820
28821
28822
28823
28824
28825
28826
28827
28828
28829
28830
28831
28832
28833
28834
28835
28836
28837
28838
28839
28840
28841
28842
28843
28844
28845
28846
28847
28848
28849
28850
28851
28852
28853
28854
28855
28856
28857
28858
28859
28860
28861
28862
28863
28864
28865
28866
28867
28868
28869
28870
28871
28872
28873
28874
28875
28876
28877
28878
28879
28880
28881
28882
28883
28884
28885
28886
28887
28888
28889
28890
28891
28892
28893
28894
28895
28896
28897
28898
28899
28900
28901
28902
28903
28904
28905
28906
28907
28908
28909
28910
28911
28912
28913
28914
28915
28916
28917
28918
28919
28920
28921
28922
28923
28924
28925
28926
28927
28928
28929
28930
28931
28932
28933
28934
28935
28936
28937
28938
28939
28940
28941
28942
28943
28944
28945
28946
28947
28948
28949
28950
28951
28952
28953
28954
28955
28956
28957
28958
28959
28960
28961
28962
28963
28964
28965
28966
28967
28968
28969
28970
28971
28972
28973
28974
28975
28976
28977
28978
28979
28980
28981
28982
28983
28984
28985
28986
28987
28988
28989
28990
28991
28992
28993
28994
28995
28996
28997
28998
28999
29000
29001
29002
29003
29004
29005
29006
29007
29008
29009
29010
29011
29012
29013
29014
29015
29016
29017
29018
29019
29020
29021
29022
29023
29024
29025
29026
29027
29028
29029
29030
29031
29032
29033
29034
29035
29036
29037
29038
29039
29040
29041
29042
29043
29044
29045
29046
29047
29048
29049
29050
29051
29052
29053
29054
29055
29056
29057
29058
29059
29060
29061
29062
29063
29064
29065
29066
29067
29068
29069
29070
29071
29072
29073
29074
29075
29076
29077
29078
29079
29080
29081
29082
29083
29084
29085
29086
29087
29088
29089
29090
29091
29092
29093
29094
29095
29096
29097
29098
29099
29100
29101
29102
29103
29104
29105
29106
29107
29108
29109
29110
29111
29112
29113
29114
29115
29116
29117
29118
29119
29120
29121
29122
29123
29124
29125
29126
29127
29128
29129
29130
29131
29132
29133
29134
29135
29136
29137
29138
29139
29140
29141
29142
29143
29144
29145
29146
29147
29148
29149
29150
29151
29152
29153
29154
29155
29156
29157
29158
29159
29160
29161
29162
29163
29164
29165
29166
29167
29168
29169
29170
29171
29172
29173
29174
29175
29176
29177
29178
29179
29180
29181
29182
29183
29184
29185
29186
29187
29188
29189
29190
29191
29192
29193
29194
29195
29196
29197
29198
29199
29200
29201
29202
29203
29204
29205
29206
29207
29208
29209
29210
29211
29212
29213
29214
29215
29216
29217
29218
29219
29220
29221
29222
29223
29224
29225
29226
29227
29228
29229
29230
29231
29232
29233
29234
29235
29236
29237
29238
29239
29240
29241
29242
29243
29244
29245
29246
29247
29248
29249
29250
29251
29252
29253
29254
29255
29256
29257
29258
29259
29260
29261
29262
29263
29264
29265
29266
29267
29268
29269
29270
29271
29272
29273
29274
29275
29276
29277
29278
29279
29280
29281
29282
29283
29284
29285
29286
29287
29288
29289
29290
29291
29292
29293
29294
29295
29296
29297
29298
29299
29300
29301
29302
29303
29304
29305
29306
29307
29308
29309
29310
29311
29312
29313
29314
29315
29316
29317
29318
29319
29320
29321
29322
29323
29324
29325
29326
29327
29328
29329
29330
29331
29332
29333
29334
29335
29336
29337
29338
29339
29340
29341
29342
29343
29344
29345
29346
29347
29348
29349
29350
29351
29352
29353
29354
29355
29356
29357
29358
29359
29360
29361
29362
29363
29364
29365
29366
29367
29368
29369
29370
29371
29372
29373
29374
29375
29376
29377
29378
29379
29380
29381
29382
29383
29384
29385
29386
29387
29388
29389
29390
29391
29392
29393
29394
29395
29396
29397
29398
29399
29400
29401
29402
29403
29404
29405
29406
29407
29408
29409
29410
29411
29412
29413
29414
29415
29416
29417
29418
29419
29420
29421
29422
29423
29424
29425
29426
29427
29428
29429
29430
29431
29432
29433
29434
29435
29436
29437
29438
29439
29440
29441
29442
29443
29444
29445
29446
29447
29448
29449
29450
29451
29452
29453
29454
29455
29456
29457
29458
29459
29460
29461
29462
29463
29464
29465
29466
29467
29468
29469
29470
29471
29472
29473
29474
29475
29476
29477
29478
29479
29480
29481
29482
29483
29484
29485
29486
29487
29488
29489
29490
29491
29492
29493
29494
29495
29496
29497
29498
29499
29500
29501
29502
29503
29504
29505
29506
29507
29508
29509
29510
29511
29512
29513
29514
29515
29516
29517
29518
29519
29520
29521
29522
29523
29524
29525
29526
29527
29528
29529
29530
29531
29532
29533
29534
29535
29536
29537
29538
29539
29540
29541
29542
29543
29544
29545
29546
29547
29548
29549
29550
29551
29552
29553
29554
29555
29556
29557
29558
29559
29560
29561
29562
29563
29564
29565
29566
29567
29568
29569
29570
29571
29572
29573
29574
29575
29576
29577
29578
29579
29580
29581
29582
29583
29584
29585
29586
29587
29588
29589
29590
29591
29592
29593
29594
29595
29596
29597
29598
29599
29600
29601
29602
29603
29604
29605
29606
29607
29608
29609
29610
29611
29612
29613
29614
29615
29616
29617
29618
29619
29620
29621
29622
29623
29624
29625
29626
29627
29628
29629
29630
29631
29632
29633
29634
29635
29636
29637
29638
29639
29640
29641
29642
29643
29644
29645
29646
29647
29648
29649
29650
29651
29652
29653
29654
29655
29656
29657
29658
29659
29660
29661
29662
29663
29664
29665
29666
29667
29668
29669
29670
29671
29672
29673
29674
29675
29676
29677
29678
29679
29680
29681
29682
29683
29684
29685
29686
29687
29688
29689
29690
29691
29692
29693
29694
29695
29696
29697
29698
29699
29700
29701
29702
29703
29704
29705
29706
29707
29708
29709
29710
29711
29712
29713
29714
29715
29716
29717
29718
29719
29720
29721
29722
29723
29724
29725
29726
29727
29728
29729
29730
29731
29732
29733
29734
29735
29736
29737
29738
29739
29740
29741
29742
29743
29744
29745
29746
29747
29748
29749
29750
29751
29752
29753
29754
29755
29756
29757
29758
29759
29760
29761
29762
29763
29764
29765
29766
29767
29768
29769
29770
29771
29772
29773
29774
29775
29776
29777
29778
29779
29780
29781
29782
29783
29784
29785
29786
29787
29788
29789
29790
29791
29792
29793
29794
29795
29796
29797
29798
29799
29800
29801
29802
29803
29804
29805
29806
29807
29808
29809
29810
29811
29812
29813
29814
29815
29816
29817
29818
29819
29820
29821
29822
29823
29824
29825
29826
29827
29828
29829
29830
29831
29832
29833
29834
29835
29836
29837
29838
29839
29840
29841
29842
29843
29844
29845
29846
29847
29848
29849
29850
29851
29852
29853
29854
29855
29856
29857
29858
29859
29860
29861
29862
29863
29864
29865
29866
29867
29868
29869
29870
29871
29872
29873
29874
29875
29876
29877
29878
29879
29880
29881
29882
29883
29884
29885
29886
29887
29888
29889
29890
29891
29892
29893
29894
29895
29896
29897
29898
29899
29900
29901
29902
29903
29904
29905
29906
29907
29908
29909
29910
29911
29912
29913
29914
29915
29916
29917
29918
29919
29920
29921
29922
29923
29924
29925
29926
29927
29928
29929
29930
29931
29932
29933
29934
29935
29936
29937
29938
29939
29940
29941
29942
29943
29944
29945
29946
29947
29948
29949
29950
29951
29952
29953
29954
29955
29956
29957
29958
29959
29960
29961
29962
29963
29964
29965
29966
29967
29968
29969
29970
29971
29972
29973
29974
29975
29976
29977
29978
29979
29980
29981
29982
29983
29984
29985
29986
29987
29988
29989
29990
29991
29992
29993
29994
29995
29996
29997
29998
29999
30000
30001
30002
30003
30004
30005
30006
30007
30008
30009
30010
30011
30012
30013
30014
30015
30016
30017
30018
30019
30020
30021
30022
30023
30024
30025
30026
30027
30028
30029
30030
30031
30032
30033
30034
30035
30036
30037
30038
30039
30040
30041
30042
30043
30044
30045
30046
30047
30048
30049
30050
30051
30052
30053
30054
30055
30056
30057
30058
30059
30060
30061
30062
30063
30064
30065
30066
30067
30068
30069
30070
30071
30072
30073
30074
30075
30076
30077
30078
30079
30080
30081
30082
30083
30084
30085
30086
30087
30088
30089
30090
30091
30092
30093
30094
30095
30096
30097
30098
30099
30100
30101
30102
30103
30104
30105
30106
30107
30108
30109
30110
30111
30112
30113
30114
30115
30116
30117
30118
30119
30120
30121
30122
30123
30124
30125
30126
30127
30128
30129
30130
30131
30132
30133
30134
30135
30136
30137
30138
30139
30140
30141
30142
30143
30144
30145
30146
30147
30148
30149
30150
30151
30152
30153
30154
30155
30156
30157
30158
30159
30160
30161
30162
30163
30164
30165
30166
30167
30168
30169
30170
30171
30172
30173
30174
30175
30176
30177
30178
30179
30180
30181
30182
30183
30184
30185
30186
30187
30188
30189
30190
30191
30192
30193
30194
30195
30196
30197
30198
30199
30200
30201
30202
30203
30204
30205
30206
30207
30208
30209
30210
30211
30212
30213
30214
30215
30216
30217
30218
30219
30220
30221
30222
30223
30224
30225
30226
30227
30228
30229
30230
30231
30232
30233
30234
30235
30236
30237
30238
30239
30240
30241
30242
30243
30244
30245
30246
30247
30248
30249
30250
30251
30252
30253
30254
30255
30256
30257
30258
30259
30260
30261
30262
30263
30264
30265
30266
30267
30268
30269
30270
30271
30272
30273
30274
30275
30276
30277
30278
30279
30280
30281
30282
30283
30284
30285
30286
30287
30288
30289
30290
30291
30292
30293
30294
30295
30296
30297
30298
30299
30300
30301
30302
30303
30304
30305
30306
30307
30308
30309
30310
30311
30312
30313
30314
30315
30316
30317
30318
30319
30320
30321
30322
30323
30324
30325
30326
30327
30328
30329
30330
30331
30332
30333
30334
30335
30336
30337
30338
30339
30340
30341
30342
30343
30344
30345
30346
30347
30348
30349
30350
30351
30352
30353
30354
30355
30356
30357
30358
30359
30360
30361
30362
30363
30364
30365
30366
30367
30368
30369
30370
30371
30372
30373
30374
30375
30376
30377
30378
30379
30380
30381
30382
30383
30384
30385
30386
30387
30388
30389
30390
30391
30392
30393
30394
30395
30396
30397
30398
30399
30400
30401
30402
30403
30404
30405
30406
30407
30408
30409
30410
30411
30412
30413
30414
30415
30416
30417
30418
30419
30420
30421
30422
30423
30424
30425
30426
30427
30428
30429
30430
30431
30432
30433
30434
30435
30436
30437
30438
30439
30440
30441
30442
30443
30444
30445
30446
30447
30448
30449
30450
30451
30452
30453
30454
30455
30456
30457
30458
30459
30460
30461
30462
30463
30464
30465
30466
30467
30468
30469
30470
30471
30472
30473
30474
30475
30476
30477
30478
30479
30480
30481
30482
30483
30484
30485
30486
30487
30488
30489
30490
30491
30492
30493
30494
30495
30496
30497
30498
30499
30500
30501
30502
30503
30504
30505
30506
30507
30508
30509
30510
30511
30512
30513
30514
30515
30516
30517
30518
30519
30520
30521
30522
30523
30524
30525
30526
30527
30528
30529
30530
30531
30532
30533
30534
30535
30536
30537
30538
30539
30540
30541
30542
30543
30544
30545
30546
30547
30548
30549
30550
30551
30552
30553
30554
30555
30556
30557
30558
30559
30560
30561
30562
30563
30564
30565
30566
30567
30568
30569
30570
30571
30572
30573
30574
30575
30576
30577
30578
30579
30580
30581
30582
30583
30584
30585
30586
30587
30588
30589
30590
30591
30592
30593
30594
30595
30596
30597
30598
30599
30600
30601
30602
30603
30604
30605
30606
30607
30608
30609
30610
30611
30612
30613
30614
30615
30616
30617
30618
30619
30620
30621
30622
30623
30624
30625
30626
30627
30628
30629
30630
30631
30632
30633
30634
30635
30636
30637
30638
30639
30640
30641
30642
30643
30644
30645
30646
30647
30648
30649
30650
30651
30652
30653
30654
30655
30656
30657
30658
30659
30660
30661
30662
30663
30664
30665
30666
30667
30668
30669
30670
30671
30672
30673
30674
30675
30676
30677
30678
30679
30680
30681
30682
30683
30684
30685
30686
30687
30688
30689
30690
30691
30692
30693
30694
30695
30696
30697
30698
30699
30700
30701
30702
30703
30704
30705
30706
30707
30708
30709
30710
30711
30712
30713
30714
30715
30716
30717
30718
30719
30720
30721
30722
30723
30724
30725
30726
30727
30728
30729
30730
30731
30732
30733
30734
30735
30736
30737
30738
30739
30740
30741
30742
30743
30744
30745
30746
30747
30748
30749
30750
30751
30752
30753
30754
30755
30756
30757
30758
30759
30760
30761
30762
30763
30764
30765
30766
30767
30768
30769
30770
30771
30772
30773
30774
30775
30776
30777
30778
30779
30780
30781
30782
30783
30784
30785
30786
30787
30788
30789
30790
30791
30792
30793
30794
30795
30796
30797
30798
30799
30800
30801
30802
30803
30804
30805
30806
30807
30808
30809
30810
30811
30812
30813
30814
30815
30816
30817
30818
30819
30820
30821
30822
30823
30824
30825
30826
30827
30828
30829
30830
30831
30832
30833
30834
30835
30836
30837
30838
30839
30840
30841
30842
30843
30844
30845
30846
30847
30848
30849
30850
30851
30852
30853
30854
30855
30856
30857
30858
30859
30860
30861
30862
30863
30864
30865
30866
30867
30868
30869
30870
30871
30872
30873
30874
30875
30876
30877
30878
30879
30880
30881
30882
30883
30884
30885
30886
30887
30888
30889
30890
30891
30892
30893
30894
30895
30896
30897
30898
30899
30900
30901
30902
30903
30904
30905
30906
30907
30908
30909
30910
30911
30912
30913
30914
30915
30916
30917
30918
30919
30920
30921
30922
30923
30924
30925
30926
30927
30928
30929
30930
30931
30932
30933
30934
30935
30936
30937
30938
30939
30940
30941
30942
30943
30944
30945
30946
30947
30948
30949
30950
30951
30952
30953
30954
30955
30956
30957
30958
30959
30960
30961
30962
30963
30964
30965
30966
30967
30968
30969
30970
30971
30972
30973
30974
30975
30976
30977
30978
30979
30980
30981
30982
30983
30984
30985
30986
30987
30988
30989
30990
30991
30992
30993
30994
30995
30996
30997
30998
30999
31000
31001
31002
31003
31004
31005
31006
31007
31008
31009
31010
31011
31012
31013
31014
31015
31016
31017
31018
31019
31020
31021
31022
31023
31024
31025
31026
31027
31028
31029
31030
31031
31032
31033
31034
31035
31036
31037
31038
31039
31040
31041
31042
31043
31044
31045
31046
31047
31048
31049
31050
31051
31052
31053
31054
31055
31056
31057
31058
31059
31060
31061
31062
31063
31064
31065
31066
31067
31068
31069
31070
31071
31072
31073
31074
31075
31076
31077
31078
31079
31080
31081
31082
31083
31084
31085
31086
31087
31088
31089
31090
31091
31092
31093
31094
31095
31096
31097
31098
31099
31100
31101
31102
31103
31104
31105
31106
31107
31108
31109
31110
31111
31112
31113
31114
31115
31116
31117
31118
31119
31120
31121
31122
31123
31124
31125
31126
31127
31128
31129
31130
31131
31132
31133
31134
31135
31136
31137
31138
31139
31140
31141
31142
31143
31144
31145
31146
31147
31148
31149
31150
31151
31152
31153
31154
31155
31156
31157
31158
31159
31160
31161
31162
31163
31164
31165
31166
31167
31168
31169
31170
31171
31172
31173
31174
31175
31176
31177
31178
31179
31180
31181
31182
31183
31184
31185
31186
31187
31188
31189
31190
31191
31192
31193
31194
31195
31196
31197
31198
31199
31200
31201
31202
31203
31204
31205
31206
31207
31208
31209
31210
31211
31212
31213
31214
31215
31216
31217
31218
31219
31220
31221
31222
31223
31224
31225
31226
31227
31228
31229
31230
31231
31232
31233
31234
31235
31236
31237
31238
31239
31240
31241
31242
31243
31244
31245
31246
31247
31248
31249
31250
31251
31252
31253
31254
31255
31256
31257
31258
31259
31260
31261
31262
31263
31264
31265
31266
31267
31268
31269
31270
31271
31272
31273
31274
31275
31276
31277
31278
31279
31280
31281
31282
31283
31284
31285
31286
31287
31288
31289
31290
31291
31292
31293
31294
31295
31296
31297
31298
31299
31300
31301
31302
31303
31304
31305
31306
31307
31308
31309
31310
31311
31312
31313
31314
31315
31316
31317
31318
31319
31320
31321
31322
31323
31324
31325
31326
31327
31328
31329
31330
31331
31332
31333
31334
31335
31336
31337
31338
31339
31340
31341
31342
31343
31344
31345
31346
31347
31348
31349
31350
31351
31352
31353
31354
31355
31356
31357
31358
31359
31360
31361
31362
31363
31364
31365
31366
31367
31368
31369
31370
31371
31372
31373
31374
31375
31376
31377
31378
31379
31380
31381
31382
31383
31384
31385
31386
31387
31388
31389
31390
31391
31392
31393
31394
31395
31396
31397
31398
31399
31400
31401
31402
31403
31404
31405
31406
31407
31408
31409
31410
31411
31412
31413
31414
31415
31416
31417
31418
31419
31420
31421
31422
31423
31424
31425
31426
31427
31428
31429
31430
31431
31432
31433
31434
31435
31436
31437
31438
31439
31440
31441
31442
31443
31444
31445
31446
31447
31448
31449
31450
31451
31452
31453
31454
31455
31456
31457
31458
31459
31460
31461
31462
31463
31464
31465
31466
31467
31468
31469
31470
31471
31472
31473
31474
31475
31476
31477
31478
31479
31480
31481
31482
31483
31484
31485
31486
31487
31488
31489
31490
31491
31492
31493
31494
31495
31496
31497
31498
31499
31500
31501
31502
31503
31504
31505
31506
31507
31508
31509
31510
31511
31512
31513
31514
31515
31516
31517
31518
31519
31520
31521
31522
31523
31524
31525
31526
31527
31528
31529
31530
31531
31532
31533
31534
31535
31536
31537
31538
31539
31540
31541
31542
31543
31544
31545
31546
31547
31548
31549
31550
31551
31552
31553
31554
31555
31556
31557
31558
31559
31560
31561
31562
31563
31564
31565
31566
31567
31568
31569
31570
31571
31572
31573
31574
31575
31576
31577
31578
31579
31580
31581
31582
31583
31584
31585
31586
31587
31588
31589
31590
31591
31592
31593
31594
31595
31596
31597
31598
31599
31600
31601
31602
31603
31604
31605
31606
31607
31608
31609
31610
31611
31612
31613
31614
31615
31616
31617
31618
31619
31620
31621
31622
31623
31624
31625
31626
31627
31628
31629
31630
31631
31632
31633
31634
31635
31636
31637
31638
31639
31640
31641
31642
31643
31644
31645
31646
31647
31648
31649
31650
31651
31652
31653
31654
31655
31656
31657
31658
31659
31660
31661
31662
31663
31664
31665
31666
31667
31668
31669
31670
31671
31672
31673
31674
31675
31676
31677
31678
31679
31680
31681
31682
31683
31684
31685
31686
31687
31688
31689
31690
31691
31692
31693
31694
31695
31696
31697
31698
31699
31700
31701
31702
31703
31704
31705
31706
31707
31708
31709
31710
31711
31712
31713
31714
31715
31716
31717
31718
31719
31720
31721
31722
31723
31724
31725
31726
31727
31728
31729
31730
31731
31732
31733
31734
31735
31736
31737
31738
31739
31740
31741
31742
31743
31744
31745
31746
31747
31748
31749
31750
31751
31752
31753
31754
31755
31756
31757
31758
31759
31760
31761
31762
31763
31764
31765
31766
31767
31768
31769
31770
31771
31772
31773
31774
31775
31776
31777
31778
31779
31780
31781
31782
31783
31784
31785
31786
31787
31788
31789
31790
31791
31792
31793
31794
31795
31796
31797
31798
31799
31800
31801
31802
31803
31804
31805
31806
31807
31808
31809
31810
31811
31812
31813
31814
31815
31816
31817
31818
31819
31820
31821
31822
31823
31824
31825
31826
31827
31828
31829
31830
31831
31832
31833
31834
31835
31836
31837
31838
31839
31840
31841
31842
31843
31844
31845
31846
31847
31848
31849
31850
31851
31852
31853
31854
31855
31856
31857
31858
31859
31860
31861
31862
31863
31864
31865
31866
31867
31868
31869
31870
31871
31872
31873
31874
31875
31876
31877
31878
31879
31880
31881
31882
31883
31884
31885
31886
31887
31888
31889
31890
31891
31892
31893
31894
31895
31896
31897
31898
31899
31900
31901
31902
31903
31904
31905
31906
31907
31908
31909
31910
31911
31912
31913
31914
31915
31916
31917
31918
31919
31920
31921
31922
31923
31924
31925
31926
31927
31928
31929
31930
31931
31932
31933
31934
31935
31936
31937
31938
31939
31940
31941
31942
31943
31944
31945
31946
31947
31948
31949
31950
31951
31952
31953
31954
31955
31956
31957
31958
31959
31960
31961
31962
31963
31964
31965
31966
31967
31968
31969
31970
31971
31972
31973
31974
31975
31976
31977
31978
31979
31980
31981
31982
31983
31984
31985
31986
31987
31988
31989
31990
31991
31992
31993
31994
31995
31996
31997
31998
31999
32000
32001
32002
32003
32004
32005
32006
32007
32008
32009
32010
32011
32012
32013
32014
32015
32016
32017
32018
32019
32020
32021
32022
32023
32024
32025
32026
32027
32028
32029
32030
32031
32032
32033
32034
32035
32036
32037
32038
32039
32040
32041
32042
32043
32044
32045
32046
32047
32048
32049
32050
32051
32052
32053
32054
32055
32056
32057
32058
32059
32060
32061
32062
32063
32064
32065
32066
32067
32068
32069
32070
32071
32072
32073
32074
32075
32076
32077
32078
32079
32080
32081
32082
32083
32084
32085
32086
32087
32088
32089
32090
32091
32092
32093
32094
32095
32096
32097
32098
32099
32100
32101
32102
32103
32104
32105
32106
32107
32108
32109
32110
32111
32112
32113
32114
32115
32116
32117
32118
32119
32120
32121
32122
32123
32124
32125
32126
32127
32128
32129
32130
32131
32132
32133
32134
32135
32136
32137
32138
32139
32140
32141
32142
32143
32144
32145
32146
32147
32148
32149
32150
32151
32152
32153
32154
32155
32156
32157
32158
32159
32160
32161
32162
32163
32164
32165
32166
32167
32168
32169
32170
32171
32172
32173
32174
32175
32176
32177
32178
32179
32180
32181
32182
32183
32184
32185
32186
32187
32188
32189
32190
32191
32192
32193
32194
32195
32196
32197
32198
32199
32200
32201
32202
32203
32204
32205
32206
32207
32208
32209
32210
32211
32212
32213
32214
32215
32216
32217
32218
32219
32220
32221
32222
32223
32224
32225
32226
32227
32228
32229
32230
32231
32232
32233
32234
32235
32236
32237
32238
32239
32240
32241
32242
32243
32244
32245
32246
32247
32248
32249
32250
32251
32252
32253
32254
32255
32256
32257
32258
32259
32260
32261
32262
32263
32264
32265
32266
32267
32268
32269
32270
32271
32272
32273
32274
32275
32276
32277
32278
32279
32280
32281
32282
32283
32284
32285
32286
32287
32288
32289
32290
32291
32292
32293
32294
32295
32296
32297
32298
32299
32300
32301
32302
32303
32304
32305
32306
32307
32308
32309
32310
32311
32312
32313
32314
32315
32316
32317
32318
32319
32320
32321
32322
32323
32324
32325
32326
32327
32328
32329
32330
32331
32332
32333
32334
32335
32336
32337
32338
32339
32340
32341
32342
32343
32344
32345
32346
32347
32348
32349
32350
32351
32352
32353
32354
32355
32356
32357
32358
32359
32360
32361
32362
32363
32364
32365
32366
32367
32368
32369
32370
32371
32372
32373
32374
32375
32376
32377
32378
32379
32380
32381
32382
32383
32384
32385
32386
32387
32388
32389
32390
32391
32392
32393
32394
32395
32396
32397
32398
32399
32400
32401
32402
32403
32404
32405
32406
32407
32408
32409
32410
32411
32412
32413
32414
32415
32416
32417
32418
32419
32420
32421
32422
32423
32424
32425
32426
32427
32428
32429
32430
32431
32432
32433
32434
32435
32436
32437
32438
32439
32440
32441
32442
32443
32444
32445
32446
32447
32448
32449
32450
32451
32452
32453
32454
32455
32456
32457
32458
32459
32460
32461
32462
32463
32464
32465
32466
32467
32468
32469
32470
32471
32472
32473
32474
32475
32476
32477
32478
32479
32480
32481
32482
32483
32484
32485
32486
32487
32488
32489
32490
32491
32492
32493
32494
32495
32496
32497
32498
32499
32500
32501
32502
32503
32504
32505
32506
32507
32508
32509
32510
32511
32512
32513
32514
32515
32516
32517
32518
32519
32520
32521
32522
32523
32524
32525
32526
32527
32528
32529
32530
32531
32532
32533
32534
32535
32536
32537
32538
32539
32540
32541
32542
32543
32544
32545
32546
32547
32548
32549
32550
32551
32552
32553
32554
32555
32556
32557
32558
32559
32560
32561
32562
32563
32564
32565
32566
32567
32568
32569
32570
32571
32572
32573
32574
32575
32576
32577
32578
32579
32580
32581
32582
32583
32584
32585
32586
32587
32588
32589
32590
32591
32592
32593
32594
32595
32596
32597
32598
32599
32600
32601
32602
32603
32604
32605
32606
32607
32608
32609
32610
32611
32612
32613
32614
32615
32616
32617
32618
32619
32620
32621
32622
32623
32624
32625
32626
32627
32628
32629
32630
32631
32632
32633
32634
32635
32636
32637
32638
32639
32640
32641
32642
32643
32644
32645
32646
32647
32648
32649
32650
32651
32652
32653
32654
32655
32656
32657
32658
32659
32660
32661
32662
32663
32664
32665
32666
32667
32668
32669
32670
32671
32672
32673
32674
32675
32676
32677
32678
32679
32680
32681
32682
32683
32684
32685
32686
32687
32688
32689
32690
32691
32692
32693
32694
32695
32696
32697
32698
32699
32700
32701
32702
32703
32704
32705
32706
32707
32708
32709
32710
32711
32712
32713
32714
32715
32716
32717
32718
32719
32720
32721
32722
32723
32724
32725
32726
32727
32728
32729
32730
32731
32732
32733
32734
32735
32736
32737
32738
32739
32740
32741
32742
32743
32744
32745
32746
32747
32748
32749
32750
32751
32752
32753
32754
32755
32756
32757
32758
32759
32760
32761
32762
32763
32764
32765
32766
32767
32768
32769
32770
32771
32772
32773
32774
32775
32776
32777
32778
32779
32780
32781
32782
32783
32784
32785
32786
32787
32788
32789
32790
32791
32792
32793
32794
32795
32796
32797
32798
32799
32800
32801
32802
32803
32804
32805
32806
32807
32808
32809
32810
32811
32812
32813
32814
32815
32816
32817
32818
32819
32820
32821
32822
32823
32824
32825
32826
32827
32828
32829
32830
32831
32832
32833
32834
32835
32836
32837
32838
32839
32840
32841
32842
32843
32844
32845
32846
32847
32848
32849
32850
32851
32852
32853
32854
32855
32856
32857
32858
32859
32860
32861
32862
32863
32864
32865
32866
32867
32868
32869
32870
32871
32872
32873
32874
32875
32876
32877
32878
32879
32880
32881
32882
32883
32884
32885
32886
32887
32888
32889
32890
32891
32892
32893
32894
32895
32896
32897
32898
32899
32900
32901
32902
32903
32904
32905
32906
32907
32908
32909
32910
32911
32912
32913
32914
32915
32916
32917
32918
32919
32920
32921
32922
32923
32924
32925
32926
32927
32928
32929
32930
32931
32932
32933
32934
32935
32936
32937
32938
32939
32940
32941
32942
32943
32944
32945
32946
32947
32948
32949
32950
32951
32952
32953
32954
32955
32956
32957
32958
32959
32960
32961
32962
32963
32964
32965
32966
32967
32968
32969
32970
32971
32972
32973
32974
32975
32976
32977
32978
32979
32980
32981
32982
32983
32984
32985
32986
32987
32988
32989
32990
32991
32992
32993
32994
32995
32996
32997
32998
32999
33000
33001
33002
33003
33004
33005
33006
33007
33008
33009
33010
33011
33012
33013
33014
33015
33016
33017
33018
33019
33020
33021
33022
33023
33024
33025
33026
33027
33028
33029
33030
33031
33032
33033
33034
33035
33036
33037
33038
33039
33040
33041
33042
33043
33044
33045
33046
33047
33048
33049
33050
33051
33052
33053
33054
33055
33056
33057
33058
33059
33060
33061
33062
33063
33064
33065
33066
33067
33068
33069
33070
33071
33072
33073
33074
33075
33076
33077
33078
33079
33080
33081
33082
33083
33084
33085
33086
33087
33088
33089
33090
33091
33092
33093
33094
33095
33096
33097
33098
33099
33100
33101
33102
33103
33104
33105
33106
33107
33108
33109
33110
33111
33112
33113
33114
33115
33116
33117
33118
33119
33120
33121
33122
33123
33124
33125
33126
33127
33128
33129
33130
33131
33132
33133
33134
33135
33136
33137
33138
33139
33140
33141
33142
33143
33144
33145
33146
33147
33148
33149
33150
33151
33152
33153
33154
33155
33156
33157
33158
33159
33160
33161
33162
33163
33164
33165
33166
33167
33168
33169
33170
33171
33172
33173
33174
33175
33176
33177
33178
33179
33180
33181
33182
33183
33184
33185
33186
33187
33188
33189
33190
33191
33192
33193
33194
33195
33196
33197
33198
33199
33200
33201
33202
33203
33204
33205
33206
33207
33208
33209
33210
33211
33212
33213
33214
33215
33216
33217
33218
33219
33220
33221
33222
33223
33224
33225
33226
33227
33228
33229
33230
33231
33232
33233
33234
33235
33236
33237
33238
33239
33240
33241
33242
33243
33244
33245
33246
33247
33248
33249
33250
33251
33252
33253
33254
33255
33256
33257
33258
33259
33260
33261
33262
33263
33264
33265
33266
33267
33268
33269
33270
33271
33272
33273
33274
33275
33276
33277
33278
33279
33280
33281
33282
33283
33284
33285
33286
33287
33288
33289
33290
33291
33292
33293
33294
33295
33296
33297
33298
33299
33300
33301
33302
33303
33304
33305
33306
33307
33308
33309
33310
33311
33312
33313
33314
33315
33316
33317
33318
33319
33320
33321
33322
33323
33324
33325
33326
33327
33328
33329
33330
33331
33332
33333
33334
33335
33336
33337
33338
33339
33340
33341
33342
33343
33344
33345
33346
33347
33348
33349
33350
33351
33352
33353
33354
33355
33356
33357
33358
33359
33360
33361
33362
33363
33364
33365
33366
33367
33368
33369
33370
33371
33372
33373
33374
33375
33376
33377
33378
33379
33380
33381
33382
33383
33384
33385
33386
33387
33388
33389
33390
33391
33392
33393
33394
33395
33396
33397
33398
33399
33400
33401
33402
33403
33404
33405
33406
33407
33408
33409
33410
33411
33412
33413
33414
33415
33416
33417
33418
33419
33420
33421
33422
33423
33424
33425
33426
33427
33428
33429
33430
33431
33432
33433
33434
33435
33436
33437
33438
33439
33440
33441
33442
33443
33444
33445
33446
33447
33448
33449
33450
33451
33452
33453
33454
33455
33456
33457
33458
33459
33460
33461
33462
33463
33464
33465
33466
33467
33468
33469
33470
33471
33472
33473
33474
33475
33476
33477
33478
33479
33480
33481
33482
33483
33484
33485
33486
33487
33488
33489
33490
33491
33492
33493
33494
33495
33496
33497
33498
33499
33500
33501
33502
33503
33504
33505
33506
33507
33508
33509
33510
33511
33512
33513
33514
33515
33516
33517
33518
33519
33520
33521
33522
33523
33524
33525
33526
33527
33528
33529
33530
33531
33532
33533
33534
33535
33536
33537
33538
33539
33540
33541
33542
33543
33544
33545
33546
33547
33548
33549
33550
33551
33552
33553
33554
33555
33556
33557
33558
33559
33560
33561
33562
33563
33564
33565
33566
33567
33568
33569
33570
33571
33572
33573
33574
33575
33576
33577
33578
33579
33580
33581
33582
33583
33584
33585
33586
33587
33588
33589
33590
33591
33592
33593
33594
33595
33596
33597
33598
33599
33600
33601
33602
33603
33604
33605
33606
33607
33608
33609
33610
33611
33612
33613
33614
33615
33616
33617
33618
33619
33620
33621
33622
33623
33624
33625
33626
33627
33628
33629
33630
33631
33632
33633
33634
33635
33636
33637
33638
33639
33640
33641
33642
33643
33644
33645
33646
33647
33648
33649
33650
33651
33652
33653
33654
33655
33656
33657
33658
33659
33660
33661
33662
33663
33664
33665
33666
33667
33668
33669
33670
33671
33672
33673
33674
33675
33676
33677
33678
33679
33680
33681
33682
33683
33684
33685
33686
33687
33688
33689
33690
33691
33692
33693
33694
33695
33696
33697
33698
33699
33700
33701
33702
33703
33704
33705
33706
33707
33708
33709
33710
33711
33712
33713
33714
33715
33716
33717
33718
33719
33720
33721
33722
33723
33724
33725
33726
33727
33728
33729
33730
33731
33732
33733
33734
33735
33736
33737
33738
33739
33740
33741
33742
33743
33744
33745
33746
33747
33748
33749
33750
33751
33752
33753
33754
33755
33756
33757
33758
33759
33760
33761
33762
33763
33764
33765
33766
33767
33768
33769
33770
33771
33772
33773
33774
33775
33776
33777
33778
33779
33780
33781
33782
33783
33784
33785
33786
33787
33788
33789
33790
33791
33792
33793
33794
33795
33796
33797
33798
33799
33800
33801
33802
33803
33804
33805
33806
33807
33808
33809
33810
33811
33812
33813
33814
33815
33816
33817
33818
33819
33820
33821
33822
33823
33824
33825
33826
33827
33828
33829
33830
33831
33832
33833
33834
33835
33836
33837
33838
33839
33840
33841
33842
33843
33844
33845
33846
33847
33848
33849
33850
33851
33852
33853
33854
33855
33856
33857
33858
33859
33860
33861
33862
33863
33864
33865
33866
33867
33868
33869
33870
33871
33872
33873
33874
33875
33876
33877
33878
33879
33880
33881
33882
33883
33884
33885
33886
33887
33888
33889
33890
33891
33892
33893
33894
33895
33896
33897
33898
33899
33900
33901
33902
33903
33904
33905
33906
33907
33908
33909
33910
33911
33912
33913
33914
33915
33916
33917
33918
33919
33920
33921
33922
33923
33924
33925
33926
33927
33928
33929
33930
33931
33932
33933
33934
33935
33936
33937
33938
33939
33940
33941
33942
33943
33944
33945
33946
33947
33948
33949
33950
33951
33952
33953
33954
33955
33956
33957
33958
33959
33960
33961
33962
33963
33964
33965
33966
33967
33968
33969
33970
33971
33972
33973
33974
33975
33976
33977
33978
33979
33980
33981
33982
33983
33984
33985
33986
33987
33988
33989
33990
33991
33992
33993
33994
33995
33996
33997
33998
33999
34000
34001
34002
34003
34004
34005
34006
34007
34008
34009
34010
34011
34012
34013
34014
34015
34016
34017
34018
34019
34020
34021
34022
34023
34024
34025
34026
34027
34028
34029
34030
34031
34032
34033
34034
34035
34036
34037
34038
34039
34040
34041
34042
34043
34044
34045
34046
34047
34048
34049
34050
34051
34052
34053
34054
34055
34056
34057
34058
34059
34060
34061
34062
34063
34064
34065
34066
34067
34068
34069
34070
34071
34072
34073
34074
34075
34076
34077
34078
34079
34080
34081
34082
34083
34084
34085
34086
34087
34088
34089
34090
34091
34092
34093
34094
34095
34096
34097
34098
34099
34100
34101
34102
34103
34104
34105
34106
34107
34108
34109
34110
34111
34112
34113
34114
34115
34116
34117
34118
34119
34120
34121
34122
34123
34124
34125
34126
34127
34128
34129
34130
34131
34132
34133
34134
34135
34136
34137
34138
34139
34140
34141
34142
34143
34144
34145
34146
34147
34148
34149
34150
34151
34152
34153
34154
34155
34156
34157
34158
34159
34160
34161
34162
34163
34164
34165
34166
34167
34168
34169
34170
34171
34172
34173
34174
34175
34176
34177
34178
34179
34180
34181
34182
34183
34184
34185
34186
34187
34188
34189
34190
34191
34192
34193
34194
34195
34196
34197
34198
34199
34200
34201
34202
34203
34204
34205
34206
34207
34208
34209
34210
34211
34212
34213
34214
34215
34216
34217
34218
34219
34220
34221
34222
34223
34224
34225
34226
34227
34228
34229
34230
34231
34232
34233
34234
34235
34236
34237
34238
34239
34240
34241
34242
34243
34244
34245
34246
34247
34248
34249
34250
34251
34252
34253
34254
34255
34256
34257
34258
34259
34260
34261
34262
34263
34264
34265
34266
34267
34268
34269
34270
34271
34272
34273
34274
34275
34276
34277
34278
34279
34280
34281
34282
34283
34284
34285
34286
34287
34288
34289
34290
34291
34292
34293
34294
34295
34296
34297
34298
34299
34300
34301
34302
34303
34304
34305
34306
34307
34308
34309
34310
34311
34312
34313
34314
34315
34316
34317
34318
34319
34320
34321
34322
34323
34324
34325
34326
34327
34328
34329
34330
34331
34332
34333
34334
34335
34336
34337
34338
34339
34340
34341
34342
34343
34344
34345
34346
34347
34348
34349
34350
34351
34352
34353
34354
34355
34356
34357
34358
34359
34360
34361
34362
34363
34364
34365
34366
34367
34368
34369
34370
34371
34372
34373
34374
34375
34376
34377
34378
34379
34380
34381
34382
34383
34384
34385
34386
34387
34388
34389
34390
34391
34392
34393
34394
34395
34396
34397
34398
34399
34400
34401
34402
34403
34404
34405
34406
34407
34408
34409
34410
34411
34412
34413
34414
34415
34416
34417
34418
34419
34420
34421
34422
34423
34424
34425
34426
34427
34428
34429
34430
34431
34432
34433
34434
34435
34436
34437
34438
34439
34440
34441
34442
34443
34444
34445
34446
34447
34448
34449
34450
34451
34452
34453
34454
34455
34456
34457
34458
34459
34460
34461
34462
34463
34464
34465
34466
34467
34468
34469
34470
34471
34472
34473
34474
34475
34476
34477
34478
34479
34480
34481
34482
34483
34484
34485
34486
34487
34488
34489
34490
34491
34492
34493
34494
34495
34496
34497
34498
34499
34500
34501
34502
34503
34504
34505
34506
34507
34508
34509
34510
34511
34512
34513
34514
34515
34516
34517
34518
34519
34520
34521
34522
34523
34524
34525
34526
34527
34528
34529
34530
34531
34532
34533
34534
34535
34536
34537
34538
34539
34540
34541
34542
34543
34544
34545
34546
34547
34548
34549
34550
34551
34552
34553
34554
34555
34556
34557
34558
34559
34560
34561
34562
34563
34564
34565
34566
34567
34568
34569
34570
34571
34572
34573
34574
34575
34576
34577
34578
34579
34580
34581
34582
34583
34584
34585
34586
34587
34588
34589
34590
34591
34592
34593
34594
34595
34596
34597
34598
34599
34600
34601
34602
34603
34604
34605
34606
34607
34608
34609
34610
34611
34612
34613
34614
34615
34616
34617
34618
34619
34620
34621
34622
34623
34624
34625
34626
34627
34628
34629
34630
34631
34632
34633
34634
34635
34636
34637
34638
34639
34640
34641
34642
34643
34644
34645
34646
34647
34648
34649
34650
34651
34652
34653
34654
34655
34656
34657
34658
34659
34660
34661
34662
34663
34664
34665
34666
34667
34668
34669
34670
34671
34672
34673
34674
34675
34676
34677
34678
34679
34680
34681
34682
34683
34684
34685
34686
34687
34688
34689
34690
34691
34692
34693
34694
34695
34696
34697
34698
34699
34700
34701
34702
34703
34704
34705
34706
34707
34708
34709
34710
34711
34712
34713
34714
34715
34716
34717
34718
34719
34720
34721
34722
34723
34724
34725
34726
34727
34728
34729
34730
34731
34732
34733
34734
34735
34736
34737
34738
34739
34740
34741
34742
34743
34744
34745
34746
34747
34748
34749
34750
34751
34752
34753
34754
34755
34756
34757
34758
34759
34760
34761
34762
34763
34764
34765
34766
34767
34768
34769
34770
34771
34772
34773
34774
34775
34776
34777
34778
34779
34780
34781
34782
34783
34784
34785
34786
34787
34788
34789
34790
34791
34792
34793
34794
34795
34796
34797
34798
34799
34800
34801
34802
34803
34804
34805
34806
34807
34808
34809
34810
34811
34812
34813
34814
34815
34816
34817
34818
34819
34820
34821
34822
34823
34824
34825
34826
34827
34828
34829
34830
34831
34832
34833
34834
34835
34836
34837
34838
34839
34840
34841
34842
34843
34844
34845
34846
34847
34848
34849
34850
34851
34852
34853
34854
34855
34856
34857
34858
34859
34860
34861
34862
34863
34864
34865
34866
34867
34868
34869
34870
34871
34872
34873
34874
34875
34876
34877
34878
34879
34880
34881
34882
34883
34884
34885
34886
34887
34888
34889
34890
34891
34892
34893
34894
34895
34896
34897
34898
34899
34900
34901
34902
34903
34904
34905
34906
34907
34908
34909
34910
34911
34912
34913
34914
34915
34916
34917
34918
34919
34920
34921
34922
34923
34924
34925
34926
34927
34928
34929
34930
34931
34932
34933
34934
34935
34936
34937
34938
34939
34940
34941
34942
34943
34944
34945
34946
34947
34948
34949
34950
34951
34952
34953
34954
34955
34956
34957
34958
34959
34960
34961
34962
34963
34964
34965
34966
34967
34968
34969
34970
34971
34972
34973
34974
34975
34976
34977
34978
34979
34980
34981
34982
34983
34984
34985
34986
34987
34988
34989
34990
34991
34992
34993
34994
34995
34996
34997
34998
34999
35000
35001
35002
35003
35004
35005
35006
35007
35008
35009
35010
35011
35012
35013
35014
35015
35016
35017
35018
35019
35020
35021
35022
35023
35024
35025
35026
35027
35028
35029
35030
35031
35032
35033
35034
35035
35036
35037
35038
35039
35040
35041
35042
35043
35044
35045
35046
35047
35048
35049
35050
35051
35052
35053
35054
35055
35056
35057
35058
35059
35060
35061
35062
35063
35064
35065
35066
35067
35068
35069
35070
35071
35072
35073
35074
35075
35076
35077
35078
35079
35080
35081
35082
35083
35084
35085
35086
35087
35088
35089
35090
35091
35092
35093
35094
35095
35096
35097
35098
35099
35100
35101
35102
35103
35104
35105
35106
35107
35108
35109
35110
35111
35112
35113
35114
35115
35116
35117
35118
35119
35120
35121
35122
35123
35124
35125
35126
35127
35128
35129
35130
35131
35132
35133
35134
35135
35136
35137
35138
35139
35140
35141
35142
35143
35144
35145
35146
35147
35148
35149
35150
35151
35152
35153
35154
35155
35156
35157
35158
35159
35160
35161
35162
35163
35164
35165
35166
35167
35168
35169
35170
35171
35172
35173
35174
35175
35176
35177
35178
35179
35180
35181
35182
35183
35184
35185
35186
35187
35188
35189
35190
35191
35192
35193
35194
35195
35196
35197
35198
35199
35200
35201
35202
35203
35204
35205
35206
35207
35208
35209
35210
35211
35212
35213
35214
35215
35216
35217
35218
35219
35220
35221
35222
35223
35224
35225
35226
35227
35228
35229
35230
35231
35232
35233
35234
35235
35236
35237
35238
35239
35240
35241
35242
35243
35244
35245
35246
35247
35248
35249
35250
35251
35252
35253
35254
35255
35256
35257
35258
35259
35260
35261
35262
35263
35264
35265
35266
35267
35268
35269
35270
35271
35272
35273
35274
35275
35276
35277
35278
35279
35280
35281
35282
35283
35284
35285
35286
35287
35288
35289
35290
35291
35292
35293
35294
35295
35296
35297
35298
35299
35300
35301
35302
35303
35304
35305
35306
35307
35308
35309
35310
35311
35312
35313
35314
35315
35316
35317
35318
35319
35320
35321
35322
35323
35324
35325
35326
35327
35328
35329
35330
35331
35332
35333
35334
35335
35336
35337
35338
35339
35340
35341
35342
35343
35344
35345
35346
35347
35348
35349
35350
35351
35352
35353
35354
35355
35356
35357
35358
35359
35360
35361
35362
35363
35364
35365
35366
35367
35368
35369
35370
35371
35372
35373
35374
35375
35376
35377
35378
35379
35380
35381
35382
35383
35384
35385
35386
35387
35388
35389
35390
35391
35392
35393
35394
35395
35396
35397
35398
35399
35400
35401
35402
35403
35404
35405
35406
35407
35408
35409
35410
35411
35412
35413
35414
35415
35416
35417
35418
35419
35420
35421
35422
35423
35424
35425
35426
35427
35428
35429
35430
35431
35432
35433
35434
35435
35436
35437
35438
35439
35440
35441
35442
35443
35444
35445
35446
35447
35448
35449
35450
35451
35452
35453
35454
35455
35456
35457
35458
35459
35460
35461
35462
35463
35464
35465
35466
35467
35468
35469
35470
35471
35472
35473
35474
35475
35476
35477
35478
35479
35480
35481
35482
35483
35484
35485
35486
35487
35488
35489
35490
35491
35492
35493
35494
35495
35496
35497
35498
35499
35500
35501
35502
35503
35504
35505
35506
35507
35508
35509
35510
35511
35512
35513
35514
35515
35516
35517
35518
35519
35520
35521
35522
35523
35524
35525
35526
35527
35528
35529
35530
35531
35532
35533
35534
35535
35536
35537
35538
35539
35540
35541
35542
35543
35544
35545
35546
35547
35548
35549
35550
35551
35552
35553
35554
35555
35556
35557
35558
35559
35560
35561
35562
35563
35564
35565
35566
35567
35568
35569
35570
35571
35572
35573
35574
35575
35576
35577
35578
35579
35580
35581
35582
35583
35584
35585
35586
35587
35588
35589
35590
35591
35592
35593
35594
35595
35596
35597
35598
35599
35600
35601
35602
35603
35604
35605
35606
35607
35608
35609
35610
35611
35612
35613
35614
35615
35616
35617
35618
35619
35620
35621
35622
35623
35624
35625
35626
35627
35628
35629
35630
35631
35632
35633
35634
35635
35636
35637
35638
35639
35640
35641
35642
35643
35644
35645
35646
35647
35648
35649
35650
35651
35652
35653
35654
35655
35656
35657
35658
35659
35660
35661
35662
35663
35664
35665
35666
35667
35668
35669
35670
35671
35672
35673
35674
35675
35676
35677
35678
35679
35680
35681
35682
35683
35684
35685
35686
35687
35688
35689
35690
35691
35692
35693
35694
35695
35696
35697
35698
35699
35700
35701
35702
35703
35704
35705
35706
35707
35708
35709
35710
35711
35712
35713
35714
35715
35716
35717
35718
35719
35720
35721
35722
35723
35724
35725
35726
35727
35728
35729
35730
35731
35732
35733
35734
35735
35736
35737
35738
35739
35740
35741
35742
35743
35744
35745
35746
35747
35748
35749
35750
35751
35752
35753
35754
35755
35756
35757
35758
35759
35760
35761
35762
35763
35764
35765
35766
35767
35768
35769
35770
35771
35772
35773
35774
35775
35776
35777
35778
35779
35780
35781
35782
35783
35784
35785
35786
35787
35788
35789
35790
35791
35792
35793
35794
35795
35796
35797
35798
35799
35800
35801
35802
35803
35804
35805
35806
35807
35808
35809
35810
35811
35812
35813
35814
35815
35816
35817
35818
35819
35820
35821
35822
35823
35824
35825
35826
35827
35828
35829
35830
35831
35832
35833
35834
35835
35836
35837
35838
35839
35840
35841
35842
35843
35844
35845
35846
35847
35848
35849
35850
35851
35852
35853
35854
35855
35856
35857
35858
35859
35860
35861
35862
35863
35864
35865
35866
35867
35868
35869
35870
35871
35872
35873
35874
35875
35876
35877
35878
35879
35880
35881
35882
35883
35884
35885
35886
35887
35888
35889
35890
35891
35892
35893
35894
35895
35896
35897
35898
35899
35900
35901
35902
35903
35904
35905
35906
35907
35908
35909
35910
35911
35912
35913
35914
35915
35916
35917
35918
35919
35920
35921
35922
35923
35924
35925
35926
35927
35928
35929
35930
35931
35932
35933
35934
35935
35936
35937
35938
35939
35940
35941
35942
35943
35944
35945
35946
35947
35948
35949
35950
35951
35952
35953
35954
35955
35956
35957
35958
35959
35960
35961
35962
35963
35964
35965
35966
35967
35968
35969
35970
35971
35972
35973
35974
35975
35976
35977
35978
35979
35980
35981
35982
35983
35984
35985
35986
35987
35988
35989
35990
35991
35992
35993
35994
35995
35996
35997
35998
35999
36000
36001
36002
36003
36004
36005
36006
36007
36008
36009
36010
36011
36012
36013
36014
36015
36016
36017
36018
36019
36020
36021
36022
36023
36024
36025
36026
36027
36028
36029
36030
36031
36032
36033
36034
36035
36036
36037
36038
36039
36040
36041
36042
36043
36044
36045
36046
36047
36048
36049
36050
36051
36052
36053
36054
36055
36056
36057
36058
36059
36060
36061
36062
36063
36064
36065
36066
36067
36068
36069
36070
36071
36072
36073
36074
36075
36076
36077
36078
36079
36080
36081
36082
36083
36084
36085
36086
36087
36088
36089
36090
36091
36092
36093
36094
36095
36096
36097
36098
36099
36100
36101
36102
36103
36104
36105
36106
36107
36108
36109
36110
36111
36112
36113
36114
36115
36116
36117
36118
36119
36120
36121
36122
36123
36124
36125
36126
36127
36128
36129
36130
36131
36132
36133
36134
36135
36136
36137
36138
36139
36140
36141
36142
36143
36144
36145
36146
36147
36148
36149
36150
36151
36152
36153
36154
36155
36156
36157
36158
36159
36160
36161
36162
36163
36164
36165
36166
36167
36168
36169
36170
36171
36172
36173
36174
36175
36176
36177
36178
36179
36180
36181
36182
36183
36184
36185
36186
36187
36188
36189
36190
36191
36192
36193
36194
36195
36196
36197
36198
36199
36200
36201
36202
36203
36204
36205
36206
36207
36208
36209
36210
36211
36212
36213
36214
36215
36216
36217
36218
36219
36220
36221
36222
36223
36224
36225
36226
36227
36228
36229
36230
36231
36232
36233
36234
36235
36236
36237
36238
36239
36240
36241
36242
36243
36244
36245
36246
36247
36248
36249
36250
36251
36252
36253
36254
36255
36256
36257
36258
36259
36260
36261
36262
36263
36264
36265
36266
36267
36268
36269
36270
36271
36272
36273
36274
36275
36276
36277
36278
36279
36280
36281
36282
36283
36284
36285
36286
36287
36288
36289
36290
36291
36292
36293
36294
36295
36296
36297
36298
36299
36300
36301
36302
36303
36304
36305
36306
36307
36308
36309
36310
36311
36312
36313
36314
36315
36316
36317
36318
36319
36320
36321
36322
36323
36324
36325
36326
36327
36328
36329
36330
36331
36332
36333
36334
36335
36336
36337
36338
36339
36340
36341
36342
36343
36344
36345
36346
36347
36348
36349
36350
36351
36352
36353
36354
36355
36356
36357
36358
36359
36360
36361
36362
36363
36364
36365
36366
36367
36368
36369
36370
36371
36372
36373
36374
36375
36376
36377
36378
36379
36380
36381
36382
36383
36384
36385
36386
36387
36388
36389
36390
36391
36392
36393
36394
36395
36396
36397
36398
36399
36400
36401
36402
36403
36404
36405
36406
36407
36408
36409
36410
36411
36412
36413
36414
36415
36416
36417
36418
36419
36420
36421
36422
36423
36424
36425
36426
36427
36428
36429
36430
36431
36432
36433
36434
36435
36436
36437
36438
36439
36440
36441
36442
36443
36444
36445
36446
36447
36448
36449
36450
36451
36452
36453
36454
36455
36456
36457
36458
36459
36460
36461
36462
36463
36464
36465
36466
36467
36468
36469
36470
36471
36472
36473
36474
36475
36476
36477
36478
36479
36480
36481
36482
36483
36484
36485
36486
36487
36488
36489
36490
36491
36492
36493
36494
36495
36496
36497
36498
36499
36500
36501
36502
36503
36504
36505
36506
36507
36508
36509
36510
36511
36512
36513
36514
36515
36516
36517
36518
36519
36520
36521
36522
36523
36524
36525
36526
36527
36528
36529
36530
36531
36532
36533
36534
36535
36536
36537
36538
36539
36540
36541
36542
36543
36544
36545
36546
36547
36548
36549
36550
36551
36552
36553
36554
36555
36556
36557
36558
36559
36560
36561
36562
36563
36564
36565
36566
36567
36568
36569
36570
36571
36572
36573
36574
36575
36576
36577
36578
36579
36580
36581
36582
36583
36584
36585
36586
36587
36588
36589
36590
36591
36592
36593
36594
36595
36596
36597
36598
36599
36600
36601
36602
36603
36604
36605
36606
36607
36608
36609
36610
36611
36612
36613
36614
36615
36616
36617
36618
36619
36620
36621
36622
36623
36624
36625
36626
36627
36628
36629
36630
36631
36632
36633
36634
36635
36636
36637
36638
36639
36640
36641
36642
36643
36644
36645
36646
36647
36648
36649
36650
36651
36652
36653
36654
36655
36656
36657
36658
36659
36660
36661
36662
36663
36664
36665
36666
36667
36668
36669
36670
36671
36672
36673
36674
36675
36676
36677
36678
36679
36680
36681
36682
36683
36684
36685
36686
36687
36688
36689
36690
36691
36692
36693
36694
36695
36696
36697
36698
36699
36700
36701
36702
36703
36704
36705
36706
36707
36708
36709
36710
36711
36712
36713
36714
36715
36716
36717
36718
36719
36720
36721
36722
36723
36724
36725
36726
36727
36728
36729
36730
36731
36732
36733
36734
36735
36736
36737
36738
36739
36740
36741
36742
36743
36744
36745
36746
36747
36748
36749
36750
36751
36752
36753
36754
36755
36756
36757
36758
36759
36760
36761
36762
36763
36764
36765
36766
36767
36768
36769
36770
36771
36772
36773
36774
36775
36776
36777
36778
36779
36780
36781
36782
36783
36784
36785
36786
36787
36788
36789
36790
36791
36792
36793
36794
36795
36796
36797
36798
36799
36800
36801
36802
36803
36804
36805
36806
36807
36808
36809
36810
36811
36812
36813
36814
36815
36816
36817
36818
36819
36820
36821
36822
36823
36824
36825
36826
36827
36828
36829
36830
36831
36832
36833
36834
36835
36836
36837
36838
36839
36840
36841
36842
36843
36844
36845
36846
36847
36848
36849
36850
36851
36852
36853
36854
36855
36856
36857
36858
36859
36860
36861
36862
36863
36864
36865
36866
36867
36868
36869
36870
36871
36872
36873
36874
36875
36876
36877
36878
36879
36880
36881
36882
36883
36884
36885
36886
36887
36888
36889
36890
36891
36892
36893
36894
36895
36896
36897
36898
36899
36900
36901
36902
36903
36904
36905
36906
36907
36908
36909
36910
36911
36912
36913
36914
36915
36916
36917
36918
36919
36920
36921
36922
36923
36924
36925
36926
36927
36928
36929
36930
36931
36932
36933
36934
36935
36936
36937
36938
36939
36940
36941
36942
36943
36944
36945
36946
36947
36948
36949
36950
36951
36952
36953
36954
36955
36956
36957
36958
36959
36960
36961
36962
36963
36964
36965
36966
36967
36968
36969
36970
36971
36972
36973
36974
36975
36976
36977
36978
36979
36980
36981
36982
36983
36984
36985
36986
36987
36988
36989
36990
36991
36992
36993
36994
36995
36996
36997
36998
36999
37000
37001
37002
37003
37004
37005
37006
37007
37008
37009
37010
37011
37012
37013
37014
37015
37016
37017
37018
37019
37020
37021
37022
37023
37024
37025
37026
37027
37028
37029
37030
37031
37032
37033
37034
37035
37036
37037
37038
37039
37040
37041
37042
37043
37044
37045
37046
37047
37048
37049
37050
37051
37052
37053
37054
37055
37056
37057
37058
37059
37060
37061
37062
37063
37064
37065
37066
37067
37068
37069
37070
37071
37072
37073
37074
37075
37076
37077
37078
37079
37080
37081
37082
37083
37084
37085
37086
37087
37088
37089
37090
37091
37092
37093
37094
37095
37096
37097
37098
37099
37100
37101
37102
37103
37104
37105
37106
37107
37108
37109
37110
37111
37112
37113
37114
37115
37116
37117
37118
37119
37120
37121
37122
37123
37124
37125
37126
37127
37128
37129
37130
37131
37132
37133
37134
37135
37136
37137
37138
37139
37140
37141
37142
37143
37144
37145
37146
37147
37148
37149
37150
37151
37152
37153
37154
37155
37156
37157
37158
37159
37160
37161
37162
37163
37164
37165
37166
37167
37168
37169
37170
37171
37172
37173
37174
37175
37176
37177
37178
37179
37180
37181
37182
37183
37184
37185
37186
37187
37188
37189
37190
37191
37192
37193
37194
37195
37196
37197
37198
37199
37200
37201
37202
37203
37204
37205
37206
37207
37208
37209
37210
37211
37212
37213
37214
37215
37216
37217
37218
37219
37220
37221
37222
37223
37224
37225
37226
37227
37228
37229
37230
37231
37232
37233
37234
37235
37236
37237
37238
37239
37240
37241
37242
37243
37244
37245
37246
37247
37248
37249
37250
37251
37252
37253
37254
37255
37256
37257
37258
37259
37260
37261
37262
37263
37264
37265
37266
37267
37268
37269
37270
37271
37272
37273
37274
37275
37276
37277
37278
37279
37280
37281
37282
37283
37284
37285
37286
37287
37288
37289
37290
37291
37292
37293
37294
37295
37296
37297
37298
37299
37300
37301
37302
37303
37304
37305
37306
37307
37308
37309
37310
37311
37312
37313
37314
37315
37316
37317
37318
37319
37320
37321
37322
37323
37324
37325
37326
37327
37328
37329
37330
37331
37332
37333
37334
37335
37336
37337
37338
37339
37340
37341
37342
37343
37344
37345
37346
37347
37348
37349
37350
37351
37352
37353
37354
37355
37356
37357
37358
37359
37360
37361
37362
37363
37364
37365
37366
37367
37368
37369
37370
37371
37372
37373
37374
37375
37376
37377
37378
37379
37380
37381
37382
37383
37384
37385
37386
37387
37388
37389
37390
37391
37392
37393
37394
37395
37396
37397
37398
37399
37400
37401
37402
37403
37404
37405
37406
37407
37408
37409
37410
37411
37412
37413
37414
37415
37416
37417
37418
37419
37420
37421
37422
37423
37424
37425
37426
37427
37428
37429
37430
37431
37432
37433
37434
37435
37436
37437
37438
37439
37440
37441
37442
37443
37444
37445
37446
37447
37448
37449
37450
37451
37452
37453
37454
37455
37456
37457
37458
37459
37460
37461
37462
37463
37464
37465
37466
37467
37468
37469
37470
37471
37472
37473
37474
37475
37476
37477
37478
37479
37480
37481
37482
37483
37484
37485
37486
37487
37488
37489
37490
37491
37492
37493
37494
37495
37496
37497
37498
37499
37500
37501
37502
37503
37504
37505
37506
37507
37508
37509
37510
37511
37512
37513
37514
37515
37516
37517
37518
37519
37520
37521
37522
37523
37524
37525
37526
37527
37528
37529
37530
37531
37532
37533
37534
37535
37536
37537
37538
37539
37540
37541
37542
37543
37544
37545
37546
37547
37548
37549
37550
37551
37552
37553
37554
37555
37556
37557
37558
37559
37560
37561
37562
37563
37564
37565
37566
37567
37568
37569
37570
37571
37572
37573
37574
37575
37576
37577
37578
37579
37580
37581
37582
37583
37584
37585
37586
37587
37588
37589
37590
37591
37592
37593
37594
37595
37596
37597
37598
37599
37600
37601
37602
37603
37604
37605
37606
37607
37608
37609
37610
37611
37612
37613
37614
37615
37616
37617
37618
37619
37620
37621
37622
37623
37624
37625
37626
37627
37628
37629
37630
37631
37632
37633
37634
37635
37636
37637
37638
37639
37640
37641
37642
37643
37644
37645
37646
37647
37648
37649
37650
37651
37652
37653
37654
37655
37656
37657
37658
37659
37660
37661
37662
37663
37664
37665
37666
37667
37668
37669
37670
37671
37672
37673
37674
37675
37676
37677
37678
37679
37680
37681
37682
37683
37684
37685
37686
37687
37688
37689
37690
37691
37692
37693
37694
37695
37696
37697
37698
37699
37700
37701
37702
37703
37704
37705
37706
37707
37708
37709
37710
37711
37712
37713
37714
37715
37716
37717
37718
37719
37720
37721
37722
37723
37724
37725
37726
37727
37728
37729
37730
37731
37732
37733
37734
37735
37736
37737
37738
37739
37740
37741
37742
37743
37744
37745
37746
37747
37748
37749
37750
37751
37752
37753
37754
37755
37756
37757
37758
37759
37760
37761
37762
37763
37764
37765
37766
37767
37768
37769
37770
37771
37772
37773
37774
37775
37776
37777
37778
37779
37780
37781
37782
37783
37784
37785
37786
37787
37788
37789
37790
37791
37792
37793
37794
37795
37796
37797
37798
37799
37800
37801
37802
37803
37804
37805
37806
37807
37808
37809
37810
37811
37812
37813
37814
37815
37816
37817
37818
37819
37820
37821
37822
37823
37824
37825
37826
37827
37828
37829
37830
37831
37832
37833
37834
37835
37836
37837
37838
37839
37840
37841
37842
37843
37844
37845
37846
37847
37848
37849
37850
37851
37852
37853
37854
37855
37856
37857
37858
37859
37860
37861
37862
37863
37864
37865
37866
37867
37868
37869
37870
37871
37872
37873
37874
37875
37876
37877
37878
37879
37880
37881
37882
37883
37884
37885
37886
37887
37888
37889
37890
37891
37892
37893
37894
37895
37896
37897
37898
37899
37900
37901
37902
37903
37904
37905
37906
37907
37908
37909
37910
37911
37912
37913
37914
37915
37916
37917
37918
37919
37920
37921
37922
37923
37924
37925
37926
37927
37928
37929
37930
37931
37932
37933
37934
37935
37936
37937
37938
37939
37940
37941
37942
37943
37944
37945
37946
37947
37948
37949
37950
37951
37952
37953
37954
37955
37956
37957
37958
37959
37960
37961
37962
37963
37964
37965
37966
37967
37968
37969
37970
37971
37972
37973
37974
37975
37976
37977
37978
37979
37980
37981
37982
37983
37984
37985
37986
37987
37988
37989
37990
37991
37992
37993
37994
37995
37996
37997
37998
37999
38000
38001
38002
38003
38004
38005
38006
38007
38008
38009
38010
38011
38012
38013
38014
38015
38016
38017
38018
38019
38020
38021
38022
38023
38024
38025
38026
38027
38028
38029
38030
38031
38032
38033
38034
38035
38036
38037
38038
38039
38040
38041
38042
38043
38044
38045
38046
38047
38048
38049
38050
38051
38052
38053
38054
38055
38056
38057
38058
38059
38060
38061
38062
38063
38064
38065
38066
38067
38068
38069
38070
38071
38072
38073
38074
38075
38076
38077
38078
38079
38080
38081
38082
38083
38084
38085
38086
38087
38088
38089
38090
38091
38092
38093
38094
38095
38096
38097
38098
38099
38100
38101
38102
38103
38104
38105
38106
38107
38108
38109
38110
38111
38112
38113
38114
38115
38116
38117
38118
38119
38120
38121
38122
38123
38124
38125
38126
38127
38128
38129
38130
38131
38132
38133
38134
38135
38136
38137
38138
38139
38140
38141
38142
38143
38144
38145
38146
38147
38148
38149
38150
38151
38152
38153
38154
38155
38156
38157
38158
38159
38160
38161
38162
38163
38164
38165
38166
38167
38168
38169
38170
38171
38172
38173
38174
38175
38176
38177
38178
38179
38180
38181
38182
38183
38184
38185
38186
38187
38188
38189
38190
38191
38192
38193
38194
38195
38196
38197
38198
38199
38200
38201
38202
38203
38204
38205
38206
38207
38208
38209
38210
38211
38212
38213
38214
38215
38216
38217
38218
38219
38220
38221
38222
38223
38224
38225
38226
38227
38228
38229
38230
38231
38232
38233
38234
38235
38236
38237
38238
38239
38240
38241
38242
38243
38244
38245
38246
38247
38248
38249
38250
38251
38252
38253
38254
38255
38256
38257
38258
38259
38260
38261
38262
38263
38264
38265
38266
38267
38268
38269
38270
38271
38272
38273
38274
38275
38276
38277
38278
38279
38280
38281
38282
38283
38284
38285
38286
38287
38288
38289
38290
38291
38292
38293
38294
38295
38296
38297
38298
38299
38300
38301
38302
38303
38304
38305
38306
38307
38308
38309
38310
38311
38312
38313
38314
38315
38316
38317
38318
38319
38320
38321
38322
38323
38324
38325
38326
38327
38328
38329
38330
38331
38332
38333
38334
38335
38336
38337
38338
38339
38340
38341
38342
38343
38344
38345
38346
38347
38348
38349
38350
38351
38352
38353
38354
38355
38356
38357
38358
38359
38360
38361
38362
38363
38364
38365
38366
38367
38368
38369
38370
38371
38372
38373
38374
38375
38376
38377
38378
38379
38380
38381
38382
38383
38384
38385
38386
38387
38388
38389
38390
38391
38392
38393
38394
38395
38396
38397
38398
38399
38400
38401
38402
38403
38404
38405
38406
38407
38408
38409
38410
38411
38412
38413
38414
38415
38416
38417
38418
38419
38420
38421
38422
38423
38424
38425
38426
38427
38428
38429
38430
38431
38432
38433
38434
38435
38436
38437
38438
38439
38440
38441
38442
38443
38444
38445
38446
38447
38448
38449
38450
38451
38452
38453
38454
38455
38456
38457
38458
38459
38460
38461
38462
38463
38464
38465
38466
38467
38468
38469
38470
38471
38472
38473
38474
38475
38476
38477
38478
38479
38480
38481
38482
38483
38484
38485
38486
38487
38488
38489
38490
38491
38492
38493
38494
38495
38496
38497
38498
38499
38500
38501
38502
38503
38504
38505
38506
38507
38508
38509
38510
38511
38512
38513
38514
38515
38516
38517
38518
38519
38520
38521
38522
38523
38524
38525
38526
38527
38528
38529
38530
38531
38532
38533
38534
38535
38536
38537
38538
38539
38540
38541
38542
38543
38544
38545
38546
38547
38548
38549
38550
38551
38552
38553
38554
38555
38556
38557
38558
38559
38560
38561
38562
38563
38564
38565
38566
38567
38568
38569
38570
38571
38572
38573
38574
38575
38576
38577
38578
38579
38580
38581
38582
38583
38584
38585
38586
38587
38588
38589
38590
38591
38592
38593
38594
38595
38596
38597
38598
38599
38600
38601
38602
38603
38604
38605
38606
38607
38608
38609
38610
38611
38612
38613
38614
38615
38616
38617
38618
38619
38620
38621
38622
38623
38624
38625
38626
38627
38628
38629
38630
38631
38632
38633
38634
38635
38636
38637
38638
38639
38640
38641
38642
38643
38644
38645
38646
38647
38648
38649
38650
38651
38652
38653
38654
38655
38656
38657
38658
38659
38660
38661
38662
38663
38664
38665
38666
38667
38668
38669
38670
38671
38672
38673
38674
38675
38676
38677
38678
38679
38680
38681
38682
38683
38684
38685
38686
38687
38688
38689
38690
38691
38692
38693
38694
38695
38696
38697
38698
38699
38700
38701
38702
38703
38704
38705
38706
38707
38708
38709
38710
38711
38712
38713
38714
38715
38716
38717
38718
38719
38720
38721
38722
38723
38724
38725
38726
38727
38728
38729
38730
38731
38732
38733
38734
38735
38736
38737
38738
38739
38740
38741
38742
38743
38744
38745
38746
38747
38748
38749
38750
38751
38752
38753
38754
38755
38756
38757
38758
38759
38760
38761
38762
38763
38764
38765
38766
38767
38768
38769
38770
38771
38772
38773
38774
38775
38776
38777
38778
38779
38780
38781
38782
38783
38784
38785
38786
38787
38788
38789
38790
38791
38792
38793
38794
38795
38796
38797
38798
38799
38800
38801
38802
38803
38804
38805
38806
38807
38808
38809
38810
38811
38812
38813
38814
38815
38816
38817
38818
38819
38820
38821
38822
38823
38824
38825
38826
38827
38828
38829
38830
38831
38832
38833
38834
38835
38836
38837
38838
38839
38840
38841
38842
38843
38844
38845
38846
38847
38848
38849
38850
38851
38852
38853
38854
38855
38856
38857
38858
38859
38860
38861
38862
38863
38864
38865
38866
38867
38868
38869
38870
38871
38872
38873
38874
38875
38876
38877
38878
38879
38880
38881
38882
38883
38884
38885
38886
38887
38888
38889
38890
38891
38892
38893
38894
38895
38896
38897
38898
38899
38900
38901
38902
38903
38904
38905
38906
38907
38908
38909
38910
38911
38912
38913
38914
38915
38916
38917
38918
38919
38920
38921
38922
38923
38924
38925
38926
38927
38928
38929
38930
38931
38932
38933
38934
38935
38936
38937
38938
38939
38940
38941
38942
38943
38944
38945
38946
38947
38948
38949
38950
38951
38952
38953
38954
38955
38956
38957
38958
38959
38960
38961
38962
38963
38964
38965
38966
38967
38968
38969
38970
38971
38972
38973
38974
38975
38976
38977
38978
38979
38980
38981
38982
38983
38984
38985
38986
38987
38988
38989
38990
38991
38992
38993
38994
38995
38996
38997
38998
38999
39000
39001
39002
39003
39004
39005
39006
39007
39008
39009
39010
39011
39012
39013
39014
39015
39016
39017
39018
39019
39020
39021
39022
39023
39024
39025
39026
39027
39028
39029
39030
39031
39032
39033
39034
39035
39036
39037
39038
39039
39040
39041
39042
39043
39044
39045
39046
39047
39048
39049
39050
39051
39052
39053
39054
39055
39056
39057
39058
39059
39060
39061
39062
39063
39064
39065
39066
39067
39068
39069
39070
39071
39072
39073
39074
39075
39076
39077
39078
39079
39080
39081
39082
39083
39084
39085
39086
39087
39088
39089
39090
39091
39092
39093
39094
39095
39096
39097
39098
39099
39100
39101
39102
39103
39104
39105
39106
39107
39108
39109
39110
39111
39112
39113
39114
39115
39116
39117
39118
39119
39120
39121
39122
39123
39124
39125
39126
39127
39128
39129
39130
39131
39132
39133
39134
39135
39136
39137
39138
39139
39140
39141
39142
39143
39144
39145
39146
39147
39148
39149
39150
39151
39152
39153
39154
39155
39156
39157
39158
39159
39160
39161
39162
39163
39164
39165
39166
39167
39168
39169
39170
39171
39172
39173
39174
39175
39176
39177
39178
39179
39180
39181
39182
39183
39184
39185
39186
39187
39188
39189
39190
39191
39192
39193
39194
39195
39196
39197
39198
39199
39200
39201
39202
39203
39204
39205
39206
39207
39208
39209
39210
39211
39212
39213
39214
39215
39216
39217
39218
39219
39220
39221
39222
39223
39224
39225
39226
39227
39228
39229
39230
39231
39232
39233
39234
39235
39236
39237
39238
39239
39240
39241
39242
39243
39244
39245
39246
39247
39248
39249
39250
39251
39252
39253
39254
39255
39256
39257
39258
39259
39260
39261
39262
39263
39264
39265
39266
39267
39268
39269
39270
39271
39272
39273
39274
39275
39276
39277
39278
39279
39280
39281
39282
39283
39284
39285
39286
39287
39288
39289
39290
39291
39292
39293
39294
39295
39296
39297
39298
39299
39300
39301
39302
39303
39304
39305
39306
39307
39308
39309
39310
39311
39312
39313
39314
39315
39316
39317
39318
39319
39320
39321
39322
39323
39324
39325
39326
39327
39328
39329
39330
39331
39332
39333
39334
39335
39336
39337
39338
39339
39340
39341
39342
39343
39344
39345
39346
39347
39348
39349
39350
39351
39352
39353
39354
39355
39356
39357
39358
39359
39360
39361
39362
39363
39364
39365
39366
39367
39368
39369
39370
39371
39372
39373
39374
39375
39376
39377
39378
39379
39380
39381
39382
39383
39384
39385
39386
39387
39388
39389
39390
39391
39392
39393
39394
39395
39396
39397
39398
39399
39400
39401
39402
39403
39404
39405
39406
39407
39408
39409
39410
39411
39412
39413
39414
39415
39416
39417
39418
39419
39420
39421
39422
39423
39424
39425
39426
39427
39428
39429
39430
39431
39432
39433
39434
39435
39436
39437
39438
39439
39440
39441
39442
39443
39444
39445
39446
39447
39448
39449
39450
39451
39452
39453
39454
39455
39456
39457
39458
39459
39460
39461
39462
39463
39464
39465
39466
39467
39468
39469
39470
39471
39472
39473
39474
39475
39476
39477
39478
39479
39480
39481
39482
39483
39484
39485
39486
39487
39488
39489
39490
39491
39492
39493
39494
39495
39496
39497
39498
39499
39500
39501
39502
39503
39504
39505
39506
39507
39508
39509
39510
39511
39512
39513
39514
39515
39516
39517
39518
39519
39520
39521
39522
39523
39524
39525
39526
39527
39528
39529
39530
39531
39532
39533
39534
39535
39536
39537
39538
39539
39540
39541
39542
39543
39544
39545
39546
39547
39548
39549
39550
39551
39552
39553
39554
39555
39556
39557
39558
39559
39560
39561
39562
39563
39564
39565
39566
39567
39568
39569
39570
39571
39572
39573
39574
39575
39576
39577
39578
39579
39580
39581
39582
39583
39584
39585
39586
39587
39588
39589
39590
39591
39592
39593
39594
39595
39596
39597
39598
39599
39600
39601
39602
39603
39604
39605
39606
39607
39608
39609
39610
39611
39612
39613
39614
39615
39616
39617
39618
39619
39620
39621
39622
39623
39624
39625
39626
39627
39628
39629
39630
39631
39632
39633
39634
39635
39636
39637
39638
39639
39640
39641
39642
39643
39644
39645
39646
39647
39648
39649
39650
39651
39652
39653
39654
39655
39656
39657
39658
39659
39660
39661
39662
39663
39664
39665
39666
39667
39668
39669
39670
39671
39672
39673
39674
39675
39676
39677
39678
39679
39680
39681
39682
39683
39684
39685
39686
39687
39688
39689
39690
39691
39692
39693
39694
39695
39696
39697
39698
39699
39700
39701
39702
39703
39704
39705
39706
39707
39708
39709
39710
39711
39712
39713
39714
39715
39716
39717
39718
39719
39720
39721
39722
39723
39724
39725
39726
39727
39728
39729
39730
39731
39732
39733
39734
39735
39736
39737
39738
39739
39740
39741
39742
39743
39744
39745
39746
39747
39748
39749
39750
39751
39752
39753
39754
39755
39756
39757
39758
39759
39760
39761
39762
39763
39764
39765
39766
39767
39768
39769
39770
39771
39772
39773
39774
39775
39776
39777
39778
39779
39780
39781
39782
39783
39784
39785
39786
39787
39788
39789
39790
39791
39792
39793
39794
39795
39796
39797
39798
39799
39800
39801
39802
39803
39804
39805
39806
39807
39808
39809
39810
39811
39812
39813
39814
39815
39816
39817
39818
39819
39820
39821
39822
39823
39824
39825
39826
39827
39828
39829
39830
39831
39832
39833
39834
39835
39836
39837
39838
39839
39840
39841
39842
39843
39844
39845
39846
39847
39848
39849
39850
39851
39852
39853
39854
39855
39856
39857
39858
39859
39860
39861
39862
39863
39864
39865
39866
39867
39868
39869
39870
39871
39872
39873
39874
39875
39876
39877
39878
39879
39880
39881
39882
39883
39884
39885
39886
39887
39888
39889
39890
39891
39892
39893
39894
39895
39896
39897
39898
39899
39900
39901
39902
39903
39904
39905
39906
39907
39908
39909
39910
39911
39912
39913
39914
39915
39916
39917
39918
39919
39920
39921
39922
39923
39924
39925
39926
39927
39928
39929
39930
39931
39932
39933
39934
39935
39936
39937
39938
39939
39940
39941
39942
39943
39944
39945
39946
39947
39948
39949
39950
39951
39952
39953
39954
39955
39956
39957
39958
39959
39960
39961
39962
39963
39964
39965
39966
39967
39968
39969
39970
39971
39972
39973
39974
39975
39976
39977
39978
39979
39980
39981
39982
39983
39984
39985
39986
39987
39988
39989
39990
39991
39992
39993
39994
39995
39996
39997
39998
39999
40000
40001
40002
40003
40004
40005
40006
40007
40008
40009
40010
40011
40012
40013
40014
40015
40016
40017
40018
40019
40020
40021
40022
40023
40024
40025
40026
40027
40028
40029
40030
40031
40032
40033
40034
40035
40036
40037
40038
40039
40040
40041
40042
40043
40044
40045
40046
40047
40048
40049
40050
40051
40052
40053
40054
40055
40056
40057
40058
40059
40060
40061
40062
40063
40064
40065
40066
40067
40068
40069
40070
40071
40072
40073
40074
40075
40076
40077
40078
40079
40080
40081
40082
40083
40084
40085
40086
40087
40088
40089
40090
40091
40092
40093
40094
40095
40096
40097
40098
40099
40100
40101
40102
40103
40104
40105
40106
40107
40108
40109
40110
40111
40112
40113
40114
40115
40116
40117
40118
40119
40120
40121
40122
40123
40124
40125
40126
40127
40128
40129
40130
40131
40132
40133
40134
40135
40136
40137
40138
40139
40140
40141
40142
40143
40144
40145
40146
40147
40148
40149
40150
40151
40152
40153
40154
40155
40156
40157
40158
40159
40160
40161
40162
40163
40164
40165
40166
40167
40168
40169
40170
40171
40172
40173
40174
40175
40176
40177
40178
40179
40180
40181
40182
40183
40184
40185
40186
40187
40188
40189
40190
40191
40192
40193
40194
40195
40196
40197
40198
40199
40200
40201
40202
40203
40204
40205
40206
40207
40208
40209
40210
40211
40212
40213
40214
40215
40216
40217
40218
40219
40220
40221
40222
40223
40224
40225
40226
40227
40228
40229
40230
40231
40232
40233
40234
40235
40236
40237
40238
40239
40240
40241
40242
40243
40244
40245
40246
40247
40248
40249
40250
40251
40252
40253
40254
40255
40256
40257
40258
40259
40260
40261
40262
40263
40264
40265
40266
40267
40268
40269
40270
40271
40272
40273
40274
40275
40276
40277
40278
40279
40280
40281
40282
40283
40284
40285
40286
40287
40288
40289
40290
40291
40292
40293
40294
40295
40296
40297
40298
40299
40300
40301
40302
40303
40304
40305
40306
40307
40308
40309
40310
40311
40312
40313
40314
40315
40316
40317
40318
40319
40320
40321
40322
40323
40324
40325
40326
40327
40328
40329
40330
40331
40332
40333
40334
40335
40336
40337
40338
40339
40340
40341
40342
40343
40344
40345
40346
40347
40348
40349
40350
40351
40352
40353
40354
40355
40356
40357
40358
40359
40360
40361
40362
40363
40364
40365
40366
40367
40368
40369
40370
40371
40372
40373
40374
40375
40376
40377
40378
40379
40380
40381
40382
40383
40384
40385
40386
40387
40388
40389
40390
40391
40392
40393
40394
40395
40396
40397
40398
40399
40400
40401
40402
40403
40404
40405
40406
40407
40408
40409
40410
40411
40412
40413
40414
40415
40416
40417
40418
40419
40420
40421
40422
40423
40424
40425
40426
40427
40428
40429
40430
40431
40432
40433
40434
40435
40436
40437
40438
40439
40440
40441
40442
40443
40444
40445
40446
40447
40448
40449
40450
40451
40452
40453
40454
40455
40456
40457
40458
40459
40460
40461
40462
40463
40464
40465
40466
40467
40468
40469
40470
40471
40472
40473
40474
40475
40476
40477
40478
40479
40480
40481
40482
40483
40484
40485
40486
40487
40488
40489
40490
40491
40492
40493
40494
40495
40496
40497
40498
40499
40500
40501
40502
40503
40504
40505
40506
40507
40508
40509
40510
40511
40512
40513
40514
40515
40516
40517
40518
40519
40520
40521
40522
40523
40524
40525
40526
40527
40528
40529
40530
40531
40532
40533
40534
40535
40536
40537
40538
40539
40540
40541
40542
40543
40544
40545
40546
40547
40548
40549
40550
40551
40552
40553
40554
40555
40556
40557
40558
40559
40560
40561
40562
40563
40564
40565
40566
40567
40568
40569
40570
40571
40572
40573
40574
40575
40576
40577
40578
40579
40580
40581
40582
40583
40584
40585
40586
40587
40588
40589
40590
40591
40592
40593
40594
40595
40596
40597
40598
40599
40600
40601
40602
40603
40604
40605
40606
40607
40608
40609
40610
40611
40612
40613
40614
40615
40616
40617
40618
40619
40620
40621
40622
40623
40624
40625
40626
40627
40628
40629
40630
40631
40632
40633
40634
40635
40636
40637
40638
40639
40640
40641
40642
40643
40644
40645
40646
40647
40648
40649
40650
40651
40652
40653
40654
40655
40656
40657
40658
40659
40660
40661
40662
40663
40664
40665
40666
40667
40668
40669
40670
40671
40672
40673
40674
40675
40676
40677
40678
40679
40680
40681
40682
40683
40684
40685
40686
40687
40688
40689
40690
40691
40692
40693
40694
40695
40696
40697
40698
40699
40700
40701
40702
40703
40704
40705
40706
40707
40708
40709
40710
40711
40712
40713
40714
40715
40716
40717
40718
40719
40720
40721
40722
40723
40724
40725
40726
40727
40728
40729
40730
40731
40732
40733
40734
40735
40736
40737
40738
40739
40740
40741
40742
40743
40744
40745
40746
40747
40748
40749
40750
40751
40752
40753
40754
40755
40756
40757
40758
40759
40760
40761
40762
40763
40764
40765
40766
40767
40768
40769
40770
40771
40772
40773
40774
40775
40776
40777
40778
40779
40780
40781
40782
40783
40784
40785
40786
40787
40788
40789
40790
40791
40792
40793
40794
40795
40796
40797
40798
40799
40800
40801
40802
40803
40804
40805
40806
40807
40808
40809
40810
40811
40812
40813
40814
40815
40816
40817
40818
40819
40820
40821
40822
40823
40824
40825
40826
40827
40828
40829
40830
40831
40832
40833
40834
40835
40836
40837
40838
40839
40840
40841
40842
40843
40844
40845
40846
40847
40848
40849
40850
40851
40852
40853
40854
40855
40856
40857
40858
40859
40860
40861
40862
40863
40864
40865
40866
40867
40868
40869
40870
40871
40872
40873
40874
40875
40876
40877
40878
40879
40880
40881
40882
40883
40884
40885
40886
40887
40888
40889
40890
40891
40892
40893
40894
40895
40896
40897
40898
40899
40900
40901
40902
40903
40904
40905
40906
40907
40908
40909
40910
40911
40912
40913
40914
40915
40916
40917
40918
40919
40920
40921
40922
40923
40924
40925
40926
40927
40928
40929
40930
40931
40932
40933
40934
40935
40936
40937
40938
40939
40940
40941
40942
40943
40944
40945
40946
40947
40948
40949
40950
40951
40952
40953
40954
40955
40956
40957
40958
40959
40960
40961
40962
40963
40964
40965
40966
40967
40968
40969
40970
40971
40972
40973
40974
40975
40976
40977
40978
40979
40980
40981
40982
40983
40984
40985
40986
40987
40988
40989
40990
40991
40992
40993
40994
40995
40996
40997
40998
40999
41000
41001
41002
41003
41004
41005
41006
41007
41008
41009
41010
41011
41012
41013
41014
41015
41016
41017
41018
41019
41020
41021
41022
41023
41024
41025
41026
41027
41028
41029
41030
41031
41032
41033
41034
41035
41036
41037
41038
41039
41040
41041
41042
41043
41044
41045
41046
41047
41048
41049
41050
41051
41052
41053
41054
41055
41056
41057
41058
41059
41060
41061
41062
41063
41064
41065
41066
41067
41068
41069
41070
41071
41072
41073
41074
41075
41076
41077
41078
41079
41080
41081
41082
41083
41084
41085
41086
41087
41088
41089
41090
41091
41092
41093
41094
41095
41096
41097
41098
41099
41100
41101
41102
41103
41104
41105
41106
41107
41108
41109
41110
41111
41112
41113
41114
41115
41116
41117
41118
41119
41120
41121
41122
41123
41124
41125
41126
41127
41128
41129
41130
41131
41132
41133
41134
41135
41136
41137
41138
41139
41140
41141
41142
41143
41144
41145
41146
41147
41148
41149
41150
41151
41152
41153
41154
41155
41156
41157
41158
41159
41160
41161
41162
41163
41164
41165
41166
41167
41168
41169
41170
41171
41172
41173
41174
41175
41176
41177
41178
41179
41180
41181
41182
41183
41184
41185
41186
41187
41188
41189
41190
41191
41192
41193
41194
41195
41196
41197
41198
41199
41200
41201
41202
41203
41204
41205
41206
41207
41208
41209
41210
41211
41212
41213
41214
41215
41216
41217
41218
41219
41220
41221
41222
41223
41224
41225
41226
41227
41228
41229
41230
41231
41232
41233
41234
41235
41236
41237
41238
41239
41240
41241
41242
41243
41244
41245
41246
41247
41248
41249
41250
41251
41252
41253
41254
41255
41256
41257
41258
41259
41260
41261
41262
41263
41264
41265
41266
41267
41268
41269
41270
41271
41272
41273
41274
41275
41276
41277
41278
41279
41280
41281
41282
41283
41284
41285
41286
41287
41288
41289
41290
41291
41292
41293
41294
41295
41296
41297
41298
41299
41300
41301
41302
41303
41304
41305
41306
41307
41308
41309
41310
41311
41312
41313
41314
41315
41316
41317
41318
41319
41320
41321
41322
41323
41324
41325
41326
41327
41328
41329
41330
41331
41332
41333
41334
41335
41336
41337
41338
41339
41340
41341
41342
41343
41344
41345
41346
41347
41348
41349
41350
41351
41352
41353
41354
41355
41356
41357
41358
41359
41360
41361
41362
41363
41364
41365
41366
41367
41368
41369
41370
41371
41372
41373
41374
41375
41376
41377
41378
41379
41380
41381
41382
41383
41384
41385
41386
41387
41388
41389
41390
41391
41392
41393
41394
41395
41396
41397
41398
41399
41400
41401
41402
41403
41404
41405
41406
41407
41408
41409
41410
41411
41412
41413
41414
41415
41416
41417
41418
41419
41420
41421
41422
41423
41424
41425
41426
41427
41428
41429
41430
41431
41432
41433
41434
41435
41436
41437
41438
41439
41440
41441
41442
41443
41444
41445
41446
41447
41448
41449
41450
41451
41452
41453
41454
41455
41456
41457
41458
41459
41460
41461
41462
41463
41464
41465
41466
41467
41468
41469
41470
41471
41472
41473
41474
41475
41476
41477
41478
41479
41480
41481
41482
41483
41484
41485
41486
41487
41488
41489
41490
41491
41492
41493
41494
41495
41496
41497
41498
41499
41500
41501
41502
41503
41504
41505
41506
41507
41508
41509
41510
41511
41512
41513
41514
41515
41516
41517
41518
41519
41520
41521
41522
41523
41524
41525
41526
41527
41528
41529
41530
41531
41532
41533
41534
41535
41536
41537
41538
41539
41540
41541
41542
41543
41544
41545
41546
41547
41548
41549
41550
41551
41552
41553
41554
41555
41556
41557
41558
41559
41560
41561
41562
41563
41564
41565
41566
41567
41568
41569
41570
41571
41572
41573
41574
41575
41576
41577
41578
41579
41580
41581
41582
41583
41584
41585
41586
41587
41588
41589
41590
41591
41592
41593
41594
41595
41596
41597
41598
41599
41600
41601
41602
41603
41604
41605
41606
41607
41608
41609
41610
41611
41612
41613
41614
41615
41616
41617
41618
41619
41620
41621
41622
41623
41624
41625
41626
41627
41628
41629
41630
41631
41632
41633
41634
41635
41636
41637
41638
41639
41640
41641
41642
41643
41644
41645
41646
41647
41648
41649
41650
41651
41652
41653
41654
41655
41656
41657
41658
41659
41660
41661
41662
41663
41664
41665
41666
41667
41668
41669
41670
41671
41672
41673
41674
41675
41676
41677
41678
41679
41680
41681
41682
41683
41684
41685
41686
41687
41688
41689
41690
41691
41692
41693
41694
41695
41696
41697
41698
41699
41700
41701
41702
41703
41704
41705
41706
41707
41708
41709
41710
41711
41712
41713
41714
41715
41716
41717
41718
41719
41720
41721
41722
41723
41724
41725
41726
41727
41728
41729
41730
41731
41732
41733
41734
41735
41736
41737
41738
41739
41740
41741
41742
41743
41744
41745
41746
41747
41748
41749
41750
41751
41752
41753
41754
41755
41756
41757
41758
41759
41760
41761
41762
41763
41764
41765
41766
41767
41768
41769
41770
41771
41772
41773
41774
41775
41776
41777
41778
41779
41780
41781
41782
41783
41784
41785
41786
41787
41788
41789
41790
41791
41792
41793
41794
41795
41796
41797
41798
41799
41800
41801
41802
41803
41804
41805
41806
41807
41808
41809
41810
41811
41812
41813
41814
41815
41816
41817
41818
41819
41820
41821
41822
41823
41824
41825
41826
41827
41828
41829
41830
41831
41832
41833
41834
41835
41836
41837
41838
41839
41840
41841
41842
41843
41844
41845
41846
41847
41848
41849
41850
41851
41852
41853
41854
41855
41856
41857
41858
41859
41860
41861
41862
41863
41864
41865
41866
41867
41868
41869
41870
41871
41872
41873
41874
41875
41876
41877
41878
41879
41880
41881
41882
41883
41884
41885
41886
41887
41888
41889
41890
41891
41892
41893
41894
41895
41896
41897
41898
41899
41900
41901
41902
41903
41904
41905
41906
41907
41908
41909
41910
41911
41912
41913
41914
41915
41916
41917
41918
41919
41920
41921
41922
41923
41924
41925
41926
41927
41928
41929
41930
41931
41932
41933
41934
41935
41936
41937
41938
41939
41940
41941
41942
41943
41944
41945
41946
41947
41948
41949
41950
41951
41952
41953
41954
41955
41956
41957
41958
41959
41960
41961
41962
41963
41964
41965
41966
41967
41968
41969
41970
41971
41972
41973
41974
41975
41976
41977
41978
41979
41980
41981
41982
41983
41984
41985
41986
41987
41988
41989
41990
41991
41992
41993
41994
41995
41996
41997
41998
41999
42000
42001
42002
42003
42004
42005
42006
42007
42008
42009
42010
42011
42012
42013
42014
42015
42016
42017
42018
42019
42020
42021
42022
42023
42024
42025
42026
42027
42028
42029
42030
42031
42032
42033
42034
42035
42036
42037
42038
42039
42040
42041
42042
42043
42044
42045
42046
42047
42048
42049
42050
42051
42052
42053
42054
42055
42056
42057
42058
42059
42060
42061
42062
42063
42064
42065
42066
42067
42068
42069
42070
42071
42072
42073
42074
42075
42076
42077
42078
42079
42080
42081
42082
42083
42084
42085
42086
42087
42088
42089
42090
42091
42092
42093
42094
42095
42096
42097
42098
42099
42100
42101
42102
42103
42104
42105
42106
42107
42108
42109
42110
42111
42112
42113
42114
42115
42116
42117
42118
42119
42120
42121
42122
42123
42124
42125
42126
42127
42128
42129
42130
42131
42132
42133
42134
42135
42136
42137
42138
42139
42140
42141
42142
42143
42144
42145
42146
42147
42148
42149
42150
42151
42152
42153
42154
42155
42156
42157
42158
42159
42160
42161
42162
42163
42164
42165
42166
42167
42168
42169
42170
42171
42172
42173
42174
42175
42176
42177
42178
42179
42180
42181
42182
42183
42184
42185
42186
42187
42188
42189
42190
42191
42192
42193
42194
42195
42196
42197
42198
42199
42200
42201
42202
42203
42204
42205
42206
42207
42208
42209
42210
42211
42212
42213
42214
42215
42216
42217
42218
42219
42220
42221
42222
42223
42224
42225
42226
42227
42228
42229
42230
42231
42232
42233
42234
42235
42236
42237
42238
42239
42240
42241
42242
42243
42244
42245
42246
42247
42248
42249
42250
42251
42252
42253
42254
42255
42256
42257
42258
42259
42260
42261
42262
42263
42264
42265
42266
42267
42268
42269
42270
42271
42272
42273
42274
42275
42276
42277
42278
42279
42280
42281
42282
42283
42284
42285
42286
42287
42288
42289
42290
42291
42292
42293
42294
42295
42296
42297
42298
42299
42300
42301
42302
42303
42304
42305
42306
42307
42308
42309
42310
42311
42312
42313
42314
42315
42316
42317
42318
42319
42320
42321
42322
42323
42324
42325
42326
42327
42328
42329
42330
42331
42332
42333
42334
42335
42336
42337
42338
42339
42340
42341
42342
42343
42344
42345
42346
42347
42348
42349
42350
42351
42352
42353
42354
42355
42356
42357
42358
42359
42360
42361
42362
42363
42364
42365
42366
42367
42368
42369
42370
42371
42372
42373
42374
42375
42376
42377
42378
42379
42380
42381
42382
42383
42384
42385
42386
42387
42388
42389
42390
42391
42392
42393
42394
42395
42396
42397
42398
42399
42400
42401
42402
42403
42404
42405
42406
42407
42408
42409
42410
42411
42412
42413
42414
42415
42416
42417
42418
42419
42420
42421
42422
42423
42424
42425
42426
42427
42428
42429
42430
42431
42432
42433
42434
42435
42436
42437
42438
42439
42440
42441
42442
42443
42444
42445
42446
42447
42448
42449
42450
42451
42452
42453
42454
42455
42456
42457
42458
42459
42460
42461
42462
42463
42464
42465
42466
42467
42468
42469
42470
42471
42472
42473
42474
42475
42476
42477
42478
42479
42480
42481
42482
42483
42484
42485
42486
42487
42488
42489
42490
42491
42492
42493
42494
42495
42496
42497
42498
42499
42500
42501
42502
42503
42504
42505
42506
42507
42508
42509
42510
42511
42512
42513
42514
42515
42516
42517
42518
42519
42520
42521
42522
42523
42524
42525
42526
42527
42528
42529
42530
42531
42532
42533
42534
42535
42536
42537
42538
42539
42540
42541
42542
42543
42544
42545
42546
42547
42548
42549
42550
42551
42552
42553
42554
42555
42556
42557
42558
42559
42560
42561
42562
42563
42564
42565
42566
42567
42568
42569
42570
42571
42572
42573
42574
42575
42576
42577
42578
42579
42580
42581
42582
42583
42584
42585
42586
42587
42588
42589
42590
42591
42592
42593
42594
42595
42596
42597
42598
42599
42600
42601
42602
42603
42604
42605
42606
42607
42608
42609
42610
42611
42612
42613
42614
42615
42616
42617
42618
42619
42620
42621
42622
42623
42624
42625
42626
42627
42628
42629
42630
42631
42632
42633
42634
42635
42636
42637
42638
42639
42640
42641
42642
42643
42644
42645
42646
42647
42648
42649
42650
42651
42652
42653
42654
42655
42656
42657
42658
42659
42660
42661
42662
42663
42664
42665
42666
42667
42668
42669
42670
42671
42672
42673
42674
42675
42676
42677
42678
42679
42680
42681
42682
42683
42684
42685
42686
42687
42688
42689
42690
42691
42692
42693
42694
42695
42696
42697
42698
42699
42700
42701
42702
42703
42704
42705
42706
42707
42708
42709
42710
42711
42712
42713
42714
42715
42716
42717
42718
42719
42720
42721
42722
42723
42724
42725
42726
42727
42728
42729
42730
42731
42732
42733
42734
42735
42736
42737
42738
42739
42740
42741
42742
42743
42744
42745
42746
42747
42748
42749
42750
42751
42752
42753
42754
42755
42756
42757
42758
42759
42760
42761
42762
42763
42764
42765
42766
42767
42768
42769
42770
42771
42772
42773
42774
42775
42776
42777
42778
42779
42780
42781
42782
42783
42784
42785
42786
42787
42788
42789
42790
42791
42792
42793
42794
42795
42796
42797
42798
42799
42800
42801
42802
42803
42804
42805
42806
42807
42808
42809
42810
42811
42812
42813
42814
42815
42816
42817
42818
42819
42820
42821
42822
42823
42824
42825
42826
42827
42828
42829
42830
42831
42832
42833
42834
42835
42836
42837
42838
42839
42840
42841
42842
42843
42844
42845
42846
42847
42848
42849
42850
42851
42852
42853
42854
42855
42856
42857
42858
42859
42860
42861
42862
42863
42864
42865
42866
42867
42868
42869
42870
42871
42872
42873
42874
42875
42876
42877
42878
42879
42880
42881
42882
42883
42884
42885
42886
42887
42888
42889
42890
42891
42892
42893
42894
42895
42896
42897
42898
42899
42900
42901
42902
42903
42904
42905
42906
42907
42908
42909
42910
42911
42912
42913
42914
42915
42916
42917
42918
42919
42920
42921
42922
42923
42924
42925
42926
42927
42928
42929
42930
42931
42932
42933
42934
42935
42936
42937
42938
42939
42940
42941
42942
42943
42944
42945
42946
42947
42948
42949
42950
42951
42952
42953
42954
42955
42956
42957
42958
42959
42960
42961
42962
42963
42964
42965
42966
42967
42968
42969
42970
42971
42972
42973
42974
42975
42976
42977
42978
42979
42980
42981
42982
42983
42984
42985
42986
42987
42988
42989
42990
42991
42992
42993
42994
42995
42996
42997
42998
42999
43000
43001
43002
43003
43004
43005
43006
43007
43008
43009
43010
43011
43012
43013
43014
43015
43016
43017
43018
43019
43020
43021
43022
43023
43024
43025
43026
43027
43028
43029
43030
43031
43032
43033
43034
43035
43036
43037
43038
43039
43040
43041
43042
43043
43044
43045
43046
43047
43048
43049
43050
43051
43052
43053
43054
43055
43056
43057
43058
43059
43060
43061
43062
43063
43064
43065
43066
43067
43068
43069
43070
43071
43072
43073
43074
43075
43076
43077
43078
43079
43080
43081
43082
43083
43084
43085
43086
43087
43088
43089
43090
43091
43092
43093
43094
43095
43096
43097
43098
43099
43100
43101
43102
43103
43104
43105
43106
43107
43108
43109
43110
43111
43112
43113
43114
43115
43116
43117
43118
43119
43120
43121
43122
43123
43124
43125
43126
43127
43128
43129
43130
43131
43132
43133
43134
43135
43136
43137
43138
43139
43140
43141
43142
43143
43144
43145
43146
43147
43148
43149
43150
43151
43152
43153
43154
43155
43156
43157
43158
43159
43160
43161
43162
43163
43164
43165
43166
43167
43168
43169
43170
43171
43172
43173
43174
43175
43176
43177
43178
43179
43180
43181
43182
43183
43184
43185
43186
43187
43188
43189
43190
43191
43192
43193
43194
43195
43196
43197
43198
43199
43200
43201
43202
43203
43204
43205
43206
43207
43208
43209
43210
43211
43212
43213
43214
43215
43216
43217
43218
43219
43220
43221
43222
43223
43224
43225
43226
43227
43228
43229
43230
43231
43232
43233
43234
43235
43236
43237
43238
43239
43240
43241
43242
43243
43244
43245
43246
43247
43248
43249
43250
43251
43252
43253
43254
43255
43256
43257
43258
43259
43260
43261
43262
43263
43264
43265
43266
43267
43268
43269
43270
43271
43272
43273
43274
43275
43276
43277
43278
43279
43280
43281
43282
43283
43284
43285
43286
43287
43288
43289
43290
43291
43292
43293
43294
43295
43296
43297
43298
43299
43300
43301
43302
43303
43304
43305
43306
43307
43308
43309
43310
43311
43312
43313
43314
43315
43316
43317
43318
43319
43320
43321
43322
43323
43324
43325
43326
43327
43328
43329
43330
43331
43332
43333
43334
43335
43336
43337
43338
43339
43340
43341
43342
43343
43344
43345
43346
43347
43348
43349
43350
43351
43352
43353
43354
43355
43356
43357
43358
43359
43360
43361
43362
43363
43364
43365
43366
43367
43368
43369
43370
43371
43372
43373
43374
43375
43376
43377
43378
43379
43380
43381
43382
43383
43384
43385
43386
43387
43388
43389
43390
43391
43392
43393
43394
43395
43396
43397
43398
43399
43400
43401
43402
43403
43404
43405
43406
43407
43408
43409
43410
43411
43412
43413
43414
43415
43416
43417
43418
43419
43420
43421
43422
43423
43424
43425
43426
43427
43428
43429
43430
43431
43432
43433
43434
43435
43436
43437
43438
43439
43440
43441
43442
43443
43444
43445
43446
43447
43448
43449
43450
43451
43452
43453
43454
43455
43456
43457
43458
43459
43460
43461
43462
43463
43464
43465
43466
43467
43468
43469
43470
43471
43472
43473
43474
43475
43476
43477
43478
43479
43480
43481
43482
43483
43484
43485
43486
43487
43488
43489
43490
43491
43492
43493
43494
43495
43496
43497
43498
43499
43500
43501
43502
43503
43504
43505
43506
43507
43508
43509
43510
43511
43512
43513
43514
43515
43516
43517
43518
43519
43520
43521
43522
43523
43524
43525
43526
43527
43528
43529
43530
43531
43532
43533
43534
43535
43536
43537
43538
43539
43540
43541
43542
43543
43544
43545
43546
43547
43548
43549
43550
43551
43552
43553
43554
43555
43556
43557
43558
43559
43560
43561
43562
43563
43564
43565
43566
43567
43568
43569
43570
43571
43572
43573
43574
43575
43576
43577
43578
43579
43580
43581
43582
43583
43584
43585
43586
43587
43588
43589
43590
43591
43592
43593
43594
43595
43596
43597
43598
43599
43600
43601
43602
43603
43604
43605
43606
43607
43608
43609
43610
43611
43612
43613
43614
43615
43616
43617
43618
43619
43620
43621
43622
43623
43624
43625
43626
43627
43628
43629
43630
43631
43632
43633
43634
43635
43636
43637
43638
43639
43640
43641
43642
43643
43644
43645
43646
43647
43648
43649
43650
43651
43652
43653
43654
43655
43656
43657
43658
43659
43660
43661
43662
43663
43664
43665
43666
43667
43668
43669
43670
43671
43672
43673
43674
43675
43676
43677
43678
43679
43680
43681
43682
43683
43684
43685
43686
43687
43688
43689
43690
43691
43692
43693
43694
43695
43696
43697
43698
43699
43700
43701
43702
43703
43704
43705
43706
43707
43708
43709
43710
43711
43712
43713
43714
43715
43716
43717
43718
43719
43720
43721
43722
43723
43724
43725
43726
43727
43728
43729
43730
43731
43732
43733
43734
43735
43736
43737
43738
43739
43740
43741
43742
43743
43744
43745
43746
43747
43748
43749
43750
43751
43752
43753
43754
43755
43756
43757
43758
43759
43760
43761
43762
43763
43764
43765
43766
43767
43768
43769
43770
43771
43772
43773
43774
43775
43776
43777
43778
43779
43780
43781
43782
43783
43784
43785
43786
43787
43788
43789
43790
43791
43792
43793
43794
43795
43796
43797
43798
43799
43800
43801
43802
43803
43804
43805
43806
43807
43808
43809
43810
43811
43812
43813
43814
43815
43816
43817
43818
43819
43820
43821
43822
43823
43824
43825
43826
43827
43828
43829
43830
43831
43832
43833
43834
43835
43836
43837
43838
43839
43840
43841
43842
43843
43844
43845
43846
43847
43848
43849
43850
43851
43852
43853
43854
43855
43856
43857
43858
43859
43860
43861
43862
43863
43864
43865
43866
43867
43868
43869
43870
43871
43872
43873
43874
43875
43876
43877
43878
43879
43880
43881
43882
43883
43884
43885
43886
43887
43888
43889
43890
43891
43892
43893
43894
43895
43896
43897
43898
43899
43900
43901
43902
43903
43904
43905
43906
43907
43908
43909
43910
43911
43912
43913
43914
43915
43916
43917
43918
43919
43920
43921
43922
43923
43924
43925
43926
43927
43928
43929
43930
43931
43932
43933
43934
43935
43936
43937
43938
43939
43940
43941
43942
43943
43944
43945
43946
43947
43948
43949
43950
43951
43952
43953
43954
43955
43956
43957
43958
43959
43960
43961
43962
43963
43964
43965
43966
43967
43968
43969
43970
43971
43972
43973
43974
43975
43976
43977
43978
43979
43980
43981
43982
43983
43984
43985
43986
43987
43988
43989
43990
43991
43992
43993
43994
43995
43996
43997
43998
43999
44000
44001
44002
44003
44004
44005
44006
44007
44008
44009
44010
44011
44012
44013
44014
44015
44016
44017
44018
44019
44020
44021
44022
44023
44024
44025
44026
44027
44028
44029
44030
44031
44032
44033
44034
44035
44036
44037
44038
44039
44040
44041
44042
44043
44044
44045
44046
44047
44048
44049
44050
44051
44052
44053
44054
44055
44056
44057
44058
44059
44060
44061
44062
44063
44064
44065
44066
44067
44068
44069
44070
44071
44072
44073
44074
44075
44076
44077
44078
44079
44080
44081
44082
44083
44084
44085
44086
44087
44088
44089
44090
44091
44092
44093
44094
44095
44096
44097
44098
44099
44100
44101
44102
44103
44104
44105
44106
44107
44108
44109
44110
44111
44112
44113
44114
44115
44116
44117
44118
44119
44120
44121
44122
44123
44124
44125
44126
44127
44128
44129
44130
44131
44132
44133
44134
44135
44136
44137
44138
44139
44140
44141
44142
44143
44144
44145
44146
44147
44148
44149
44150
44151
44152
44153
44154
44155
44156
44157
44158
44159
44160
44161
44162
44163
44164
44165
44166
44167
44168
44169
44170
44171
44172
44173
44174
44175
44176
44177
44178
44179
44180
44181
44182
44183
44184
44185
44186
44187
44188
44189
44190
44191
44192
44193
44194
44195
44196
44197
44198
44199
44200
44201
44202
44203
44204
44205
44206
44207
44208
44209
44210
44211
44212
44213
44214
44215
44216
44217
44218
44219
44220
44221
44222
44223
44224
44225
44226
44227
44228
44229
44230
44231
44232
44233
44234
44235
44236
44237
44238
44239
44240
44241
44242
44243
44244
44245
44246
44247
44248
44249
44250
44251
44252
44253
44254
44255
44256
44257
44258
44259
44260
44261
44262
44263
44264
44265
44266
44267
44268
44269
44270
44271
44272
44273
44274
44275
44276
44277
44278
44279
44280
44281
44282
44283
44284
44285
44286
44287
44288
44289
44290
44291
44292
44293
44294
44295
44296
44297
44298
44299
44300
44301
44302
44303
44304
44305
44306
44307
44308
44309
44310
44311
44312
44313
44314
44315
44316
44317
44318
44319
44320
44321
44322
44323
44324
44325
44326
44327
44328
44329
44330
44331
44332
44333
44334
44335
44336
44337
44338
44339
44340
44341
44342
44343
44344
44345
44346
44347
44348
44349
44350
44351
44352
44353
44354
44355
44356
44357
44358
44359
44360
44361
44362
44363
44364
44365
44366
44367
44368
44369
44370
44371
44372
44373
44374
44375
44376
44377
44378
44379
44380
44381
44382
44383
44384
44385
44386
44387
44388
44389
44390
44391
44392
44393
44394
44395
44396
44397
44398
44399
44400
44401
44402
44403
44404
44405
44406
44407
44408
44409
44410
44411
44412
44413
44414
44415
44416
44417
44418
44419
44420
44421
44422
44423
44424
44425
44426
44427
44428
44429
44430
44431
44432
44433
44434
44435
44436
44437
44438
44439
44440
44441
44442
44443
44444
44445
44446
44447
44448
44449
44450
44451
44452
44453
44454
44455
44456
44457
44458
44459
44460
44461
44462
44463
44464
44465
44466
44467
44468
44469
44470
44471
44472
44473
44474
44475
44476
44477
44478
44479
44480
44481
44482
44483
44484
44485
44486
44487
44488
44489
44490
44491
44492
44493
44494
44495
44496
44497
44498
44499
44500
44501
44502
44503
44504
44505
44506
44507
44508
44509
44510
44511
44512
44513
44514
44515
44516
44517
44518
44519
44520
44521
44522
44523
44524
44525
44526
44527
44528
44529
44530
44531
44532
44533
44534
44535
44536
44537
44538
44539
44540
44541
44542
44543
44544
44545
44546
44547
44548
44549
44550
44551
44552
44553
44554
44555
44556
44557
44558
44559
44560
44561
44562
44563
44564
44565
44566
44567
44568
44569
44570
44571
44572
44573
44574
44575
44576
44577
44578
44579
44580
44581
44582
44583
44584
44585
44586
44587
44588
44589
44590
44591
44592
44593
44594
44595
44596
44597
44598
44599
44600
44601
44602
44603
44604
44605
44606
44607
44608
44609
44610
44611
44612
44613
44614
44615
44616
44617
44618
44619
44620
44621
44622
44623
44624
44625
44626
44627
44628
44629
44630
44631
44632
44633
44634
44635
44636
44637
44638
44639
44640
44641
44642
44643
44644
44645
44646
44647
44648
44649
44650
44651
44652
44653
44654
44655
44656
44657
44658
44659
44660
44661
44662
44663
44664
44665
44666
44667
44668
44669
44670
44671
44672
44673
44674
44675
44676
44677
44678
44679
44680
44681
44682
44683
44684
44685
44686
44687
44688
44689
44690
44691
44692
44693
44694
44695
44696
44697
44698
44699
44700
44701
44702
44703
44704
44705
44706
44707
44708
44709
44710
44711
44712
44713
44714
44715
44716
44717
44718
44719
44720
44721
44722
44723
44724
44725
44726
44727
44728
44729
44730
44731
44732
44733
44734
44735
44736
44737
44738
44739
44740
44741
44742
44743
44744
44745
44746
44747
44748
44749
44750
44751
44752
44753
44754
44755
44756
44757
44758
44759
44760
44761
44762
44763
44764
44765
44766
44767
44768
44769
44770
44771
44772
44773
44774
44775
44776
44777
44778
44779
44780
44781
44782
44783
44784
44785
44786
44787
44788
44789
44790
44791
44792
44793
44794
44795
44796
44797
44798
44799
44800
44801
44802
44803
44804
44805
44806
44807
44808
44809
44810
44811
44812
44813
44814
44815
44816
44817
44818
44819
44820
44821
44822
44823
44824
44825
44826
44827
44828
44829
44830
44831
44832
44833
44834
44835
44836
44837
44838
44839
44840
44841
44842
44843
44844
44845
44846
44847
44848
44849
44850
44851
44852
44853
44854
44855
44856
44857
44858
44859
44860
44861
44862
44863
44864
44865
44866
44867
44868
44869
44870
44871
44872
44873
44874
44875
44876
44877
44878
44879
44880
44881
44882
44883
44884
44885
44886
44887
44888
44889
44890
44891
44892
44893
44894
44895
44896
44897
44898
44899
44900
44901
44902
44903
44904
44905
44906
44907
44908
44909
44910
44911
44912
44913
44914
44915
44916
44917
44918
44919
44920
44921
44922
44923
44924
44925
44926
44927
44928
44929
44930
44931
44932
44933
44934
44935
44936
44937
44938
44939
44940
44941
44942
44943
44944
44945
44946
44947
44948
44949
44950
44951
44952
44953
44954
44955
44956
44957
44958
44959
44960
44961
44962
44963
44964
44965
44966
44967
44968
44969
44970
44971
44972
44973
44974
44975
44976
44977
44978
44979
44980
44981
44982
44983
44984
44985
44986
44987
44988
44989
44990
44991
44992
44993
44994
44995
44996
44997
44998
44999
45000
45001
45002
45003
45004
45005
45006
45007
45008
45009
45010
45011
45012
45013
45014
45015
45016
45017
45018
45019
45020
45021
45022
45023
45024
45025
45026
45027
45028
45029
45030
45031
45032
45033
45034
45035
45036
45037
45038
45039
45040
45041
45042
45043
45044
45045
45046
45047
45048
45049
45050
45051
45052
45053
45054
45055
45056
45057
45058
45059
45060
45061
45062
45063
45064
45065
45066
45067
45068
45069
45070
45071
45072
45073
45074
45075
45076
45077
45078
45079
45080
45081
45082
45083
45084
45085
45086
45087
45088
45089
45090
45091
45092
45093
45094
45095
45096
45097
45098
45099
45100
45101
45102
45103
45104
45105
45106
45107
45108
45109
45110
45111
45112
45113
45114
45115
45116
45117
45118
45119
45120
45121
45122
45123
45124
45125
45126
45127
45128
45129
45130
45131
45132
45133
45134
45135
45136
45137
45138
45139
45140
45141
45142
45143
45144
45145
45146
45147
45148
45149
45150
45151
45152
45153
45154
45155
45156
45157
45158
45159
45160
45161
45162
45163
45164
45165
45166
45167
45168
45169
45170
45171
45172
45173
45174
45175
45176
45177
45178
45179
45180
45181
45182
45183
45184
45185
45186
45187
45188
45189
45190
45191
45192
45193
45194
45195
45196
45197
45198
45199
45200
45201
45202
45203
45204
45205
45206
45207
45208
45209
45210
45211
45212
45213
45214
45215
45216
45217
45218
45219
45220
45221
45222
45223
45224
45225
45226
45227
45228
45229
45230
45231
45232
45233
45234
45235
45236
45237
45238
45239
45240
45241
45242
45243
45244
45245
45246
45247
45248
45249
45250
45251
45252
45253
45254
45255
45256
45257
45258
45259
45260
45261
45262
45263
45264
45265
45266
45267
45268
45269
45270
45271
45272
45273
45274
45275
45276
45277
45278
45279
45280
45281
45282
45283
45284
45285
45286
45287
45288
45289
45290
45291
45292
45293
45294
45295
45296
45297
45298
45299
45300
45301
45302
45303
45304
45305
45306
45307
45308
45309
45310
45311
45312
45313
45314
45315
45316
45317
45318
45319
45320
45321
45322
45323
45324
45325
45326
45327
45328
45329
45330
45331
45332
45333
45334
45335
45336
45337
45338
45339
45340
45341
45342
45343
45344
45345
45346
45347
45348
45349
45350
45351
45352
45353
45354
45355
45356
45357
45358
45359
45360
45361
45362
45363
45364
45365
45366
45367
45368
45369
45370
45371
45372
45373
45374
45375
45376
45377
45378
45379
45380
45381
45382
45383
45384
45385
45386
45387
45388
45389
45390
45391
45392
45393
45394
45395
45396
45397
45398
45399
45400
45401
45402
45403
45404
45405
45406
45407
45408
45409
45410
45411
45412
45413
45414
45415
45416
45417
45418
45419
45420
45421
45422
45423
45424
45425
45426
45427
45428
45429
45430
45431
45432
45433
45434
45435
45436
45437
45438
45439
45440
45441
45442
45443
45444
45445
45446
45447
45448
45449
45450
45451
45452
45453
45454
45455
45456
45457
45458
45459
45460
45461
45462
45463
45464
45465
45466
45467
45468
45469
45470
45471
45472
45473
45474
45475
45476
45477
45478
45479
45480
45481
45482
45483
45484
45485
45486
45487
45488
45489
45490
45491
45492
45493
45494
45495
45496
45497
45498
45499
45500
45501
45502
45503
45504
45505
45506
45507
45508
45509
45510
45511
45512
45513
45514
45515
45516
45517
45518
45519
45520
45521
45522
45523
45524
45525
45526
45527
45528
45529
45530
45531
45532
45533
45534
45535
45536
45537
45538
45539
45540
45541
45542
45543
45544
45545
45546
45547
45548
45549
45550
45551
45552
45553
45554
45555
45556
45557
45558
45559
45560
45561
45562
45563
45564
45565
45566
45567
45568
45569
45570
45571
45572
45573
45574
45575
45576
45577
45578
45579
45580
45581
45582
45583
45584
45585
45586
45587
45588
45589
45590
45591
45592
45593
45594
45595
45596
45597
45598
45599
45600
45601
45602
45603
45604
45605
45606
45607
45608
45609
45610
45611
45612
45613
45614
45615
45616
45617
45618
45619
45620
45621
45622
45623
45624
45625
45626
45627
45628
45629
45630
45631
45632
45633
45634
45635
45636
45637
45638
45639
45640
45641
45642
45643
45644
45645
45646
45647
45648
45649
45650
45651
45652
45653
45654
45655
45656
45657
45658
45659
45660
45661
45662
45663
45664
45665
45666
45667
45668
45669
45670
45671
45672
45673
45674
45675
45676
45677
45678
45679
45680
45681
45682
45683
45684
45685
45686
45687
45688
45689
45690
45691
45692
45693
45694
45695
45696
45697
45698
45699
45700
45701
45702
45703
45704
45705
45706
45707
45708
45709
45710
45711
45712
45713
45714
45715
45716
45717
45718
45719
45720
45721
45722
45723
45724
45725
45726
45727
45728
45729
45730
45731
45732
45733
45734
45735
45736
45737
45738
45739
45740
45741
45742
45743
45744
45745
45746
45747
45748
45749
45750
45751
45752
45753
45754
45755
45756
45757
45758
45759
45760
45761
45762
45763
45764
45765
45766
45767
45768
45769
45770
45771
45772
45773
45774
45775
45776
45777
45778
45779
45780
45781
45782
45783
45784
45785
45786
45787
45788
45789
45790
45791
45792
45793
45794
45795
45796
45797
45798
45799
45800
45801
45802
45803
45804
45805
45806
45807
45808
45809
45810
45811
45812
45813
45814
45815
45816
45817
45818
45819
45820
45821
45822
45823
45824
45825
45826
45827
45828
45829
45830
45831
45832
45833
45834
45835
45836
45837
45838
45839
45840
45841
45842
45843
45844
45845
45846
45847
45848
45849
45850
45851
45852
45853
45854
45855
45856
45857
45858
45859
45860
45861
45862
45863
45864
45865
45866
45867
45868
45869
45870
45871
45872
45873
45874
45875
45876
45877
45878
45879
45880
45881
45882
45883
45884
45885
45886
45887
45888
45889
45890
45891
45892
45893
45894
45895
45896
45897
45898
45899
45900
45901
45902
45903
45904
45905
45906
45907
45908
45909
45910
45911
45912
45913
45914
45915
45916
45917
45918
45919
45920
45921
45922
45923
45924
45925
45926
45927
45928
45929
45930
45931
45932
45933
45934
45935
45936
45937
45938
45939
45940
45941
45942
45943
45944
45945
45946
45947
45948
45949
45950
45951
45952
45953
45954
45955
45956
45957
45958
45959
45960
45961
45962
45963
45964
45965
45966
45967
45968
45969
45970
45971
45972
45973
45974
45975
45976
45977
45978
45979
45980
45981
45982
45983
45984
45985
45986
45987
45988
45989
45990
45991
45992
45993
45994
45995
45996
45997
45998
45999
46000
46001
46002
46003
46004
46005
46006
46007
46008
46009
46010
46011
46012
46013
46014
46015
46016
46017
46018
46019
46020
46021
46022
46023
46024
46025
46026
46027
46028
46029
46030
46031
46032
46033
46034
46035
46036
46037
46038
46039
46040
46041
46042
46043
46044
46045
46046
46047
46048
46049
46050
46051
46052
46053
46054
46055
46056
46057
46058
46059
46060
46061
46062
46063
46064
46065
46066
46067
46068
46069
46070
46071
46072
46073
46074
46075
46076
46077
46078
46079
46080
46081
46082
46083
46084
46085
46086
46087
46088
46089
46090
46091
46092
46093
46094
46095
46096
46097
46098
46099
46100
46101
46102
46103
46104
46105
46106
46107
46108
46109
46110
46111
46112
46113
46114
46115
46116
46117
46118
46119
46120
46121
46122
46123
46124
46125
46126
46127
46128
46129
46130
46131
46132
46133
46134
46135
46136
46137
46138
46139
46140
46141
46142
46143
46144
46145
46146
46147
46148
46149
46150
46151
46152
46153
46154
46155
46156
46157
46158
46159
46160
46161
46162
46163
46164
46165
46166
46167
46168
46169
46170
46171
46172
46173
46174
46175
46176
46177
46178
46179
46180
46181
46182
46183
46184
46185
46186
46187
46188
46189
46190
46191
46192
46193
46194
46195
46196
46197
46198
46199
46200
46201
46202
46203
46204
46205
46206
46207
46208
46209
46210
46211
46212
46213
46214
46215
46216
46217
46218
46219
46220
46221
46222
46223
46224
46225
46226
46227
46228
46229
46230
46231
46232
46233
46234
46235
46236
46237
46238
46239
46240
46241
46242
46243
46244
46245
46246
46247
46248
46249
46250
46251
46252
46253
46254
46255
46256
46257
46258
46259
46260
46261
46262
46263
46264
46265
46266
46267
46268
46269
46270
46271
46272
46273
46274
46275
46276
46277
46278
46279
46280
46281
46282
46283
46284
46285
46286
46287
46288
46289
46290
46291
46292
46293
46294
46295
46296
46297
46298
46299
46300
46301
46302
46303
46304
46305
46306
46307
46308
46309
46310
46311
46312
46313
46314
46315
46316
46317
46318
46319
46320
46321
46322
46323
46324
46325
46326
46327
46328
46329
46330
46331
46332
46333
46334
46335
46336
46337
46338
46339
46340
46341
46342
46343
46344
46345
46346
46347
46348
46349
46350
46351
46352
46353
46354
46355
46356
46357
46358
46359
46360
46361
46362
46363
46364
46365
46366
46367
46368
46369
46370
46371
46372
46373
46374
46375
46376
46377
46378
46379
46380
46381
46382
46383
46384
46385
46386
46387
46388
46389
46390
46391
46392
46393
46394
46395
46396
46397
46398
46399
46400
46401
46402
46403
46404
46405
46406
46407
46408
46409
46410
46411
46412
46413
46414
46415
46416
46417
46418
46419
46420
46421
46422
46423
46424
46425
46426
46427
46428
46429
46430
46431
46432
46433
46434
46435
46436
46437
46438
46439
46440
46441
46442
46443
46444
46445
46446
46447
46448
46449
46450
46451
46452
46453
46454
46455
46456
46457
46458
46459
46460
46461
46462
46463
46464
46465
46466
46467
46468
46469
46470
46471
46472
46473
46474
46475
46476
46477
46478
46479
46480
46481
46482
46483
46484
46485
46486
46487
46488
46489
46490
46491
46492
46493
46494
46495
46496
46497
46498
46499
46500
46501
46502
46503
46504
46505
46506
46507
46508
46509
46510
46511
46512
46513
46514
46515
46516
46517
46518
46519
46520
46521
46522
46523
46524
46525
46526
46527
46528
46529
46530
46531
46532
46533
46534
46535
46536
46537
46538
46539
46540
46541
46542
46543
46544
46545
46546
46547
46548
46549
46550
46551
46552
46553
46554
46555
46556
46557
46558
46559
46560
46561
46562
46563
46564
46565
46566
46567
46568
46569
46570
46571
46572
46573
46574
46575
46576
46577
46578
46579
46580
46581
46582
46583
46584
46585
46586
46587
46588
46589
46590
46591
46592
46593
46594
46595
46596
46597
46598
46599
46600
46601
46602
46603
46604
46605
46606
46607
46608
46609
46610
46611
46612
46613
46614
46615
46616
46617
46618
46619
46620
46621
46622
46623
46624
46625
46626
46627
46628
46629
46630
46631
46632
46633
46634
46635
46636
46637
46638
46639
46640
46641
46642
46643
46644
46645
46646
46647
46648
46649
46650
46651
46652
46653
46654
46655
46656
46657
46658
46659
46660
46661
46662
46663
46664
46665
46666
46667
46668
46669
46670
46671
46672
46673
46674
46675
46676
46677
46678
46679
46680
46681
46682
46683
46684
46685
46686
46687
46688
46689
46690
46691
46692
46693
46694
46695
46696
46697
46698
46699
46700
46701
46702
46703
46704
46705
46706
46707
46708
46709
46710
46711
46712
46713
46714
46715
46716
46717
46718
46719
46720
46721
46722
46723
46724
46725
46726
46727
46728
46729
46730
46731
46732
46733
46734
46735
46736
46737
46738
46739
46740
46741
46742
46743
46744
46745
46746
46747
46748
46749
46750
46751
46752
46753
46754
46755
46756
46757
46758
46759
46760
46761
46762
46763
46764
46765
46766
46767
46768
46769
46770
46771
46772
46773
46774
46775
46776
46777
46778
46779
46780
46781
46782
46783
46784
46785
46786
46787
46788
46789
46790
46791
46792
46793
46794
46795
46796
46797
46798
46799
46800
46801
46802
46803
46804
46805
46806
46807
46808
46809
46810
46811
46812
46813
46814
46815
46816
46817
46818
46819
46820
46821
46822
46823
46824
46825
46826
46827
46828
46829
46830
46831
46832
46833
46834
46835
46836
46837
46838
46839
46840
46841
46842
46843
46844
46845
46846
46847
46848
46849
46850
46851
46852
46853
46854
46855
46856
46857
46858
46859
46860
46861
46862
46863
46864
46865
46866
46867
46868
46869
46870
46871
46872
46873
46874
46875
46876
46877
46878
46879
46880
46881
46882
46883
46884
46885
46886
46887
46888
46889
46890
46891
46892
46893
46894
46895
46896
46897
46898
46899
46900
46901
46902
46903
46904
46905
46906
46907
46908
46909
46910
46911
46912
46913
46914
46915
46916
46917
46918
46919
46920
46921
46922
46923
46924
46925
46926
46927
46928
46929
46930
46931
46932
46933
46934
46935
46936
46937
46938
46939
46940
46941
46942
46943
46944
46945
46946
46947
46948
46949
46950
46951
46952
46953
46954
46955
46956
46957
46958
46959
46960
46961
46962
46963
46964
46965
46966
46967
46968
46969
46970
46971
46972
46973
46974
46975
46976
46977
46978
46979
46980
46981
46982
46983
46984
46985
46986
46987
46988
46989
46990
46991
46992
46993
46994
46995
46996
46997
46998
46999
47000
47001
47002
47003
47004
47005
47006
47007
47008
47009
47010
47011
47012
47013
47014
47015
47016
47017
47018
47019
47020
47021
47022
47023
47024
47025
47026
47027
47028
47029
47030
47031
47032
47033
47034
47035
47036
47037
47038
47039
47040
47041
47042
47043
47044
47045
47046
47047
47048
47049
47050
47051
47052
47053
47054
47055
47056
47057
47058
47059
47060
47061
47062
47063
47064
47065
47066
47067
47068
47069
47070
47071
47072
47073
47074
47075
47076
47077
47078
47079
47080
47081
47082
47083
47084
47085
47086
47087
47088
47089
47090
47091
47092
47093
47094
47095
47096
47097
47098
47099
47100
47101
47102
47103
47104
47105
47106
47107
47108
47109
47110
47111
47112
47113
47114
47115
47116
47117
47118
47119
47120
47121
47122
47123
47124
47125
47126
47127
47128
47129
47130
47131
47132
47133
47134
47135
47136
47137
47138
47139
47140
47141
47142
47143
47144
47145
47146
47147
47148
47149
47150
47151
47152
47153
47154
47155
47156
47157
47158
47159
47160
47161
47162
47163
47164
47165
47166
47167
47168
47169
47170
47171
47172
47173
47174
47175
47176
47177
47178
47179
47180
47181
47182
47183
47184
47185
47186
47187
47188
47189
47190
47191
47192
47193
47194
47195
47196
47197
47198
47199
47200
47201
47202
47203
47204
47205
47206
47207
47208
47209
47210
47211
47212
47213
47214
47215
47216
47217
47218
47219
47220
47221
47222
47223
47224
47225
47226
47227
47228
47229
47230
47231
47232
47233
47234
47235
47236
47237
47238
47239
47240
47241
47242
47243
47244
47245
47246
47247
47248
47249
47250
47251
47252
47253
47254
47255
47256
47257
47258
47259
47260
47261
47262
47263
47264
47265
47266
47267
47268
47269
47270
47271
47272
47273
47274
47275
47276
47277
47278
47279
47280
47281
47282
47283
47284
47285
47286
47287
47288
47289
47290
47291
47292
47293
47294
47295
47296
47297
47298
47299
47300
47301
47302
47303
47304
47305
47306
47307
47308
47309
47310
47311
47312
47313
47314
47315
47316
47317
47318
47319
47320
47321
47322
47323
47324
47325
47326
47327
47328
47329
47330
47331
47332
47333
47334
47335
47336
47337
47338
47339
47340
47341
47342
47343
47344
47345
47346
47347
47348
47349
47350
47351
47352
47353
47354
47355
47356
47357
47358
47359
47360
47361
47362
47363
47364
47365
47366
47367
47368
47369
47370
47371
47372
47373
47374
47375
47376
47377
47378
47379
47380
47381
47382
47383
47384
47385
47386
47387
47388
47389
47390
47391
47392
47393
47394
47395
47396
47397
47398
47399
47400
47401
47402
47403
47404
47405
47406
47407
47408
47409
47410
47411
47412
47413
47414
47415
47416
47417
47418
47419
47420
47421
47422
47423
47424
47425
47426
47427
47428
47429
47430
47431
47432
47433
47434
47435
47436
47437
47438
47439
47440
47441
47442
47443
47444
47445
47446
47447
47448
47449
47450
47451
47452
47453
47454
47455
47456
47457
47458
47459
47460
47461
47462
47463
47464
47465
47466
47467
47468
47469
47470
47471
47472
47473
47474
47475
47476
47477
47478
47479
47480
47481
47482
47483
47484
47485
47486
47487
47488
47489
47490
47491
47492
47493
47494
47495
47496
47497
47498
47499
47500
47501
47502
47503
47504
47505
47506
47507
47508
47509
47510
47511
47512
47513
47514
47515
47516
47517
47518
47519
47520
47521
47522
47523
47524
47525
47526
47527
47528
47529
47530
47531
47532
47533
47534
47535
47536
47537
47538
47539
47540
47541
47542
47543
47544
47545
47546
47547
47548
47549
47550
47551
47552
47553
47554
47555
47556
47557
47558
47559
47560
47561
47562
47563
47564
47565
47566
47567
47568
47569
47570
47571
47572
47573
47574
47575
47576
47577
47578
47579
47580
47581
47582
47583
47584
47585
47586
47587
47588
47589
47590
47591
47592
47593
47594
47595
47596
47597
47598
47599
47600
47601
47602
47603
47604
47605
47606
47607
47608
47609
47610
47611
47612
47613
47614
47615
47616
47617
47618
47619
47620
47621
47622
47623
47624
47625
47626
47627
47628
47629
47630
47631
47632
47633
47634
47635
47636
47637
47638
47639
47640
47641
47642
47643
47644
47645
47646
47647
47648
47649
47650
47651
47652
47653
47654
47655
47656
47657
47658
47659
47660
47661
47662
47663
47664
47665
47666
47667
47668
47669
47670
47671
47672
47673
47674
47675
47676
47677
47678
47679
47680
47681
47682
47683
47684
47685
47686
47687
47688
47689
47690
47691
47692
47693
47694
47695
47696
47697
47698
47699
47700
47701
47702
47703
47704
47705
47706
47707
47708
47709
47710
47711
47712
47713
47714
47715
47716
47717
47718
47719
47720
47721
47722
47723
47724
47725
47726
47727
47728
47729
47730
47731
47732
47733
47734
47735
47736
47737
47738
47739
47740
47741
47742
47743
47744
47745
47746
47747
47748
47749
47750
47751
47752
47753
47754
47755
47756
47757
47758
47759
47760
47761
47762
47763
47764
47765
47766
47767
47768
47769
47770
47771
47772
47773
47774
47775
47776
47777
47778
47779
47780
47781
47782
47783
47784
47785
47786
47787
47788
47789
47790
47791
47792
47793
47794
47795
47796
47797
47798
47799
47800
47801
47802
47803
47804
47805
47806
47807
47808
47809
47810
47811
47812
47813
47814
47815
47816
47817
47818
47819
47820
47821
47822
47823
47824
47825
47826
47827
47828
47829
47830
47831
47832
47833
47834
47835
47836
47837
47838
47839
47840
47841
47842
47843
47844
47845
47846
47847
47848
47849
47850
47851
47852
47853
47854
47855
47856
47857
47858
47859
47860
47861
47862
47863
47864
47865
47866
47867
47868
47869
47870
47871
47872
47873
47874
47875
47876
47877
47878
47879
47880
47881
47882
47883
47884
47885
47886
47887
47888
47889
47890
47891
47892
47893
47894
47895
47896
47897
47898
47899
47900
47901
47902
47903
47904
47905
47906
47907
47908
47909
47910
47911
47912
47913
47914
47915
47916
47917
47918
47919
47920
47921
47922
47923
47924
47925
47926
47927
47928
47929
47930
47931
47932
47933
47934
47935
47936
47937
47938
47939
47940
47941
47942
47943
47944
47945
47946
47947
47948
47949
47950
47951
47952
47953
47954
47955
47956
47957
47958
47959
47960
47961
47962
47963
47964
47965
47966
47967
47968
47969
47970
47971
47972
47973
47974
47975
47976
47977
47978
47979
47980
47981
47982
47983
47984
47985
47986
47987
47988
47989
47990
47991
47992
47993
47994
47995
47996
47997
47998
47999
48000
48001
48002
48003
48004
48005
48006
48007
48008
48009
48010
48011
48012
48013
48014
48015
48016
48017
48018
48019
48020
48021
48022
48023
48024
48025
48026
48027
48028
48029
48030
48031
48032
48033
48034
48035
48036
48037
48038
48039
48040
48041
48042
48043
48044
48045
48046
48047
48048
48049
48050
48051
48052
48053
48054
48055
48056
48057
48058
48059
48060
48061
48062
48063
48064
48065
48066
48067
48068
48069
48070
48071
48072
48073
48074
48075
48076
48077
48078
48079
48080
48081
48082
48083
48084
48085
48086
48087
48088
48089
48090
48091
48092
48093
48094
48095
48096
48097
48098
48099
48100
48101
48102
48103
48104
48105
48106
48107
48108
48109
48110
48111
48112
48113
48114
48115
48116
48117
48118
48119
48120
48121
48122
48123
48124
48125
48126
48127
48128
48129
48130
48131
48132
48133
48134
48135
48136
48137
48138
48139
48140
48141
48142
48143
48144
48145
48146
48147
48148
48149
48150
48151
48152
48153
48154
48155
48156
48157
48158
48159
48160
48161
48162
48163
48164
48165
48166
48167
48168
48169
48170
48171
48172
48173
48174
48175
48176
48177
48178
48179
48180
48181
48182
48183
48184
48185
48186
48187
48188
48189
48190
48191
48192
48193
48194
48195
48196
48197
48198
48199
48200
48201
48202
48203
48204
48205
48206
48207
48208
48209
48210
48211
48212
48213
48214
48215
48216
48217
48218
48219
48220
48221
48222
48223
48224
48225
48226
48227
48228
48229
48230
48231
48232
48233
48234
48235
48236
48237
48238
48239
48240
48241
48242
48243
48244
48245
48246
48247
48248
48249
48250
48251
48252
48253
48254
48255
48256
48257
48258
48259
48260
48261
48262
48263
48264
48265
48266
48267
48268
48269
48270
48271
48272
48273
48274
48275
48276
48277
48278
48279
48280
48281
48282
48283
48284
48285
48286
48287
48288
48289
48290
48291
48292
48293
48294
48295
48296
48297
48298
48299
48300
48301
48302
48303
48304
48305
48306
48307
48308
48309
48310
48311
48312
48313
48314
48315
48316
48317
48318
48319
48320
48321
48322
48323
48324
48325
48326
48327
48328
48329
48330
48331
48332
48333
48334
48335
48336
48337
48338
48339
48340
48341
48342
48343
48344
48345
48346
48347
48348
48349
48350
48351
48352
48353
48354
48355
48356
48357
48358
48359
48360
48361
48362
48363
48364
48365
48366
48367
48368
48369
48370
48371
48372
48373
48374
48375
48376
48377
48378
48379
48380
48381
48382
48383
48384
48385
48386
48387
48388
48389
48390
48391
48392
48393
48394
48395
48396
48397
48398
48399
48400
48401
48402
48403
48404
48405
48406
48407
48408
48409
48410
48411
48412
48413
48414
48415
48416
48417
48418
48419
48420
48421
48422
48423
48424
48425
48426
48427
48428
48429
48430
48431
48432
48433
48434
48435
48436
48437
48438
48439
48440
48441
48442
48443
48444
48445
48446
48447
48448
48449
48450
48451
48452
48453
48454
48455
48456
48457
48458
48459
48460
48461
48462
48463
48464
48465
48466
48467
48468
48469
48470
48471
48472
48473
48474
48475
48476
48477
48478
48479
48480
48481
48482
48483
48484
48485
48486
48487
48488
48489
48490
48491
48492
48493
48494
48495
48496
48497
48498
48499
48500
48501
48502
48503
48504
48505
48506
48507
48508
48509
48510
48511
48512
48513
48514
48515
48516
48517
48518
48519
48520
48521
48522
48523
48524
48525
48526
48527
48528
48529
48530
48531
48532
48533
48534
48535
48536
48537
48538
48539
48540
48541
48542
48543
48544
48545
48546
48547
48548
48549
48550
48551
48552
48553
48554
48555
48556
48557
48558
48559
48560
48561
48562
48563
48564
48565
48566
48567
48568
48569
48570
48571
48572
48573
48574
48575
48576
48577
48578
48579
48580
48581
48582
48583
48584
48585
48586
48587
48588
48589
48590
48591
48592
48593
48594
48595
48596
48597
48598
48599
48600
48601
48602
48603
48604
48605
48606
48607
48608
48609
48610
48611
48612
48613
48614
48615
48616
48617
48618
48619
48620
48621
48622
48623
48624
48625
48626
48627
48628
48629
48630
48631
48632
48633
48634
48635
48636
48637
48638
48639
48640
48641
48642
48643
48644
48645
48646
48647
48648
48649
48650
48651
48652
48653
48654
48655
48656
48657
48658
48659
48660
48661
48662
48663
48664
48665
48666
48667
48668
48669
48670
48671
48672
48673
48674
48675
48676
48677
48678
48679
48680
48681
48682
48683
48684
48685
48686
48687
48688
48689
48690
48691
48692
48693
48694
48695
48696
48697
48698
48699
48700
48701
48702
48703
48704
48705
48706
48707
48708
48709
48710
48711
48712
48713
48714
48715
48716
48717
48718
48719
48720
48721
48722
48723
48724
48725
48726
48727
48728
48729
48730
48731
48732
48733
48734
48735
48736
48737
48738
48739
48740
48741
48742
48743
48744
48745
48746
48747
48748
48749
48750
48751
48752
48753
48754
48755
48756
48757
48758
48759
48760
48761
48762
48763
48764
48765
48766
48767
48768
48769
48770
48771
48772
48773
48774
48775
48776
48777
48778
48779
48780
48781
48782
48783
48784
48785
48786
48787
48788
48789
48790
48791
48792
48793
48794
48795
48796
48797
48798
48799
48800
48801
48802
48803
48804
48805
48806
48807
48808
48809
48810
48811
48812
48813
48814
48815
48816
48817
48818
48819
48820
48821
48822
48823
48824
48825
48826
48827
48828
48829
48830
48831
48832
48833
48834
48835
48836
48837
48838
48839
48840
48841
48842
48843
48844
48845
48846
48847
48848
48849
48850
48851
48852
48853
48854
48855
48856
48857
48858
48859
48860
48861
48862
48863
48864
48865
48866
48867
48868
48869
48870
48871
48872
48873
48874
48875
48876
48877
48878
48879
48880
48881
48882
48883
48884
48885
48886
48887
48888
48889
48890
48891
48892
48893
48894
48895
48896
48897
48898
48899
48900
48901
48902
48903
48904
48905
48906
48907
48908
48909
48910
48911
48912
48913
48914
48915
48916
48917
48918
48919
48920
48921
48922
48923
48924
48925
48926
48927
48928
48929
48930
48931
48932
48933
48934
48935
48936
48937
48938
48939
48940
48941
48942
48943
48944
48945
48946
48947
48948
48949
48950
48951
48952
48953
48954
48955
48956
48957
48958
48959
48960
48961
48962
48963
48964
48965
48966
48967
48968
48969
48970
48971
48972
48973
48974
48975
48976
48977
48978
48979
48980
48981
48982
48983
48984
48985
48986
48987
48988
48989
48990
48991
48992
48993
48994
48995
48996
48997
48998
48999
49000
49001
49002
49003
49004
49005
49006
49007
49008
49009
49010
49011
49012
49013
49014
49015
49016
49017
49018
49019
49020
49021
49022
49023
49024
49025
49026
49027
49028
49029
49030
49031
49032
49033
49034
49035
49036
49037
49038
49039
49040
49041
49042
49043
49044
49045
49046
49047
49048
49049
49050
49051
49052
49053
49054
49055
49056
49057
49058
49059
49060
49061
49062
49063
49064
49065
49066
49067
49068
49069
49070
49071
49072
49073
49074
49075
49076
49077
49078
49079
49080
49081
49082
49083
49084
49085
49086
49087
49088
49089
49090
49091
49092
49093
49094
49095
49096
49097
49098
49099
49100
49101
49102
49103
49104
49105
49106
49107
49108
49109
49110
49111
49112
49113
49114
49115
49116
49117
49118
49119
49120
49121
49122
49123
49124
49125
49126
49127
49128
49129
49130
49131
49132
49133
49134
49135
49136
49137
49138
49139
49140
49141
49142
49143
49144
49145
49146
49147
49148
49149
49150
49151
49152
49153
49154
49155
49156
49157
49158
49159
49160
49161
49162
49163
49164
49165
49166
49167
49168
49169
49170
49171
49172
49173
49174
49175
49176
49177
49178
49179
49180
49181
49182
49183
49184
49185
49186
49187
49188
49189
49190
49191
49192
49193
49194
49195
49196
49197
49198
49199
49200
49201
49202
49203
49204
49205
49206
49207
49208
49209
49210
49211
49212
49213
49214
49215
49216
49217
49218
49219
49220
49221
49222
49223
49224
49225
49226
49227
49228
49229
49230
49231
49232
49233
49234
49235
49236
49237
49238
49239
49240
49241
49242
49243
49244
49245
49246
49247
49248
49249
49250
49251
49252
49253
49254
49255
49256
49257
49258
49259
49260
49261
49262
49263
49264
49265
49266
49267
49268
49269
49270
49271
49272
49273
49274
49275
49276
49277
49278
49279
49280
49281
49282
49283
49284
49285
49286
49287
49288
49289
49290
49291
49292
49293
49294
49295
49296
49297
49298
49299
49300
49301
49302
49303
49304
49305
49306
49307
49308
49309
49310
49311
49312
49313
49314
49315
49316
49317
49318
49319
49320
49321
49322
49323
49324
49325
49326
49327
49328
49329
49330
49331
49332
49333
49334
49335
49336
49337
49338
49339
49340
49341
49342
49343
49344
49345
49346
49347
49348
49349
49350
49351
49352
49353
49354
49355
49356
49357
49358
49359
49360
49361
49362
49363
49364
49365
49366
49367
49368
49369
49370
49371
49372
49373
49374
49375
49376
49377
49378
49379
49380
49381
49382
49383
49384
49385
49386
49387
49388
49389
49390
49391
49392
49393
49394
49395
49396
49397
49398
49399
49400
49401
49402
49403
49404
49405
49406
49407
49408
49409
49410
49411
49412
49413
49414
49415
49416
49417
49418
49419
49420
49421
49422
49423
49424
49425
49426
49427
49428
49429
49430
49431
49432
49433
49434
49435
49436
49437
49438
49439
49440
49441
49442
49443
49444
49445
49446
49447
49448
49449
49450
49451
49452
49453
49454
49455
49456
49457
49458
49459
49460
49461
49462
49463
49464
49465
49466
49467
49468
49469
49470
49471
49472
49473
49474
49475
49476
49477
49478
49479
49480
49481
49482
49483
49484
49485
49486
49487
49488
49489
49490
49491
49492
49493
49494
49495
49496
49497
49498
49499
49500
49501
49502
49503
49504
49505
49506
49507
49508
49509
49510
49511
49512
49513
49514
49515
49516
49517
49518
49519
49520
49521
49522
49523
49524
49525
49526
49527
49528
49529
49530
49531
49532
49533
49534
49535
49536
49537
49538
49539
49540
49541
49542
49543
49544
49545
49546
49547
49548
49549
49550
49551
49552
49553
49554
49555
49556
49557
49558
49559
49560
49561
49562
49563
49564
49565
49566
49567
49568
49569
49570
49571
49572
49573
49574
49575
49576
49577
49578
49579
49580
49581
49582
49583
49584
49585
49586
49587
49588
49589
49590
49591
49592
49593
49594
49595
49596
49597
49598
49599
49600
49601
49602
49603
49604
49605
49606
49607
49608
49609
49610
49611
49612
49613
49614
49615
49616
49617
49618
49619
49620
49621
49622
49623
49624
49625
49626
49627
49628
49629
49630
49631
49632
49633
49634
49635
49636
49637
49638
49639
49640
49641
49642
49643
49644
49645
49646
49647
49648
49649
49650
49651
49652
49653
49654
49655
49656
49657
49658
49659
49660
49661
49662
49663
49664
49665
49666
49667
49668
49669
49670
49671
49672
49673
49674
49675
49676
49677
49678
49679
49680
49681
49682
49683
49684
49685
49686
49687
49688
49689
49690
49691
49692
49693
49694
49695
49696
49697
49698
49699
49700
49701
49702
49703
49704
49705
49706
49707
49708
49709
49710
49711
49712
49713
49714
49715
49716
49717
49718
49719
49720
49721
49722
49723
49724
49725
49726
49727
49728
49729
49730
49731
49732
49733
49734
49735
49736
49737
49738
49739
49740
49741
49742
49743
49744
49745
49746
49747
49748
49749
49750
49751
49752
49753
49754
49755
49756
49757
49758
49759
49760
49761
49762
49763
49764
49765
49766
49767
49768
49769
49770
49771
49772
49773
49774
49775
49776
49777
49778
49779
49780
49781
49782
49783
49784
49785
49786
49787
49788
49789
49790
49791
49792
49793
49794
49795
49796
49797
49798
49799
49800
49801
49802
49803
49804
49805
49806
49807
49808
49809
49810
49811
49812
49813
49814
49815
49816
49817
49818
49819
49820
49821
49822
49823
49824
49825
49826
49827
49828
49829
49830
49831
49832
49833
49834
49835
49836
49837
49838
49839
49840
49841
49842
49843
49844
49845
49846
49847
49848
49849
49850
49851
49852
49853
49854
49855
49856
49857
49858
49859
49860
49861
49862
49863
49864
49865
49866
49867
49868
49869
49870
49871
49872
49873
49874
49875
49876
49877
49878
49879
49880
49881
49882
49883
49884
49885
49886
49887
49888
49889
49890
49891
49892
49893
49894
49895
49896
49897
49898
49899
49900
49901
49902
49903
49904
49905
49906
49907
49908
49909
49910
49911
49912
49913
49914
49915
49916
49917
49918
49919
49920
49921
49922
49923
49924
49925
49926
49927
49928
49929
49930
49931
49932
49933
49934
49935
49936
49937
49938
49939
49940
49941
49942
49943
49944
49945
49946
49947
49948
49949
49950
49951
49952
49953
49954
49955
49956
49957
49958
49959
49960
49961
49962
49963
49964
49965
49966
49967
49968
49969
49970
49971
49972
49973
49974
49975
49976
49977
49978
49979
49980
49981
49982
49983
49984
49985
49986
49987
49988
49989
49990
49991
49992
49993
49994
49995
49996
49997
49998
49999
50000
50001
50002
50003
50004
50005
50006
50007
50008
50009
50010
50011
50012
50013
50014
50015
50016
50017
50018
50019
50020
50021
50022
50023
50024
50025
50026
50027
50028
50029
50030
50031
50032
50033
50034
50035
50036
50037
50038
50039
50040
50041
50042
50043
50044
50045
50046
50047
50048
50049
50050
50051
50052
50053
50054
50055
50056
50057
50058
50059
50060
50061
50062
50063
50064
50065
50066
50067
50068
50069
50070
50071
50072
50073
50074
50075
50076
50077
50078
50079
50080
50081
50082
50083
50084
50085
50086
50087
50088
50089
50090
50091
50092
50093
50094
50095
50096
50097
50098
50099
50100
50101
50102
50103
50104
50105
50106
50107
50108
50109
50110
50111
50112
50113
50114
50115
50116
50117
50118
50119
50120
50121
50122
50123
50124
50125
50126
50127
50128
50129
50130
50131
50132
50133
50134
50135
50136
50137
50138
50139
50140
50141
50142
50143
50144
50145
50146
50147
50148
50149
50150
50151
50152
50153
50154
50155
50156
50157
50158
50159
50160
50161
50162
50163
50164
50165
50166
50167
50168
50169
50170
50171
50172
50173
50174
50175
50176
50177
50178
50179
50180
50181
50182
50183
50184
50185
50186
50187
50188
50189
50190
50191
50192
50193
50194
50195
50196
50197
50198
50199
50200
50201
50202
50203
50204
50205
50206
50207
50208
50209
50210
50211
50212
50213
50214
50215
50216
50217
50218
50219
50220
50221
50222
50223
50224
50225
50226
50227
50228
50229
50230
50231
50232
50233
50234
50235
50236
50237
50238
50239
50240
50241
50242
50243
50244
50245
50246
50247
50248
50249
50250
50251
50252
50253
50254
50255
50256
50257
50258
50259
50260
50261
50262
50263
50264
50265
50266
50267
50268
50269
50270
50271
50272
50273
50274
50275
50276
50277
50278
50279
50280
50281
50282
50283
50284
50285
50286
50287
50288
50289
50290
50291
50292
50293
50294
50295
50296
50297
50298
50299
50300
50301
50302
50303
50304
50305
50306
50307
50308
50309
50310
50311
50312
50313
50314
50315
50316
50317
50318
50319
50320
50321
50322
50323
50324
50325
50326
50327
50328
50329
50330
50331
50332
50333
50334
50335
50336
50337
50338
50339
50340
50341
50342
50343
50344
50345
50346
50347
50348
50349
50350
50351
50352
50353
50354
50355
50356
50357
50358
50359
50360
50361
50362
50363
50364
50365
50366
50367
50368
50369
50370
50371
50372
50373
50374
50375
50376
50377
50378
50379
50380
50381
50382
50383
50384
50385
50386
50387
50388
50389
50390
50391
50392
50393
50394
50395
50396
50397
50398
50399
50400
50401
50402
50403
50404
50405
50406
50407
50408
50409
50410
50411
50412
50413
50414
50415
50416
50417
50418
50419
50420
50421
50422
50423
50424
50425
50426
50427
50428
50429
50430
50431
50432
50433
50434
50435
50436
50437
50438
50439
50440
50441
50442
50443
50444
50445
50446
50447
50448
50449
50450
50451
50452
50453
50454
50455
50456
50457
50458
50459
50460
50461
50462
50463
50464
50465
50466
50467
50468
50469
50470
50471
50472
50473
50474
50475
50476
50477
50478
50479
50480
50481
50482
50483
50484
50485
50486
50487
50488
50489
50490
50491
50492
50493
50494
50495
50496
50497
50498
50499
50500
50501
50502
50503
50504
50505
50506
50507
50508
50509
50510
50511
50512
50513
50514
50515
50516
50517
50518
50519
50520
50521
50522
50523
50524
50525
50526
50527
50528
50529
50530
50531
50532
50533
50534
50535
50536
50537
50538
50539
50540
50541
50542
50543
50544
50545
50546
50547
50548
50549
50550
50551
50552
50553
50554
50555
50556
50557
50558
50559
50560
50561
50562
50563
50564
50565
50566
50567
50568
50569
50570
50571
50572
50573
50574
50575
50576
50577
50578
50579
50580
50581
50582
50583
50584
50585
50586
50587
50588
50589
50590
50591
50592
50593
50594
50595
50596
50597
50598
50599
50600
50601
50602
50603
50604
50605
50606
50607
50608
50609
50610
50611
50612
50613
50614
50615
50616
50617
50618
50619
50620
50621
50622
50623
50624
50625
50626
50627
50628
50629
50630
50631
50632
50633
50634
50635
50636
50637
50638
50639
50640
50641
50642
50643
50644
50645
50646
50647
50648
50649
50650
50651
50652
50653
50654
50655
50656
50657
50658
50659
50660
50661
50662
50663
50664
50665
50666
50667
50668
50669
50670
50671
50672
50673
50674
50675
50676
50677
50678
50679
50680
50681
50682
50683
50684
50685
50686
50687
50688
50689
50690
50691
50692
50693
50694
50695
50696
50697
50698
50699
50700
50701
50702
50703
50704
50705
50706
50707
50708
50709
50710
50711
50712
50713
50714
50715
50716
50717
50718
50719
50720
50721
50722
50723
50724
50725
50726
50727
50728
50729
50730
50731
50732
50733
50734
50735
50736
50737
50738
50739
50740
50741
50742
50743
50744
50745
50746
50747
50748
50749
50750
50751
50752
50753
50754
50755
50756
50757
50758
50759
50760
50761
50762
50763
50764
50765
50766
50767
50768
50769
50770
50771
50772
50773
50774
50775
50776
50777
50778
50779
50780
50781
50782
50783
50784
50785
50786
50787
50788
50789
50790
50791
50792
50793
50794
50795
50796
50797
50798
50799
50800
50801
50802
50803
50804
50805
50806
50807
50808
50809
50810
50811
50812
50813
50814
50815
50816
50817
50818
50819
50820
50821
50822
50823
50824
50825
50826
50827
50828
50829
50830
50831
50832
50833
50834
50835
50836
50837
50838
50839
50840
50841
50842
50843
50844
50845
50846
50847
50848
50849
50850
50851
50852
50853
50854
50855
50856
50857
50858
50859
50860
50861
50862
50863
50864
50865
50866
50867
50868
50869
50870
50871
50872
50873
50874
50875
50876
50877
50878
50879
50880
50881
50882
50883
50884
50885
50886
50887
50888
50889
50890
50891
50892
50893
50894
50895
50896
50897
50898
50899
50900
50901
50902
50903
50904
50905
50906
50907
50908
50909
50910
50911
50912
50913
50914
50915
50916
50917
50918
50919
50920
50921
50922
50923
50924
50925
50926
50927
50928
50929
50930
50931
50932
50933
50934
50935
50936
50937
50938
50939
50940
50941
50942
50943
50944
50945
50946
50947
50948
50949
50950
50951
50952
50953
50954
50955
50956
50957
50958
50959
50960
50961
50962
50963
50964
50965
50966
50967
50968
50969
50970
50971
50972
50973
50974
50975
50976
50977
50978
50979
50980
50981
50982
50983
50984
50985
50986
50987
50988
50989
50990
50991
50992
50993
50994
50995
50996
50997
50998
50999
51000
51001
51002
51003
51004
51005
51006
51007
51008
51009
51010
51011
51012
51013
51014
51015
51016
51017
51018
51019
51020
51021
51022
51023
51024
51025
51026
51027
51028
51029
51030
51031
51032
51033
51034
51035
51036
51037
51038
51039
51040
51041
51042
51043
51044
51045
51046
51047
51048
51049
51050
51051
51052
51053
51054
51055
51056
51057
51058
51059
51060
51061
51062
51063
51064
51065
51066
51067
51068
51069
51070
51071
51072
51073
51074
51075
51076
51077
51078
51079
51080
51081
51082
51083
51084
51085
51086
51087
51088
51089
51090
51091
51092
51093
51094
51095
51096
51097
51098
51099
51100
51101
51102
51103
51104
51105
51106
51107
51108
51109
51110
51111
51112
51113
51114
51115
51116
51117
51118
51119
51120
51121
51122
51123
51124
51125
51126
51127
51128
51129
51130
51131
51132
51133
51134
51135
51136
51137
51138
51139
51140
51141
51142
51143
51144
51145
51146
51147
51148
51149
51150
51151
51152
51153
51154
51155
51156
51157
51158
51159
51160
51161
51162
51163
51164
51165
51166
51167
51168
51169
51170
51171
51172
51173
51174
51175
51176
51177
51178
51179
51180
51181
51182
51183
51184
51185
51186
51187
51188
51189
51190
51191
51192
51193
51194
51195
51196
51197
51198
51199
51200
51201
51202
51203
51204
51205
51206
51207
51208
51209
51210
51211
51212
51213
51214
51215
51216
51217
51218
51219
51220
51221
51222
51223
51224
51225
51226
51227
51228
51229
51230
51231
51232
51233
51234
51235
51236
51237
51238
51239
51240
51241
51242
51243
51244
51245
51246
51247
51248
51249
51250
51251
51252
51253
51254
51255
51256
51257
51258
51259
51260
51261
51262
51263
51264
51265
51266
51267
51268
51269
51270
51271
51272
51273
51274
51275
51276
51277
51278
51279
51280
51281
51282
51283
51284
51285
51286
51287
51288
51289
51290
51291
51292
51293
51294
51295
51296
51297
51298
51299
51300
51301
51302
51303
51304
51305
51306
51307
51308
51309
51310
51311
51312
51313
51314
51315
51316
51317
51318
51319
51320
51321
51322
51323
51324
51325
51326
51327
51328
51329
51330
51331
51332
51333
51334
51335
51336
51337
51338
51339
51340
51341
51342
51343
51344
51345
51346
51347
51348
51349
51350
51351
51352
51353
51354
51355
51356
51357
51358
51359
51360
51361
51362
51363
51364
51365
51366
51367
51368
51369
51370
51371
51372
51373
51374
51375
51376
51377
51378
51379
51380
51381
51382
51383
51384
51385
51386
51387
51388
51389
51390
51391
51392
51393
51394
51395
51396
51397
51398
51399
51400
51401
51402
51403
51404
51405
51406
51407
51408
51409
51410
51411
51412
51413
51414
51415
51416
51417
51418
51419
51420
51421
51422
51423
51424
51425
51426
51427
51428
51429
51430
51431
51432
51433
51434
51435
51436
51437
51438
51439
51440
51441
51442
51443
51444
51445
51446
51447
51448
51449
51450
51451
51452
51453
51454
51455
51456
51457
51458
51459
51460
51461
51462
51463
51464
51465
51466
51467
51468
51469
51470
51471
51472
51473
51474
51475
51476
51477
51478
51479
51480
51481
51482
51483
51484
51485
51486
51487
51488
51489
51490
51491
51492
51493
51494
51495
51496
51497
51498
51499
51500
51501
51502
51503
51504
51505
51506
51507
51508
51509
51510
51511
51512
51513
51514
51515
51516
51517
51518
51519
51520
51521
51522
51523
51524
51525
51526
51527
51528
51529
51530
51531
51532
51533
51534
51535
51536
51537
51538
51539
51540
51541
51542
51543
51544
51545
51546
51547
51548
51549
51550
51551
51552
51553
51554
51555
51556
51557
51558
51559
51560
51561
51562
51563
51564
51565
51566
51567
51568
51569
51570
51571
51572
51573
51574
51575
51576
51577
51578
51579
51580
51581
51582
51583
51584
51585
51586
51587
51588
51589
51590
51591
51592
51593
51594
51595
51596
51597
51598
51599
51600
51601
51602
51603
51604
51605
51606
51607
51608
51609
51610
51611
51612
51613
51614
51615
51616
51617
51618
51619
51620
51621
51622
51623
51624
51625
51626
51627
51628
51629
51630
51631
51632
51633
51634
51635
51636
51637
51638
51639
51640
51641
51642
51643
51644
51645
51646
51647
51648
51649
51650
51651
51652
51653
51654
51655
51656
51657
51658
51659
51660
51661
51662
51663
51664
51665
51666
51667
51668
51669
51670
51671
51672
51673
51674
51675
51676
51677
51678
51679
51680
51681
51682
51683
51684
51685
51686
51687
51688
51689
51690
51691
51692
51693
51694
51695
51696
51697
51698
51699
51700
51701
51702
51703
51704
51705
51706
51707
51708
51709
51710
51711
51712
51713
51714
51715
51716
51717
51718
51719
51720
51721
51722
51723
51724
51725
51726
51727
51728
51729
51730
51731
51732
51733
51734
51735
51736
51737
51738
51739
51740
51741
51742
51743
51744
51745
51746
51747
51748
51749
51750
51751
51752
51753
51754
51755
51756
51757
51758
51759
51760
51761
51762
51763
51764
51765
51766
51767
51768
51769
51770
51771
51772
51773
51774
51775
51776
51777
51778
51779
51780
51781
51782
51783
51784
51785
51786
51787
51788
51789
51790
51791
51792
51793
51794
51795
51796
51797
51798
51799
51800
51801
51802
51803
51804
51805
51806
51807
51808
51809
51810
51811
51812
51813
51814
51815
51816
51817
51818
51819
51820
51821
51822
51823
51824
51825
51826
51827
51828
51829
51830
51831
51832
51833
51834
51835
51836
51837
51838
51839
51840
51841
51842
51843
51844
51845
51846
51847
51848
51849
51850
51851
51852
51853
51854
51855
51856
51857
51858
51859
51860
51861
51862
51863
51864
51865
51866
51867
51868
51869
51870
51871
51872
51873
51874
51875
51876
51877
51878
51879
51880
51881
51882
51883
51884
51885
51886
51887
51888
51889
51890
51891
51892
51893
51894
51895
51896
51897
51898
51899
51900
51901
51902
51903
51904
51905
51906
51907
51908
51909
51910
51911
51912
51913
51914
51915
51916
51917
51918
51919
51920
51921
51922
51923
51924
51925
51926
51927
51928
51929
51930
51931
51932
51933
51934
51935
51936
51937
51938
51939
51940
51941
51942
51943
51944
51945
51946
51947
51948
51949
51950
51951
51952
51953
51954
51955
51956
51957
51958
51959
51960
51961
51962
51963
51964
51965
51966
51967
51968
51969
51970
51971
51972
51973
51974
51975
51976
51977
51978
51979
51980
51981
51982
51983
51984
51985
51986
51987
51988
51989
51990
51991
51992
51993
51994
51995
51996
51997
51998
51999
52000
52001
52002
52003
52004
52005
52006
52007
52008
52009
52010
52011
52012
52013
52014
52015
52016
52017
52018
52019
52020
52021
52022
52023
52024
52025
52026
52027
52028
52029
52030
52031
52032
52033
52034
52035
52036
52037
52038
52039
52040
52041
52042
52043
52044
52045
52046
52047
52048
52049
52050
52051
52052
52053
52054
52055
52056
52057
52058
52059
52060
52061
52062
52063
52064
52065
52066
52067
52068
52069
52070
52071
52072
52073
52074
52075
52076
52077
52078
52079
52080
52081
52082
52083
52084
52085
52086
52087
52088
52089
52090
52091
52092
52093
52094
52095
52096
52097
52098
52099
52100
52101
52102
52103
52104
52105
52106
52107
52108
52109
52110
52111
52112
52113
52114
52115
52116
52117
52118
52119
52120
52121
52122
52123
52124
52125
52126
52127
52128
52129
52130
52131
52132
52133
52134
52135
52136
52137
52138
52139
52140
52141
52142
52143
52144
52145
52146
52147
52148
52149
52150
52151
52152
52153
52154
52155
52156
52157
52158
52159
52160
52161
52162
52163
52164
52165
52166
52167
52168
52169
52170
52171
52172
52173
52174
52175
52176
52177
52178
52179
52180
52181
52182
52183
52184
52185
52186
52187
52188
52189
52190
52191
52192
52193
52194
52195
52196
52197
52198
52199
52200
52201
52202
52203
52204
52205
52206
52207
52208
52209
52210
52211
52212
52213
52214
52215
52216
52217
52218
52219
52220
52221
52222
52223
52224
52225
52226
52227
52228
52229
52230
52231
52232
52233
52234
52235
52236
52237
52238
52239
52240
52241
52242
52243
52244
52245
52246
52247
52248
52249
52250
52251
52252
52253
52254
52255
52256
52257
52258
52259
52260
52261
52262
52263
52264
52265
52266
52267
52268
52269
52270
52271
52272
52273
52274
52275
52276
52277
52278
52279
52280
52281
52282
52283
52284
52285
52286
52287
52288
52289
52290
52291
52292
52293
52294
52295
52296
52297
52298
52299
52300
52301
52302
52303
52304
52305
52306
52307
52308
52309
52310
52311
52312
52313
52314
52315
52316
52317
52318
52319
52320
52321
52322
52323
52324
52325
52326
52327
52328
52329
52330
52331
52332
52333
52334
52335
52336
52337
52338
52339
52340
52341
52342
52343
52344
52345
52346
52347
52348
52349
52350
52351
52352
52353
52354
52355
52356
52357
52358
52359
52360
52361
52362
52363
52364
52365
52366
52367
52368
52369
52370
52371
52372
52373
52374
52375
52376
52377
52378
52379
52380
52381
52382
52383
52384
52385
52386
52387
52388
52389
52390
52391
52392
52393
52394
52395
52396
52397
52398
52399
52400
52401
52402
52403
52404
52405
52406
52407
52408
52409
52410
52411
52412
52413
52414
52415
52416
52417
52418
52419
52420
52421
52422
52423
52424
52425
52426
52427
52428
52429
52430
52431
52432
52433
52434
52435
52436
52437
52438
52439
52440
52441
52442
52443
52444
52445
52446
52447
52448
52449
52450
52451
52452
52453
52454
52455
52456
52457
52458
52459
52460
52461
52462
52463
52464
52465
52466
52467
52468
52469
52470
52471
52472
52473
52474
52475
52476
52477
52478
52479
52480
52481
52482
52483
52484
52485
52486
52487
52488
52489
52490
52491
52492
52493
52494
52495
52496
52497
52498
52499
52500
52501
52502
52503
52504
52505
52506
52507
52508
52509
52510
52511
52512
52513
52514
52515
52516
52517
52518
52519
52520
52521
52522
52523
52524
52525
52526
52527
52528
52529
52530
52531
52532
52533
52534
52535
52536
52537
52538
52539
52540
52541
52542
52543
52544
52545
52546
52547
52548
52549
52550
52551
52552
52553
52554
52555
52556
52557
52558
52559
52560
52561
52562
52563
52564
52565
52566
52567
52568
52569
52570
52571
52572
52573
52574
52575
52576
52577
52578
52579
52580
52581
52582
52583
52584
52585
52586
52587
52588
52589
52590
52591
52592
52593
52594
52595
52596
52597
52598
52599
52600
52601
52602
52603
52604
52605
52606
52607
52608
52609
52610
52611
52612
52613
52614
52615
52616
52617
52618
52619
52620
52621
52622
52623
52624
52625
52626
52627
52628
52629
52630
52631
52632
52633
52634
52635
52636
52637
52638
52639
52640
52641
52642
52643
52644
52645
52646
52647
52648
52649
52650
52651
52652
52653
52654
52655
52656
52657
52658
52659
52660
52661
52662
52663
52664
52665
52666
52667
52668
52669
52670
52671
52672
52673
52674
52675
52676
52677
52678
52679
52680
52681
52682
52683
52684
52685
52686
52687
52688
52689
52690
52691
52692
52693
52694
52695
52696
52697
52698
52699
52700
52701
52702
52703
52704
52705
52706
52707
52708
52709
52710
52711
52712
52713
52714
52715
52716
52717
52718
52719
52720
52721
52722
52723
52724
52725
52726
52727
52728
52729
52730
52731
52732
52733
52734
52735
52736
52737
52738
52739
52740
52741
52742
52743
52744
52745
52746
52747
52748
52749
52750
52751
52752
52753
52754
52755
52756
52757
52758
52759
52760
52761
52762
52763
52764
52765
52766
52767
52768
52769
52770
52771
52772
52773
52774
52775
52776
52777
52778
52779
52780
52781
52782
52783
52784
52785
52786
52787
52788
52789
52790
52791
52792
52793
52794
52795
52796
52797
52798
52799
52800
52801
52802
52803
52804
52805
52806
52807
52808
52809
52810
52811
52812
52813
52814
52815
52816
52817
52818
52819
52820
52821
52822
52823
52824
52825
52826
52827
52828
52829
52830
52831
52832
52833
52834
52835
52836
52837
52838
52839
52840
52841
52842
52843
52844
52845
52846
52847
52848
52849
52850
52851
52852
52853
52854
52855
52856
52857
52858
52859
52860
52861
52862
52863
52864
52865
52866
52867
52868
52869
52870
52871
52872
52873
52874
52875
52876
52877
52878
52879
52880
52881
52882
52883
52884
52885
52886
52887
52888
52889
52890
52891
52892
52893
52894
52895
52896
52897
52898
52899
52900
52901
52902
52903
52904
52905
52906
52907
52908
52909
52910
52911
52912
52913
52914
52915
52916
52917
52918
52919
52920
52921
52922
52923
52924
52925
52926
52927
52928
52929
52930
52931
52932
52933
52934
52935
52936
52937
52938
52939
52940
52941
52942
52943
52944
52945
52946
52947
52948
52949
52950
52951
52952
52953
52954
52955
52956
52957
52958
52959
52960
52961
52962
52963
52964
52965
52966
52967
52968
52969
52970
52971
52972
52973
52974
52975
52976
52977
52978
52979
52980
52981
52982
52983
52984
52985
52986
52987
52988
52989
52990
52991
52992
52993
52994
52995
52996
52997
52998
52999
53000
53001
53002
53003
53004
53005
53006
53007
53008
53009
53010
53011
53012
53013
53014
53015
53016
53017
53018
53019
53020
53021
53022
53023
53024
53025
53026
53027
53028
53029
53030
53031
53032
53033
53034
53035
53036
53037
53038
53039
53040
53041
53042
53043
53044
53045
53046
53047
53048
53049
53050
53051
53052
53053
53054
53055
53056
53057
53058
53059
53060
53061
53062
53063
53064
53065
53066
53067
53068
53069
53070
53071
53072
53073
53074
53075
53076
53077
53078
53079
53080
53081
53082
53083
53084
53085
53086
53087
53088
53089
53090
53091
53092
53093
53094
53095
53096
53097
53098
53099
53100
53101
53102
53103
53104
53105
53106
53107
53108
53109
53110
53111
53112
53113
53114
53115
53116
53117
53118
53119
53120
53121
53122
53123
53124
53125
53126
53127
53128
53129
53130
53131
53132
53133
53134
53135
53136
53137
53138
53139
53140
53141
53142
53143
53144
53145
53146
53147
53148
53149
53150
53151
53152
53153
53154
53155
53156
53157
53158
53159
53160
53161
53162
53163
53164
53165
53166
53167
53168
53169
53170
53171
53172
53173
53174
53175
53176
53177
53178
53179
53180
53181
53182
53183
53184
53185
53186
53187
53188
53189
53190
53191
53192
53193
53194
53195
53196
53197
53198
53199
53200
53201
53202
53203
53204
53205
53206
53207
53208
53209
53210
53211
53212
53213
53214
53215
53216
53217
53218
53219
53220
53221
53222
53223
53224
53225
53226
53227
53228
53229
53230
53231
53232
53233
53234
53235
53236
53237
53238
53239
53240
53241
53242
53243
53244
53245
53246
53247
53248
53249
53250
53251
53252
53253
53254
53255
53256
53257
53258
53259
53260
53261
53262
53263
53264
53265
53266
53267
53268
53269
53270
53271
53272
53273
53274
53275
53276
53277
53278
53279
53280
53281
53282
53283
53284
53285
53286
53287
53288
53289
53290
53291
53292
53293
53294
53295
53296
53297
53298
53299
53300
53301
53302
53303
53304
53305
53306
53307
53308
53309
53310
53311
53312
53313
53314
53315
53316
53317
53318
53319
53320
53321
53322
53323
53324
53325
53326
53327
53328
53329
53330
53331
53332
53333
53334
53335
53336
53337
53338
53339
53340
53341
53342
53343
53344
53345
53346
53347
53348
53349
53350
53351
53352
53353
53354
53355
53356
53357
53358
53359
53360
53361
53362
53363
53364
53365
53366
53367
53368
53369
53370
53371
53372
53373
53374
53375
53376
53377
53378
53379
53380
53381
53382
53383
53384
53385
53386
53387
53388
53389
53390
53391
53392
53393
53394
53395
53396
53397
53398
53399
53400
53401
53402
53403
53404
53405
53406
53407
53408
53409
53410
53411
53412
53413
53414
53415
53416
53417
53418
53419
53420
53421
53422
53423
53424
53425
53426
53427
53428
53429
53430
53431
53432
53433
53434
53435
53436
53437
53438
53439
53440
53441
53442
53443
53444
53445
53446
53447
53448
53449
53450
53451
53452
53453
53454
53455
53456
53457
53458
53459
53460
53461
53462
53463
53464
53465
53466
53467
53468
53469
53470
53471
53472
53473
53474
53475
53476
53477
53478
53479
53480
53481
53482
53483
53484
53485
53486
53487
53488
53489
53490
53491
53492
53493
53494
53495
53496
53497
53498
53499
53500
53501
53502
53503
53504
53505
53506
53507
53508
53509
53510
53511
53512
53513
53514
53515
53516
53517
53518
53519
53520
53521
53522
53523
53524
53525
53526
53527
53528
53529
53530
53531
53532
53533
53534
53535
53536
53537
53538
53539
53540
53541
53542
53543
53544
53545
53546
53547
53548
53549
53550
53551
53552
53553
53554
53555
53556
53557
53558
53559
53560
53561
53562
53563
53564
53565
53566
53567
53568
53569
53570
53571
53572
53573
53574
53575
53576
53577
53578
53579
53580
53581
53582
53583
53584
53585
53586
53587
53588
53589
53590
53591
53592
53593
53594
53595
53596
53597
53598
53599
53600
53601
53602
53603
53604
53605
53606
53607
53608
53609
53610
53611
53612
53613
53614
53615
53616
53617
53618
53619
53620
53621
53622
53623
53624
53625
53626
53627
53628
53629
53630
53631
53632
53633
53634
53635
53636
53637
53638
53639
53640
53641
53642
53643
53644
53645
53646
53647
53648
53649
53650
53651
53652
53653
53654
53655
53656
53657
53658
53659
53660
53661
53662
53663
53664
53665
53666
53667
53668
53669
53670
53671
53672
53673
53674
53675
53676
53677
53678
53679
53680
53681
53682
53683
53684
53685
53686
53687
53688
53689
53690
53691
53692
53693
53694
53695
53696
53697
53698
53699
53700
53701
53702
53703
53704
53705
53706
53707
53708
53709
53710
53711
53712
53713
53714
53715
53716
53717
53718
53719
53720
53721
53722
53723
53724
53725
53726
53727
53728
53729
53730
53731
53732
53733
53734
53735
53736
53737
53738
53739
53740
53741
53742
53743
53744
53745
53746
53747
53748
53749
53750
53751
53752
53753
53754
53755
53756
53757
53758
53759
53760
53761
53762
53763
53764
53765
53766
53767
53768
53769
53770
53771
53772
53773
53774
53775
53776
53777
53778
53779
53780
53781
53782
53783
53784
53785
53786
53787
53788
53789
53790
53791
53792
53793
53794
53795
53796
53797
53798
53799
53800
53801
53802
53803
53804
53805
53806
53807
53808
53809
53810
53811
53812
53813
53814
53815
53816
53817
53818
53819
53820
53821
53822
53823
53824
53825
53826
53827
53828
53829
53830
53831
53832
53833
53834
53835
53836
53837
53838
53839
53840
53841
53842
53843
53844
53845
53846
53847
53848
53849
53850
53851
53852
53853
53854
53855
53856
53857
53858
53859
53860
53861
53862
53863
53864
53865
53866
53867
53868
53869
53870
53871
53872
53873
53874
53875
53876
53877
53878
53879
53880
53881
53882
53883
53884
53885
53886
53887
53888
53889
53890
53891
53892
53893
53894
53895
53896
53897
53898
53899
53900
53901
53902
53903
53904
53905
53906
53907
53908
53909
53910
53911
53912
53913
53914
53915
53916
53917
53918
53919
53920
53921
53922
53923
53924
53925
53926
53927
53928
53929
53930
53931
53932
53933
53934
53935
53936
53937
53938
53939
53940
53941
53942
53943
53944
53945
53946
53947
53948
53949
53950
53951
53952
53953
53954
53955
53956
53957
53958
53959
53960
53961
53962
53963
53964
53965
53966
53967
53968
53969
53970
53971
53972
53973
53974
53975
53976
53977
53978
53979
53980
53981
53982
53983
53984
53985
53986
53987
53988
53989
53990
53991
53992
53993
53994
53995
53996
53997
53998
53999
54000
54001
54002
54003
54004
54005
54006
54007
54008
54009
54010
54011
54012
54013
54014
54015
54016
54017
54018
54019
54020
54021
54022
54023
54024
54025
54026
54027
54028
54029
54030
54031
54032
54033
54034
54035
54036
54037
54038
54039
54040
54041
54042
54043
54044
54045
54046
54047
54048
54049
54050
54051
54052
54053
54054
54055
54056
54057
54058
54059
54060
54061
54062
54063
54064
54065
54066
54067
54068
54069
54070
54071
54072
54073
54074
54075
54076
54077
54078
54079
54080
54081
54082
54083
54084
54085
54086
54087
54088
54089
54090
54091
54092
54093
54094
54095
54096
54097
54098
54099
54100
54101
54102
54103
54104
54105
54106
54107
54108
54109
54110
54111
54112
54113
54114
54115
54116
54117
54118
54119
54120
54121
54122
54123
54124
54125
54126
54127
54128
54129
54130
54131
54132
54133
54134
54135
54136
54137
54138
54139
54140
54141
54142
54143
54144
54145
54146
54147
54148
54149
54150
54151
54152
54153
54154
54155
54156
54157
54158
54159
54160
54161
54162
54163
54164
54165
54166
54167
54168
54169
54170
54171
54172
54173
54174
54175
54176
54177
54178
54179
54180
54181
54182
54183
54184
54185
54186
54187
54188
54189
54190
54191
54192
54193
54194
54195
54196
54197
54198
54199
54200
54201
54202
54203
54204
54205
54206
54207
54208
54209
54210
54211
54212
54213
54214
54215
54216
54217
54218
54219
54220
54221
54222
54223
54224
54225
54226
54227
54228
54229
54230
54231
54232
54233
54234
54235
54236
54237
54238
54239
54240
54241
54242
54243
54244
54245
54246
54247
54248
54249
54250
54251
54252
54253
54254
54255
54256
54257
54258
54259
54260
54261
54262
54263
54264
54265
54266
54267
54268
54269
54270
54271
54272
54273
54274
54275
54276
54277
54278
54279
54280
54281
54282
54283
54284
54285
54286
54287
54288
54289
54290
54291
54292
54293
54294
54295
54296
54297
54298
54299
54300
54301
54302
54303
54304
54305
54306
54307
54308
54309
54310
54311
54312
54313
54314
54315
54316
54317
54318
54319
54320
54321
54322
54323
54324
54325
54326
54327
54328
54329
54330
54331
54332
54333
54334
54335
54336
54337
54338
54339
54340
54341
54342
54343
54344
54345
54346
54347
54348
54349
54350
54351
54352
54353
54354
54355
54356
54357
54358
54359
54360
54361
54362
54363
54364
54365
54366
54367
54368
54369
54370
54371
54372
54373
54374
54375
54376
54377
54378
54379
54380
54381
54382
54383
54384
54385
54386
54387
54388
54389
54390
54391
54392
54393
54394
54395
54396
54397
54398
54399
54400
54401
54402
54403
54404
54405
54406
54407
54408
54409
54410
54411
54412
54413
54414
54415
54416
54417
54418
54419
54420
54421
54422
54423
54424
54425
54426
54427
54428
54429
54430
54431
54432
54433
54434
54435
54436
54437
54438
54439
54440
54441
54442
54443
54444
54445
54446
54447
54448
54449
54450
54451
54452
54453
54454
54455
54456
54457
54458
54459
54460
54461
54462
54463
54464
54465
54466
54467
54468
54469
54470
54471
54472
54473
54474
54475
54476
54477
54478
54479
54480
54481
54482
54483
54484
54485
54486
54487
54488
54489
54490
54491
54492
54493
54494
54495
54496
54497
54498
54499
54500
54501
54502
54503
54504
54505
54506
54507
54508
54509
54510
54511
54512
54513
54514
54515
54516
54517
54518
54519
54520
54521
54522
54523
54524
54525
54526
54527
54528
54529
54530
54531
54532
54533
54534
54535
54536
54537
54538
54539
54540
54541
54542
54543
54544
54545
54546
54547
54548
54549
54550
54551
54552
54553
54554
54555
54556
54557
54558
54559
54560
54561
54562
54563
54564
54565
54566
54567
54568
54569
54570
54571
54572
54573
54574
54575
54576
54577
54578
54579
54580
54581
54582
54583
54584
54585
54586
54587
54588
54589
54590
54591
54592
54593
54594
54595
54596
54597
54598
54599
54600
54601
54602
54603
54604
54605
54606
54607
54608
54609
54610
54611
54612
54613
54614
54615
54616
54617
54618
54619
54620
54621
54622
54623
54624
54625
54626
54627
54628
54629
54630
54631
54632
54633
54634
54635
54636
54637
54638
54639
54640
54641
54642
54643
54644
54645
54646
54647
54648
54649
54650
54651
54652
54653
54654
54655
54656
54657
54658
54659
54660
54661
54662
54663
54664
54665
54666
54667
54668
54669
54670
54671
54672
54673
54674
54675
54676
54677
54678
54679
54680
54681
54682
54683
54684
54685
54686
54687
54688
54689
54690
54691
54692
54693
54694
54695
54696
54697
54698
54699
54700
54701
54702
54703
54704
54705
54706
54707
54708
54709
54710
54711
54712
54713
54714
54715
54716
54717
54718
54719
54720
54721
54722
54723
54724
54725
54726
54727
54728
54729
54730
54731
54732
54733
54734
54735
54736
54737
54738
54739
54740
54741
54742
54743
54744
54745
54746
54747
54748
54749
54750
54751
54752
54753
54754
54755
54756
54757
54758
54759
54760
54761
54762
54763
54764
54765
54766
54767
54768
54769
54770
54771
54772
54773
54774
54775
54776
54777
54778
54779
54780
54781
54782
54783
54784
54785
54786
54787
54788
54789
54790
54791
54792
54793
54794
54795
54796
54797
54798
54799
54800
54801
54802
54803
54804
54805
54806
54807
54808
54809
54810
54811
54812
54813
54814
54815
54816
54817
54818
54819
54820
54821
54822
54823
54824
54825
54826
54827
54828
54829
54830
54831
54832
54833
54834
54835
54836
54837
54838
54839
54840
54841
54842
54843
54844
54845
54846
54847
54848
54849
54850
54851
54852
54853
54854
54855
54856
54857
54858
54859
54860
54861
54862
54863
54864
54865
54866
54867
54868
54869
54870
54871
54872
54873
54874
54875
54876
54877
54878
54879
54880
54881
54882
54883
54884
54885
54886
54887
54888
54889
54890
54891
54892
54893
54894
54895
54896
54897
54898
54899
54900
54901
54902
54903
54904
54905
54906
54907
54908
54909
54910
54911
54912
54913
54914
54915
54916
54917
54918
54919
54920
54921
54922
54923
54924
54925
54926
54927
54928
54929
54930
54931
54932
54933
54934
54935
54936
54937
54938
54939
54940
54941
54942
54943
54944
54945
54946
54947
54948
54949
54950
54951
54952
54953
54954
54955
54956
54957
54958
54959
54960
54961
54962
54963
54964
54965
54966
54967
54968
54969
54970
54971
54972
54973
54974
54975
54976
54977
54978
54979
54980
54981
54982
54983
54984
54985
54986
54987
54988
54989
54990
54991
54992
54993
54994
54995
54996
54997
54998
54999
55000
55001
55002
55003
55004
55005
55006
55007
55008
55009
55010
55011
55012
55013
55014
55015
55016
55017
55018
55019
55020
55021
55022
55023
55024
55025
55026
55027
55028
55029
55030
55031
55032
55033
55034
55035
55036
55037
55038
55039
55040
55041
55042
55043
55044
55045
55046
55047
55048
55049
55050
55051
55052
55053
55054
55055
55056
55057
55058
55059
55060
55061
55062
55063
55064
55065
55066
55067
55068
55069
55070
55071
55072
55073
55074
55075
55076
55077
55078
55079
55080
55081
55082
55083
55084
55085
55086
55087
55088
55089
55090
55091
55092
55093
55094
55095
55096
55097
55098
55099
55100
55101
55102
55103
55104
55105
55106
55107
55108
55109
55110
55111
55112
55113
55114
55115
55116
55117
55118
55119
55120
55121
55122
55123
55124
55125
55126
55127
55128
55129
55130
55131
55132
55133
55134
55135
55136
55137
55138
55139
55140
55141
55142
55143
55144
55145
55146
55147
55148
55149
55150
55151
55152
55153
55154
55155
55156
55157
55158
55159
55160
55161
55162
55163
55164
55165
55166
55167
55168
55169
55170
55171
55172
55173
55174
55175
55176
55177
55178
55179
55180
55181
55182
55183
55184
55185
55186
55187
55188
55189
55190
55191
55192
55193
55194
55195
55196
55197
55198
55199
55200
55201
55202
55203
55204
55205
55206
55207
55208
55209
55210
55211
55212
55213
55214
55215
55216
55217
55218
55219
55220
55221
55222
55223
55224
55225
55226
55227
55228
55229
55230
55231
55232
55233
55234
55235
55236
55237
55238
55239
55240
55241
55242
55243
55244
55245
55246
55247
55248
55249
55250
55251
55252
55253
55254
55255
55256
55257
55258
55259
55260
55261
55262
55263
55264
55265
55266
55267
55268
55269
55270
55271
55272
55273
55274
55275
55276
55277
55278
55279
55280
55281
55282
55283
55284
55285
55286
55287
55288
55289
55290
55291
55292
55293
55294
55295
55296
55297
55298
55299
55300
55301
55302
55303
55304
55305
55306
55307
55308
55309
55310
55311
55312
55313
55314
55315
55316
55317
55318
55319
55320
55321
55322
55323
55324
55325
55326
55327
55328
55329
55330
55331
55332
55333
55334
55335
55336
55337
55338
55339
55340
55341
55342
55343
55344
55345
55346
55347
55348
55349
55350
55351
55352
55353
55354
55355
55356
55357
55358
55359
55360
55361
55362
55363
55364
55365
55366
55367
55368
55369
55370
55371
55372
55373
55374
55375
55376
55377
55378
55379
55380
55381
55382
55383
55384
55385
55386
55387
55388
55389
55390
55391
55392
55393
55394
55395
55396
55397
55398
55399
55400
55401
55402
55403
55404
55405
55406
55407
55408
55409
55410
55411
55412
55413
55414
55415
55416
55417
55418
55419
55420
55421
55422
55423
55424
55425
55426
55427
55428
55429
55430
55431
55432
55433
55434
55435
55436
55437
55438
55439
55440
55441
55442
55443
55444
55445
55446
55447
55448
55449
55450
55451
55452
55453
55454
55455
55456
55457
55458
55459
55460
55461
55462
55463
55464
55465
55466
55467
55468
55469
55470
55471
55472
55473
55474
55475
55476
55477
55478
55479
55480
55481
55482
55483
55484
55485
55486
55487
55488
55489
55490
55491
55492
55493
55494
55495
55496
55497
55498
55499
55500
55501
55502
55503
55504
55505
55506
55507
55508
55509
55510
55511
55512
55513
55514
55515
55516
55517
55518
55519
55520
55521
55522
55523
55524
55525
55526
55527
55528
55529
55530
55531
55532
55533
55534
55535
55536
55537
55538
55539
55540
55541
55542
55543
55544
55545
55546
55547
55548
55549
55550
55551
55552
55553
55554
55555
55556
55557
55558
55559
55560
55561
55562
55563
55564
55565
55566
55567
55568
55569
55570
55571
55572
55573
55574
55575
55576
55577
55578
55579
55580
55581
55582
55583
55584
55585
55586
55587
55588
55589
55590
55591
55592
55593
55594
55595
55596
55597
55598
55599
55600
55601
55602
55603
55604
55605
55606
55607
55608
55609
55610
55611
55612
55613
55614
55615
55616
55617
55618
55619
55620
55621
55622
55623
55624
55625
55626
55627
55628
55629
55630
55631
55632
55633
55634
55635
55636
55637
55638
55639
55640
55641
55642
55643
55644
55645
55646
55647
55648
55649
55650
55651
55652
55653
55654
55655
55656
55657
55658
55659
55660
55661
55662
55663
55664
55665
55666
55667
55668
55669
55670
55671
55672
55673
55674
55675
55676
55677
55678
55679
55680
55681
55682
55683
55684
55685
55686
55687
55688
55689
55690
55691
55692
55693
55694
55695
55696
55697
55698
55699
55700
55701
55702
55703
55704
55705
55706
55707
55708
55709
55710
55711
55712
55713
55714
55715
55716
55717
55718
55719
55720
55721
55722
55723
55724
55725
55726
55727
55728
55729
55730
55731
55732
55733
55734
55735
55736
55737
55738
55739
55740
55741
55742
55743
55744
55745
55746
55747
55748
55749
55750
55751
55752
55753
55754
55755
55756
55757
55758
55759
55760
55761
55762
55763
55764
55765
55766
55767
55768
55769
55770
55771
55772
55773
55774
55775
55776
55777
55778
55779
55780
55781
55782
55783
55784
55785
55786
55787
55788
55789
55790
55791
55792
55793
55794
55795
55796
55797
55798
55799
55800
55801
55802
55803
55804
55805
55806
55807
55808
55809
55810
55811
55812
55813
55814
55815
55816
55817
55818
55819
55820
55821
55822
55823
55824
55825
55826
55827
55828
55829
55830
55831
55832
55833
55834
55835
55836
55837
55838
55839
55840
55841
55842
55843
55844
55845
55846
55847
55848
55849
55850
55851
55852
55853
55854
55855
55856
55857
55858
55859
55860
55861
55862
55863
55864
55865
55866
55867
55868
55869
55870
55871
55872
55873
55874
55875
55876
55877
55878
55879
55880
55881
55882
55883
55884
55885
55886
55887
55888
55889
55890
55891
55892
55893
55894
55895
55896
55897
55898
55899
55900
55901
55902
55903
55904
55905
55906
55907
55908
55909
55910
55911
55912
55913
55914
55915
55916
55917
55918
55919
55920
55921
55922
55923
55924
55925
55926
55927
55928
55929
55930
55931
55932
55933
55934
55935
55936
55937
55938
55939
55940
55941
55942
55943
55944
55945
55946
55947
55948
55949
55950
55951
55952
55953
55954
55955
55956
55957
55958
55959
55960
55961
55962
55963
55964
55965
55966
55967
55968
55969
55970
55971
55972
55973
55974
55975
55976
55977
55978
55979
55980
55981
55982
55983
55984
55985
55986
55987
55988
55989
55990
55991
55992
55993
55994
55995
55996
55997
55998
55999
56000
56001
56002
56003
56004
56005
56006
56007
56008
56009
56010
56011
56012
56013
56014
56015
56016
56017
56018
56019
56020
56021
56022
56023
56024
56025
56026
56027
56028
56029
56030
56031
56032
56033
56034
56035
56036
56037
56038
56039
56040
56041
56042
56043
56044
56045
56046
56047
56048
56049
56050
56051
56052
56053
56054
56055
56056
56057
56058
56059
56060
56061
56062
56063
56064
56065
56066
56067
56068
56069
56070
56071
56072
56073
56074
56075
56076
56077
56078
56079
56080
56081
56082
56083
56084
56085
56086
56087
56088
56089
56090
56091
56092
56093
56094
56095
56096
56097
56098
56099
56100
56101
56102
56103
56104
56105
56106
56107
56108
56109
56110
56111
56112
56113
56114
56115
56116
56117
56118
56119
56120
56121
56122
56123
56124
56125
56126
56127
56128
56129
56130
56131
56132
56133
56134
56135
56136
56137
56138
56139
56140
56141
56142
56143
56144
56145
56146
56147
56148
56149
56150
56151
56152
56153
56154
56155
56156
56157
56158
56159
56160
56161
56162
56163
56164
56165
56166
56167
56168
56169
56170
56171
56172
56173
56174
56175
56176
56177
56178
56179
56180
56181
56182
56183
56184
56185
56186
56187
56188
56189
56190
56191
56192
56193
56194
56195
56196
56197
56198
56199
56200
56201
56202
56203
56204
56205
56206
56207
56208
56209
56210
56211
56212
56213
56214
56215
56216
56217
56218
56219
56220
56221
56222
56223
56224
56225
56226
56227
56228
56229
56230
56231
56232
56233
56234
56235
56236
56237
56238
56239
56240
56241
56242
56243
56244
56245
56246
56247
56248
56249
56250
56251
56252
56253
56254
56255
56256
56257
56258
56259
56260
56261
56262
56263
56264
56265
56266
56267
56268
56269
56270
56271
56272
56273
56274
56275
56276
56277
56278
56279
56280
56281
56282
56283
56284
56285
56286
56287
56288
56289
56290
56291
56292
56293
56294
56295
56296
56297
56298
56299
56300
56301
56302
56303
56304
56305
56306
56307
56308
56309
56310
56311
56312
56313
56314
56315
56316
56317
56318
56319
56320
56321
56322
56323
56324
56325
56326
56327
56328
56329
56330
56331
56332
56333
56334
56335
56336
56337
56338
56339
56340
56341
56342
56343
56344
56345
56346
56347
56348
56349
56350
56351
56352
56353
56354
56355
56356
56357
56358
56359
56360
56361
56362
56363
56364
56365
56366
56367
56368
56369
56370
56371
56372
56373
56374
56375
56376
56377
56378
56379
56380
56381
56382
56383
56384
56385
56386
56387
56388
56389
56390
56391
56392
56393
56394
56395
56396
56397
56398
56399
56400
56401
56402
56403
56404
56405
56406
56407
56408
56409
56410
56411
56412
56413
56414
56415
56416
56417
56418
56419
56420
56421
56422
56423
56424
56425
56426
56427
56428
56429
56430
56431
56432
56433
56434
56435
56436
56437
56438
56439
56440
56441
56442
56443
56444
56445
56446
56447
56448
56449
56450
56451
56452
56453
56454
56455
56456
56457
56458
56459
56460
56461
56462
56463
56464
56465
56466
56467
56468
56469
56470
56471
56472
56473
56474
56475
56476
56477
56478
56479
56480
56481
56482
56483
56484
56485
56486
56487
56488
56489
56490
56491
56492
56493
56494
56495
56496
56497
56498
56499
56500
56501
56502
56503
56504
56505
56506
56507
56508
56509
56510
56511
56512
56513
56514
56515
56516
56517
56518
56519
56520
56521
56522
56523
56524
56525
56526
56527
56528
56529
56530
56531
56532
56533
56534
56535
56536
56537
56538
56539
56540
56541
56542
56543
56544
56545
56546
56547
56548
56549
56550
56551
56552
56553
56554
56555
56556
56557
56558
56559
56560
56561
56562
56563
56564
56565
56566
56567
56568
56569
56570
56571
56572
56573
56574
56575
56576
56577
56578
56579
56580
56581
56582
56583
56584
56585
56586
56587
56588
56589
56590
56591
56592
56593
56594
56595
56596
56597
56598
56599
56600
56601
56602
56603
56604
56605
56606
56607
56608
56609
56610
56611
56612
56613
56614
56615
56616
56617
56618
56619
56620
56621
56622
56623
56624
56625
56626
56627
56628
56629
56630
56631
56632
56633
56634
56635
56636
56637
56638
56639
56640
56641
56642
56643
56644
56645
56646
56647
56648
56649
56650
56651
56652
56653
56654
56655
56656
56657
56658
56659
56660
56661
56662
56663
56664
56665
56666
56667
56668
56669
56670
56671
56672
56673
56674
56675
56676
56677
56678
56679
56680
56681
56682
56683
56684
56685
56686
56687
56688
56689
56690
56691
56692
56693
56694
56695
56696
56697
56698
56699
56700
56701
56702
56703
56704
56705
56706
56707
56708
56709
56710
56711
56712
56713
56714
56715
56716
56717
56718
56719
56720
56721
56722
56723
56724
56725
56726
56727
56728
56729
56730
56731
56732
56733
56734
56735
56736
56737
56738
56739
56740
56741
56742
56743
56744
56745
56746
56747
56748
56749
56750
56751
56752
56753
56754
56755
56756
56757
56758
56759
56760
56761
56762
56763
56764
56765
56766
56767
56768
56769
56770
56771
56772
56773
56774
56775
56776
56777
56778
56779
56780
56781
56782
56783
56784
56785
56786
56787
56788
56789
56790
56791
56792
56793
56794
56795
56796
56797
56798
56799
56800
56801
56802
56803
56804
56805
56806
56807
56808
56809
56810
56811
56812
56813
56814
56815
56816
56817
56818
56819
56820
56821
56822
56823
56824
56825
56826
56827
56828
56829
56830
56831
56832
56833
56834
56835
56836
56837
56838
56839
56840
56841
56842
56843
56844
56845
56846
56847
56848
56849
56850
56851
56852
56853
56854
56855
56856
56857
56858
56859
56860
56861
56862
56863
56864
56865
56866
56867
56868
56869
56870
56871
56872
56873
56874
56875
56876
56877
56878
56879
56880
56881
56882
56883
56884
56885
56886
56887
56888
56889
56890
56891
56892
56893
56894
56895
56896
56897
56898
56899
56900
56901
56902
56903
56904
56905
56906
56907
56908
56909
56910
56911
56912
56913
56914
56915
56916
56917
56918
56919
56920
56921
56922
56923
56924
56925
56926
56927
56928
56929
56930
56931
56932
56933
56934
56935
56936
56937
56938
56939
56940
56941
56942
56943
56944
56945
56946
56947
56948
56949
56950
56951
56952
56953
56954
56955
56956
56957
56958
56959
56960
56961
56962
56963
56964
56965
56966
56967
56968
56969
56970
56971
56972
56973
56974
56975
56976
56977
56978
56979
56980
56981
56982
56983
56984
56985
56986
56987
56988
56989
56990
56991
56992
56993
56994
56995
56996
56997
56998
56999
57000
57001
57002
57003
57004
57005
57006
57007
57008
57009
57010
57011
57012
57013
57014
57015
57016
57017
57018
57019
57020
57021
57022
57023
57024
57025
57026
57027
57028
57029
57030
57031
57032
57033
57034
57035
57036
57037
57038
57039
57040
57041
57042
57043
57044
57045
57046
57047
57048
57049
57050
57051
57052
57053
57054
57055
57056
57057
57058
57059
57060
57061
57062
57063
57064
57065
57066
57067
57068
57069
57070
57071
57072
57073
57074
57075
57076
57077
57078
57079
57080
57081
57082
57083
57084
57085
57086
57087
57088
57089
57090
57091
57092
57093
57094
57095
57096
57097
57098
57099
57100
57101
57102
57103
57104
57105
57106
57107
57108
57109
57110
57111
57112
57113
57114
57115
57116
57117
57118
57119
57120
57121
57122
57123
57124
57125
57126
57127
57128
57129
57130
57131
57132
57133
57134
57135
57136
57137
57138
57139
57140
57141
57142
57143
57144
57145
57146
57147
57148
57149
57150
57151
57152
57153
57154
57155
57156
57157
57158
57159
57160
57161
57162
57163
57164
57165
57166
57167
57168
57169
57170
57171
57172
57173
57174
57175
57176
57177
57178
57179
57180
57181
57182
57183
57184
57185
57186
57187
57188
57189
57190
57191
57192
57193
57194
57195
57196
57197
57198
57199
57200
57201
57202
57203
57204
57205
57206
57207
57208
57209
57210
57211
57212
57213
57214
57215
57216
57217
57218
57219
57220
57221
57222
57223
57224
57225
57226
57227
57228
57229
57230
57231
57232
57233
57234
57235
57236
57237
57238
57239
57240
57241
57242
57243
57244
57245
57246
57247
57248
57249
57250
57251
57252
57253
57254
57255
57256
57257
57258
57259
57260
57261
57262
57263
57264
57265
57266
57267
57268
57269
57270
57271
57272
57273
57274
57275
57276
57277
57278
57279
57280
57281
57282
57283
57284
57285
57286
57287
57288
57289
57290
57291
57292
57293
57294
57295
57296
57297
57298
57299
57300
57301
57302
57303
57304
57305
57306
57307
57308
57309
57310
57311
57312
57313
57314
57315
57316
57317
57318
57319
57320
57321
57322
57323
57324
57325
57326
57327
57328
57329
57330
57331
57332
57333
57334
57335
57336
57337
57338
57339
57340
57341
57342
57343
57344
57345
57346
57347
57348
57349
57350
57351
57352
57353
57354
57355
57356
57357
57358
57359
57360
57361
57362
57363
57364
57365
57366
57367
57368
57369
57370
57371
57372
57373
57374
57375
57376
57377
57378
57379
57380
57381
57382
57383
57384
57385
57386
57387
57388
57389
57390
57391
57392
57393
57394
57395
57396
57397
57398
57399
57400
57401
57402
57403
57404
57405
57406
57407
57408
57409
57410
57411
57412
57413
57414
57415
57416
57417
57418
57419
57420
57421
57422
57423
57424
57425
57426
57427
57428
57429
57430
57431
57432
57433
57434
57435
57436
57437
57438
57439
57440
57441
57442
57443
57444
57445
57446
57447
57448
57449
57450
57451
57452
57453
57454
57455
57456
57457
57458
57459
57460
57461
57462
57463
57464
57465
57466
57467
57468
57469
57470
57471
57472
57473
57474
57475
57476
57477
57478
57479
57480
57481
57482
57483
57484
57485
57486
57487
57488
57489
57490
57491
57492
57493
57494
57495
57496
57497
57498
57499
57500
57501
57502
57503
57504
57505
57506
57507
57508
57509
57510
57511
57512
57513
57514
57515
57516
57517
57518
57519
57520
57521
57522
57523
57524
57525
57526
57527
57528
57529
57530
57531
57532
57533
57534
57535
57536
57537
57538
57539
57540
57541
57542
57543
57544
57545
57546
57547
57548
57549
57550
57551
57552
57553
57554
57555
57556
57557
57558
57559
57560
57561
57562
57563
57564
57565
57566
57567
57568
57569
57570
57571
57572
57573
57574
57575
57576
57577
57578
57579
57580
57581
57582
57583
57584
57585
57586
57587
57588
57589
57590
57591
57592
57593
57594
57595
57596
57597
57598
57599
57600
57601
57602
57603
57604
57605
57606
57607
57608
57609
57610
57611
57612
57613
57614
57615
57616
57617
57618
57619
57620
57621
57622
57623
57624
57625
57626
57627
57628
57629
57630
57631
57632
57633
57634
57635
57636
57637
57638
57639
57640
57641
57642
57643
57644
57645
57646
57647
57648
57649
57650
57651
57652
57653
57654
57655
57656
57657
57658
57659
57660
57661
57662
57663
57664
57665
57666
57667
57668
57669
57670
57671
57672
57673
57674
57675
57676
57677
57678
57679
57680
57681
57682
57683
57684
57685
57686
57687
57688
57689
57690
57691
57692
57693
57694
57695
57696
57697
57698
57699
57700
57701
57702
57703
57704
57705
57706
57707
57708
57709
57710
57711
57712
57713
57714
57715
57716
57717
57718
57719
57720
57721
57722
57723
57724
57725
57726
57727
57728
57729
57730
57731
57732
57733
57734
57735
57736
57737
57738
57739
57740
57741
57742
57743
57744
57745
57746
57747
57748
57749
57750
57751
57752
57753
57754
57755
57756
57757
57758
57759
57760
57761
57762
57763
57764
57765
57766
57767
57768
57769
57770
57771
57772
57773
57774
57775
57776
57777
57778
57779
57780
57781
57782
57783
57784
57785
57786
57787
57788
57789
57790
57791
57792
57793
57794
57795
57796
57797
57798
57799
57800
57801
57802
57803
57804
57805
57806
57807
57808
57809
57810
57811
57812
57813
57814
57815
57816
57817
57818
57819
57820
57821
57822
57823
57824
57825
57826
57827
57828
57829
57830
57831
57832
57833
57834
57835
57836
57837
57838
57839
57840
57841
57842
57843
57844
57845
57846
57847
57848
57849
57850
57851
57852
57853
57854
57855
57856
57857
57858
57859
57860
57861
57862
57863
57864
57865
57866
57867
57868
57869
57870
57871
57872
57873
57874
57875
57876
57877
57878
57879
57880
57881
57882
57883
57884
57885
57886
57887
57888
57889
57890
57891
57892
57893
57894
57895
57896
57897
57898
57899
57900
57901
57902
57903
57904
57905
57906
57907
57908
57909
57910
57911
57912
57913
57914
57915
57916
57917
57918
57919
57920
57921
57922
57923
57924
57925
57926
57927
57928
57929
57930
57931
57932
57933
57934
57935
57936
57937
57938
57939
57940
57941
57942
57943
57944
57945
57946
57947
57948
57949
57950
57951
57952
57953
57954
57955
57956
57957
57958
57959
57960
57961
57962
57963
57964
57965
57966
57967
57968
57969
57970
57971
57972
57973
57974
57975
57976
57977
57978
57979
57980
57981
57982
57983
57984
57985
57986
57987
57988
57989
57990
57991
57992
57993
57994
57995
57996
57997
57998
57999
58000
58001
58002
58003
58004
58005
58006
58007
58008
58009
58010
58011
58012
58013
58014
58015
58016
58017
58018
58019
58020
58021
58022
58023
58024
58025
58026
58027
58028
58029
58030
58031
58032
58033
58034
58035
58036
58037
58038
58039
58040
58041
58042
58043
58044
58045
58046
58047
58048
58049
58050
58051
58052
58053
58054
58055
58056
58057
58058
58059
58060
58061
58062
58063
58064
58065
58066
58067
58068
58069
58070
58071
58072
58073
58074
58075
58076
58077
58078
58079
58080
58081
58082
58083
58084
58085
58086
58087
58088
58089
58090
58091
58092
58093
58094
58095
58096
58097
58098
58099
58100
58101
58102
58103
58104
58105
58106
58107
58108
58109
58110
58111
58112
58113
58114
58115
58116
58117
58118
58119
58120
58121
58122
58123
58124
58125
58126
58127
58128
58129
58130
58131
58132
58133
58134
58135
58136
58137
58138
58139
58140
58141
58142
58143
58144
58145
58146
58147
58148
58149
58150
58151
58152
58153
58154
58155
58156
58157
58158
58159
58160
58161
58162
58163
58164
58165
58166
58167
58168
58169
58170
58171
58172
58173
58174
58175
58176
58177
58178
58179
58180
58181
58182
58183
58184
58185
58186
58187
58188
58189
58190
58191
58192
58193
58194
58195
58196
58197
58198
58199
58200
58201
58202
58203
58204
58205
58206
58207
58208
58209
58210
58211
58212
58213
58214
58215
58216
58217
58218
58219
58220
58221
58222
58223
58224
58225
58226
58227
58228
58229
58230
58231
58232
58233
58234
58235
58236
58237
58238
58239
58240
58241
58242
58243
58244
58245
58246
58247
58248
58249
58250
58251
58252
58253
58254
58255
58256
58257
58258
58259
58260
58261
58262
58263
58264
58265
58266
58267
58268
58269
58270
58271
58272
58273
58274
58275
58276
58277
58278
58279
58280
58281
58282
58283
58284
58285
58286
58287
58288
58289
58290
58291
58292
58293
58294
58295
58296
58297
58298
58299
58300
58301
58302
58303
58304
58305
58306
58307
58308
58309
58310
58311
58312
58313
58314
58315
58316
58317
58318
58319
58320
58321
58322
58323
58324
58325
58326
58327
58328
58329
58330
58331
58332
58333
58334
58335
58336
58337
58338
58339
58340
58341
58342
58343
58344
58345
58346
58347
58348
58349
58350
58351
58352
58353
58354
58355
58356
58357
58358
58359
58360
58361
58362
58363
58364
58365
58366
58367
58368
58369
58370
58371
58372
58373
58374
58375
58376
58377
58378
58379
58380
58381
58382
58383
58384
58385
58386
58387
58388
58389
58390
58391
58392
58393
58394
58395
58396
58397
58398
58399
58400
58401
58402
58403
58404
58405
58406
58407
58408
58409
58410
58411
58412
58413
58414
58415
58416
58417
58418
58419
58420
58421
58422
58423
58424
58425
58426
58427
58428
58429
58430
58431
58432
58433
58434
58435
58436
58437
58438
58439
58440
58441
58442
58443
58444
58445
58446
58447
58448
58449
58450
58451
58452
58453
58454
58455
58456
58457
58458
58459
58460
58461
58462
58463
58464
58465
58466
58467
58468
58469
58470
58471
58472
58473
58474
58475
58476
58477
58478
58479
58480
58481
58482
58483
58484
58485
58486
58487
58488
58489
58490
58491
58492
58493
58494
58495
58496
58497
58498
58499
58500
58501
58502
58503
58504
58505
58506
58507
58508
58509
58510
58511
58512
58513
58514
58515
58516
58517
58518
58519
58520
58521
58522
58523
58524
58525
58526
58527
58528
58529
58530
58531
58532
58533
58534
58535
58536
58537
58538
58539
58540
58541
58542
58543
58544
58545
58546
58547
58548
58549
58550
58551
58552
58553
58554
58555
58556
58557
58558
58559
58560
58561
58562
58563
58564
58565
58566
58567
58568
58569
58570
58571
58572
58573
58574
58575
58576
58577
58578
58579
58580
58581
58582
58583
58584
58585
58586
58587
58588
58589
58590
58591
58592
58593
58594
58595
58596
58597
58598
58599
58600
58601
58602
58603
58604
58605
58606
58607
58608
58609
58610
58611
58612
58613
58614
58615
58616
58617
58618
58619
58620
58621
58622
58623
58624
58625
58626
58627
58628
58629
58630
58631
58632
58633
58634
58635
58636
58637
58638
58639
58640
58641
58642
58643
58644
58645
58646
58647
58648
58649
58650
58651
58652
58653
58654
58655
58656
58657
58658
58659
58660
58661
58662
58663
58664
58665
58666
58667
58668
58669
58670
58671
58672
58673
58674
58675
58676
58677
58678
58679
58680
58681
58682
58683
58684
58685
58686
58687
58688
58689
58690
58691
58692
58693
58694
58695
58696
58697
58698
58699
58700
58701
58702
58703
58704
58705
58706
58707
58708
58709
58710
58711
58712
58713
58714
58715
58716
58717
58718
58719
58720
58721
58722
58723
58724
58725
58726
58727
58728
58729
58730
58731
58732
58733
58734
58735
58736
58737
58738
58739
58740
58741
58742
58743
58744
58745
58746
58747
58748
58749
58750
58751
58752
58753
58754
58755
58756
58757
58758
58759
58760
58761
58762
58763
58764
58765
58766
58767
58768
58769
58770
58771
58772
58773
58774
58775
58776
58777
58778
58779
58780
58781
58782
58783
58784
58785
58786
58787
58788
58789
58790
58791
58792
58793
58794
58795
58796
58797
58798
58799
58800
58801
58802
58803
58804
58805
58806
58807
58808
58809
58810
58811
58812
58813
58814
58815
58816
58817
58818
58819
58820
58821
58822
58823
58824
58825
58826
58827
58828
58829
58830
58831
58832
58833
58834
58835
58836
58837
58838
58839
58840
58841
58842
58843
58844
58845
58846
58847
58848
58849
58850
58851
58852
58853
58854
58855
58856
58857
58858
58859
58860
58861
58862
58863
58864
58865
58866
58867
58868
58869
58870
58871
58872
58873
58874
58875
58876
58877
58878
58879
58880
58881
58882
58883
58884
58885
58886
58887
58888
58889
58890
58891
58892
58893
58894
58895
58896
58897
58898
58899
58900
58901
58902
58903
58904
58905
58906
58907
58908
58909
58910
58911
58912
58913
58914
58915
58916
58917
58918
58919
58920
58921
58922
58923
58924
58925
58926
58927
58928
58929
58930
58931
58932
58933
58934
58935
58936
58937
58938
58939
58940
58941
58942
58943
58944
58945
58946
58947
58948
58949
58950
58951
58952
58953
58954
58955
58956
58957
58958
58959
58960
58961
58962
58963
58964
58965
58966
58967
58968
58969
58970
58971
58972
58973
58974
58975
58976
58977
58978
58979
58980
58981
58982
58983
58984
58985
58986
58987
58988
58989
58990
58991
58992
58993
58994
58995
58996
58997
58998
58999
59000
59001
59002
59003
59004
59005
59006
59007
59008
59009
59010
59011
59012
59013
59014
59015
59016
59017
59018
59019
59020
59021
59022
59023
59024
59025
59026
59027
59028
59029
59030
59031
59032
59033
59034
59035
59036
59037
59038
59039
59040
59041
59042
59043
59044
59045
59046
59047
59048
59049
59050
59051
59052
59053
59054
59055
59056
59057
59058
59059
59060
59061
59062
59063
59064
59065
59066
59067
59068
59069
59070
59071
59072
59073
59074
59075
59076
59077
59078
59079
59080
59081
59082
59083
59084
59085
59086
59087
59088
59089
59090
59091
59092
59093
59094
59095
59096
59097
59098
59099
59100
59101
59102
59103
59104
59105
59106
59107
59108
59109
59110
59111
59112
59113
59114
59115
59116
59117
59118
59119
59120
59121
59122
59123
59124
59125
59126
59127
59128
59129
59130
59131
59132
59133
59134
59135
59136
59137
59138
59139
59140
59141
59142
59143
59144
59145
59146
59147
59148
59149
59150
59151
59152
59153
59154
59155
59156
59157
59158
59159
59160
59161
59162
59163
59164
59165
59166
59167
59168
59169
59170
59171
59172
59173
59174
59175
59176
59177
59178
59179
59180
59181
59182
59183
59184
59185
59186
59187
59188
59189
59190
59191
59192
59193
59194
59195
59196
59197
59198
59199
59200
59201
59202
59203
59204
59205
59206
59207
59208
59209
59210
59211
59212
59213
59214
59215
59216
59217
59218
59219
59220
59221
59222
59223
59224
59225
59226
59227
59228
59229
59230
59231
59232
59233
59234
59235
59236
59237
59238
59239
59240
59241
59242
59243
59244
59245
59246
59247
59248
59249
59250
59251
59252
59253
59254
59255
59256
59257
59258
59259
59260
59261
59262
59263
59264
59265
59266
59267
59268
59269
59270
59271
59272
59273
59274
59275
59276
59277
59278
59279
59280
59281
59282
59283
59284
59285
59286
59287
59288
59289
59290
59291
59292
59293
59294
59295
59296
59297
59298
59299
59300
59301
59302
59303
59304
59305
59306
59307
59308
59309
59310
59311
59312
59313
59314
59315
59316
59317
59318
59319
59320
59321
59322
59323
59324
59325
59326
59327
59328
59329
59330
59331
59332
59333
59334
59335
59336
59337
59338
59339
59340
59341
59342
59343
59344
59345
59346
59347
59348
59349
59350
59351
59352
59353
59354
59355
59356
59357
59358
59359
59360
59361
59362
59363
59364
59365
59366
59367
59368
59369
59370
59371
59372
59373
59374
59375
59376
59377
59378
59379
59380
59381
59382
59383
59384
59385
59386
59387
59388
59389
59390
59391
59392
59393
59394
59395
59396
59397
59398
59399
59400
59401
59402
59403
59404
59405
59406
59407
59408
59409
59410
59411
59412
59413
59414
59415
59416
59417
59418
59419
59420
59421
59422
59423
59424
59425
59426
59427
59428
59429
59430
59431
59432
59433
59434
59435
59436
59437
59438
59439
59440
59441
59442
59443
59444
59445
59446
59447
59448
59449
59450
59451
59452
59453
59454
59455
59456
59457
59458
59459
59460
59461
59462
59463
59464
59465
59466
59467
59468
59469
59470
59471
59472
59473
59474
59475
59476
59477
59478
59479
59480
59481
59482
59483
59484
59485
59486
59487
59488
59489
59490
59491
59492
59493
59494
59495
59496
59497
59498
59499
59500
59501
59502
59503
59504
59505
59506
59507
59508
59509
59510
59511
59512
59513
59514
59515
59516
59517
59518
59519
59520
59521
59522
59523
59524
59525
59526
59527
59528
59529
59530
59531
59532
59533
59534
59535
59536
59537
59538
59539
59540
59541
59542
59543
59544
59545
59546
59547
59548
59549
59550
59551
59552
59553
59554
59555
59556
59557
59558
59559
59560
59561
59562
59563
59564
59565
59566
59567
59568
59569
59570
59571
59572
59573
59574
59575
59576
59577
59578
59579
59580
59581
59582
59583
59584
59585
59586
59587
59588
59589
59590
59591
59592
59593
59594
59595
59596
59597
59598
59599
59600
59601
59602
59603
59604
59605
59606
59607
59608
59609
59610
59611
59612
59613
59614
59615
59616
59617
59618
59619
59620
59621
59622
59623
59624
59625
59626
59627
59628
59629
59630
59631
59632
59633
59634
59635
59636
59637
59638
59639
59640
59641
59642
59643
59644
59645
59646
59647
59648
59649
59650
59651
59652
59653
59654
59655
59656
59657
59658
59659
59660
59661
59662
59663
59664
59665
59666
59667
59668
59669
59670
59671
59672
59673
59674
59675
59676
59677
59678
59679
59680
59681
59682
59683
59684
59685
59686
59687
59688
59689
59690
59691
59692
59693
59694
59695
59696
59697
59698
59699
59700
59701
59702
59703
59704
59705
59706
59707
59708
59709
59710
59711
59712
59713
59714
59715
59716
59717
59718
59719
59720
59721
59722
59723
59724
59725
59726
59727
59728
59729
59730
59731
59732
59733
59734
59735
59736
59737
59738
59739
59740
59741
59742
59743
59744
59745
59746
59747
59748
59749
59750
59751
59752
59753
59754
59755
59756
59757
59758
59759
59760
59761
59762
59763
59764
59765
59766
59767
59768
59769
59770
59771
59772
59773
59774
59775
59776
59777
59778
59779
59780
59781
59782
59783
59784
59785
59786
59787
59788
59789
59790
59791
59792
59793
59794
59795
59796
59797
59798
59799
59800
59801
59802
59803
59804
59805
59806
59807
59808
59809
59810
59811
59812
59813
59814
59815
59816
59817
59818
59819
59820
59821
59822
59823
59824
59825
59826
59827
59828
59829
59830
59831
59832
59833
59834
59835
59836
59837
59838
59839
59840
59841
59842
59843
59844
59845
59846
59847
59848
59849
59850
59851
59852
59853
59854
59855
59856
59857
59858
59859
59860
59861
59862
59863
59864
59865
59866
59867
59868
59869
59870
59871
59872
59873
59874
59875
59876
59877
59878
59879
59880
59881
59882
59883
59884
59885
59886
59887
59888
59889
59890
59891
59892
59893
59894
59895
59896
59897
59898
59899
59900
59901
59902
59903
59904
59905
59906
59907
59908
59909
59910
59911
59912
59913
59914
59915
59916
59917
59918
59919
59920
59921
59922
59923
59924
59925
59926
59927
59928
59929
59930
59931
59932
59933
59934
59935
59936
59937
59938
59939
59940
59941
59942
59943
59944
59945
59946
59947
59948
59949
59950
59951
59952
59953
59954
59955
59956
59957
59958
59959
59960
59961
59962
59963
59964
59965
59966
59967
59968
59969
59970
59971
59972
59973
59974
59975
59976
59977
59978
59979
59980
59981
59982
59983
59984
59985
59986
59987
59988
59989
59990
59991
59992
59993
59994
59995
59996
59997
59998
59999
60000
60001
60002
60003
60004
60005
60006
60007
60008
60009
60010
60011
60012
60013
60014
60015
60016
60017
60018
60019
60020
60021
60022
60023
60024
60025
60026
60027
60028
60029
60030
60031
60032
60033
60034
60035
60036
60037
60038
60039
60040
60041
60042
60043
60044
60045
60046
60047
60048
60049
60050
60051
60052
60053
60054
60055
60056
60057
60058
60059
60060
60061
60062
60063
60064
60065
60066
60067
60068
60069
60070
60071
60072
60073
60074
60075
60076
60077
60078
60079
60080
60081
60082
60083
60084
60085
60086
60087
60088
60089
60090
60091
60092
60093
60094
60095
60096
60097
60098
60099
60100
60101
60102
60103
60104
60105
60106
60107
60108
60109
60110
60111
60112
60113
60114
60115
60116
60117
60118
60119
60120
60121
60122
60123
60124
60125
60126
60127
60128
60129
60130
60131
60132
60133
60134
60135
60136
60137
60138
60139
60140
60141
60142
60143
60144
60145
60146
60147
60148
60149
60150
60151
60152
60153
60154
60155
60156
60157
60158
60159
60160
60161
60162
60163
60164
60165
60166
60167
60168
60169
60170
60171
60172
60173
60174
60175
60176
60177
60178
60179
60180
60181
60182
60183
60184
60185
60186
60187
60188
60189
60190
60191
60192
60193
60194
60195
60196
60197
60198
60199
60200
60201
60202
60203
60204
60205
60206
60207
60208
60209
60210
60211
60212
60213
60214
60215
60216
60217
60218
60219
60220
60221
60222
60223
60224
60225
60226
60227
60228
60229
60230
60231
60232
60233
60234
60235
60236
60237
60238
60239
60240
60241
60242
60243
60244
60245
60246
60247
60248
60249
60250
60251
60252
60253
60254
60255
60256
60257
60258
60259
60260
60261
60262
60263
60264
60265
60266
60267
60268
60269
60270
60271
60272
60273
60274
60275
60276
60277
60278
60279
60280
60281
60282
60283
60284
60285
60286
60287
60288
60289
60290
60291
60292
60293
60294
60295
60296
60297
60298
60299
60300
60301
60302
60303
60304
60305
60306
60307
60308
60309
60310
60311
60312
60313
60314
60315
60316
60317
60318
60319
60320
60321
60322
60323
60324
60325
60326
60327
60328
60329
60330
60331
60332
60333
60334
60335
60336
60337
60338
60339
60340
60341
60342
60343
60344
60345
60346
60347
60348
60349
60350
60351
60352
60353
60354
60355
60356
60357
60358
60359
60360
60361
60362
60363
60364
60365
60366
60367
60368
60369
60370
60371
60372
60373
60374
60375
60376
60377
60378
60379
60380
60381
60382
60383
60384
60385
60386
60387
60388
60389
60390
60391
60392
60393
60394
60395
60396
60397
60398
60399
60400
60401
60402
60403
60404
60405
60406
60407
60408
60409
60410
60411
60412
60413
60414
60415
60416
60417
60418
60419
60420
60421
60422
60423
60424
60425
60426
60427
60428
60429
60430
60431
60432
60433
60434
60435
60436
60437
60438
60439
60440
60441
60442
60443
60444
60445
60446
60447
60448
60449
60450
60451
60452
60453
60454
60455
60456
60457
60458
60459
60460
60461
60462
60463
60464
60465
60466
60467
60468
60469
60470
60471
60472
60473
60474
60475
60476
60477
60478
60479
60480
60481
60482
60483
60484
60485
60486
60487
60488
60489
60490
60491
60492
60493
60494
60495
60496
60497
60498
60499
60500
60501
60502
60503
60504
60505
60506
60507
60508
60509
60510
60511
60512
60513
60514
60515
60516
60517
60518
60519
60520
60521
60522
60523
60524
60525
60526
60527
60528
60529
60530
60531
60532
60533
60534
60535
60536
60537
60538
60539
60540
60541
60542
60543
60544
60545
60546
60547
60548
60549
60550
60551
60552
60553
60554
60555
60556
60557
60558
60559
60560
60561
60562
60563
60564
60565
60566
60567
60568
60569
60570
60571
60572
60573
60574
60575
60576
60577
60578
60579
60580
60581
60582
60583
60584
60585
60586
60587
60588
60589
60590
60591
60592
60593
60594
60595
60596
60597
60598
60599
60600
60601
60602
60603
60604
60605
60606
60607
60608
60609
60610
60611
60612
60613
60614
60615
60616
60617
60618
60619
60620
60621
60622
60623
60624
60625
60626
60627
60628
60629
60630
60631
60632
60633
60634
60635
60636
60637
60638
60639
60640
60641
60642
60643
60644
60645
60646
60647
60648
60649
60650
60651
60652
60653
60654
60655
60656
60657
60658
60659
60660
60661
60662
60663
60664
60665
60666
60667
60668
60669
60670
60671
60672
60673
60674
60675
60676
60677
60678
60679
60680
60681
60682
60683
60684
60685
60686
60687
60688
60689
60690
60691
60692
60693
60694
60695
60696
60697
60698
60699
60700
60701
60702
60703
60704
60705
60706
60707
60708
60709
60710
60711
60712
60713
60714
60715
60716
60717
60718
60719
60720
60721
60722
60723
60724
60725
60726
60727
60728
60729
60730
60731
60732
60733
60734
60735
60736
60737
60738
60739
60740
60741
60742
60743
60744
60745
60746
60747
60748
60749
60750
60751
60752
60753
60754
60755
60756
60757
60758
60759
60760
60761
60762
60763
60764
60765
60766
60767
60768
60769
60770
60771
60772
60773
60774
60775
60776
60777
60778
60779
60780
60781
60782
60783
60784
60785
60786
60787
60788
60789
60790
60791
60792
60793
60794
60795
60796
60797
60798
60799
60800
60801
60802
60803
60804
60805
60806
60807
60808
60809
60810
60811
60812
60813
60814
60815
60816
60817
60818
60819
60820
60821
60822
60823
60824
60825
60826
60827
60828
60829
60830
60831
60832
60833
60834
60835
60836
60837
60838
60839
60840
60841
60842
60843
60844
60845
60846
60847
60848
60849
60850
60851
60852
60853
60854
60855
60856
60857
60858
60859
60860
60861
60862
60863
60864
60865
60866
60867
60868
60869
60870
60871
60872
60873
60874
60875
60876
60877
60878
60879
60880
60881
60882
60883
60884
60885
60886
60887
60888
60889
60890
60891
60892
60893
60894
60895
60896
60897
60898
60899
60900
60901
60902
60903
60904
60905
60906
60907
60908
60909
60910
60911
60912
60913
60914
60915
60916
60917
60918
60919
60920
60921
60922
60923
60924
60925
60926
60927
60928
60929
60930
60931
60932
60933
60934
60935
60936
60937
60938
60939
60940
60941
60942
60943
60944
60945
60946
60947
60948
60949
60950
60951
60952
60953
60954
60955
60956
60957
60958
60959
60960
60961
60962
60963
60964
60965
60966
60967
60968
60969
60970
60971
60972
60973
60974
60975
60976
60977
60978
60979
60980
60981
60982
60983
60984
60985
60986
60987
60988
60989
60990
60991
60992
60993
60994
60995
60996
60997
60998
60999
61000
61001
61002
61003
61004
61005
61006
61007
61008
61009
61010
61011
61012
61013
61014
61015
61016
61017
61018
61019
61020
61021
61022
61023
61024
61025
61026
61027
61028
61029
61030
61031
61032
61033
61034
61035
61036
61037
61038
61039
61040
61041
61042
61043
61044
61045
61046
61047
61048
61049
61050
61051
61052
61053
61054
61055
61056
61057
61058
61059
61060
61061
61062
61063
61064
61065
61066
61067
61068
61069
61070
61071
61072
61073
61074
61075
61076
61077
61078
61079
61080
61081
61082
61083
61084
61085
61086
61087
61088
61089
61090
61091
61092
61093
61094
61095
61096
61097
61098
61099
61100
61101
61102
61103
61104
61105
61106
61107
61108
61109
61110
61111
61112
61113
61114
61115
61116
61117
61118
61119
61120
61121
61122
61123
61124
61125
61126
61127
61128
61129
61130
61131
61132
61133
61134
61135
61136
61137
61138
61139
61140
61141
61142
61143
61144
61145
61146
61147
61148
61149
61150
61151
61152
61153
61154
61155
61156
61157
61158
61159
61160
61161
61162
61163
61164
61165
61166
61167
61168
61169
61170
61171
61172
61173
61174
61175
61176
61177
61178
61179
61180
61181
61182
61183
61184
61185
61186
61187
61188
61189
61190
61191
61192
61193
61194
61195
61196
61197
61198
61199
61200
61201
61202
61203
61204
61205
61206
61207
61208
61209
61210
61211
61212
61213
61214
61215
61216
61217
61218
61219
61220
61221
61222
61223
61224
61225
61226
61227
61228
61229
61230
61231
61232
61233
61234
61235
61236
61237
61238
61239
61240
61241
61242
61243
61244
61245
61246
61247
61248
61249
61250
61251
61252
61253
61254
61255
61256
61257
61258
61259
61260
61261
61262
61263
61264
61265
61266
61267
61268
61269
61270
61271
61272
61273
61274
61275
61276
61277
61278
61279
61280
61281
61282
61283
61284
61285
61286
61287
61288
61289
61290
61291
61292
61293
61294
61295
61296
61297
61298
61299
61300
61301
61302
61303
61304
61305
61306
61307
61308
61309
61310
61311
61312
61313
61314
61315
61316
61317
61318
61319
61320
61321
61322
61323
61324
61325
61326
61327
61328
61329
61330
61331
61332
61333
61334
61335
61336
61337
61338
61339
61340
61341
61342
61343
61344
61345
61346
61347
61348
61349
61350
61351
61352
61353
61354
61355
61356
61357
61358
61359
61360
61361
61362
61363
61364
61365
61366
61367
61368
61369
61370
61371
61372
61373
61374
61375
61376
61377
61378
61379
61380
61381
61382
61383
61384
61385
61386
61387
61388
61389
61390
61391
61392
61393
61394
61395
61396
61397
61398
61399
61400
61401
61402
61403
61404
61405
61406
61407
61408
61409
61410
61411
61412
61413
61414
61415
61416
61417
61418
61419
61420
61421
61422
61423
61424
61425
61426
61427
61428
61429
61430
61431
61432
61433
61434
61435
61436
61437
61438
61439
61440
61441
61442
61443
61444
61445
61446
61447
61448
61449
61450
61451
61452
61453
61454
61455
61456
61457
61458
61459
61460
61461
61462
61463
61464
61465
61466
61467
61468
61469
61470
61471
61472
61473
61474
61475
61476
61477
61478
61479
61480
61481
61482
61483
61484
61485
61486
61487
61488
61489
61490
61491
61492
61493
61494
61495
61496
61497
61498
61499
61500
61501
61502
61503
61504
61505
61506
61507
61508
61509
61510
61511
61512
61513
61514
61515
61516
61517
61518
61519
61520
61521
61522
61523
61524
61525
61526
61527
61528
61529
61530
61531
61532
61533
61534
61535
61536
61537
61538
61539
61540
61541
61542
61543
61544
61545
61546
61547
61548
61549
61550
61551
61552
61553
61554
61555
61556
61557
61558
61559
61560
61561
61562
61563
61564
61565
61566
61567
61568
61569
61570
61571
61572
61573
61574
61575
61576
61577
61578
61579
61580
61581
61582
61583
61584
61585
61586
61587
61588
61589
61590
61591
61592
61593
61594
61595
61596
61597
61598
61599
61600
61601
61602
61603
61604
61605
61606
61607
61608
61609
61610
61611
61612
61613
61614
61615
61616
61617
61618
61619
61620
61621
61622
61623
61624
61625
61626
61627
61628
61629
61630
61631
61632
61633
61634
61635
61636
61637
61638
61639
61640
61641
61642
61643
61644
61645
61646
61647
61648
61649
61650
61651
61652
61653
61654
61655
61656
61657
61658
61659
61660
61661
61662
61663
61664
61665
61666
61667
61668
61669
61670
61671
61672
61673
61674
61675
61676
61677
61678
61679
61680
61681
61682
61683
61684
61685
61686
61687
61688
61689
61690
61691
61692
61693
61694
61695
61696
61697
61698
61699
61700
61701
61702
61703
61704
61705
61706
61707
61708
61709
61710
61711
61712
61713
61714
61715
61716
61717
61718
61719
61720
61721
61722
61723
61724
61725
61726
61727
61728
61729
61730
61731
61732
61733
61734
61735
61736
61737
61738
61739
61740
61741
61742
61743
61744
61745
61746
61747
61748
61749
61750
61751
61752
61753
61754
61755
61756
61757
61758
61759
61760
61761
61762
61763
61764
61765
61766
61767
61768
61769
61770
61771
61772
61773
61774
61775
61776
61777
61778
61779
61780
61781
61782
61783
61784
61785
61786
61787
61788
61789
61790
61791
61792
61793
61794
61795
61796
61797
61798
61799
61800
61801
61802
61803
61804
61805
61806
61807
61808
61809
61810
61811
61812
61813
61814
61815
61816
61817
61818
61819
61820
61821
61822
61823
61824
61825
61826
61827
61828
61829
61830
61831
61832
61833
61834
61835
61836
61837
61838
61839
61840
61841
61842
61843
61844
61845
61846
61847
61848
61849
61850
61851
61852
61853
61854
61855
61856
61857
61858
61859
61860
61861
61862
61863
61864
61865
61866
61867
61868
61869
61870
61871
61872
61873
61874
61875
61876
61877
61878
61879
61880
61881
61882
61883
61884
61885
61886
61887
61888
61889
61890
61891
61892
61893
61894
61895
61896
61897
61898
61899
61900
61901
61902
61903
61904
61905
61906
61907
61908
61909
61910
61911
61912
61913
61914
61915
61916
61917
61918
61919
61920
61921
61922
61923
61924
61925
61926
61927
61928
61929
61930
61931
61932
61933
61934
61935
61936
61937
61938
61939
61940
61941
61942
61943
61944
61945
61946
61947
61948
61949
61950
61951
61952
61953
61954
61955
61956
61957
61958
61959
61960
61961
61962
61963
61964
61965
61966
61967
61968
61969
61970
61971
61972
61973
61974
61975
61976
61977
61978
61979
61980
<!DOCTYPE html>
<HTML>
<HEAD>
<TITLE>SWIG-4.0 Documentation</TITLE>
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; CHARSET=iso-8859-1">
<STYLE TYPE="text/css"><!--

div.sectiontoc {
  border-style: dotted;
  border-width: 2px;
  padding: 2pt;
}

h2 { 
  padding: 3px;
  color: #000000;
  border-bottom: 2px 
  solid #dddddd; 
}

h3, h4 {
  margin-left: 1em;
}

p,li,table,dl {
  margin-left: 2em;
  margin-right: 2em;
}

div.indent {
  margin-left: 4em;
  margin-right: 4em;
}

div.code {
  border-style: solid; 
  border-width: 1px; 
  padding: 2pt; 
  margin-left: 4em;
  margin-right: 4em;
  background-color: #F0FFFF;
  font-family: "Courier New", Courier, "Courier 10 Pitch", monospace;
}

div.targetlang {
  border-style: solid; 
  border-width: 1px; 
  padding: 2pt; 
  margin-left: 4em;
  margin-right: 4em;
  background-color: #d7f6bb;
  font-family: "Courier New", Courier, "Courier 10 Pitch", monospace;
}

div.shell {
  border-style: solid; 
  border-width: 1px; 
  padding: 2pt; 
  margin-left: 4em;
  margin-right: 4em;
  background-color: #DCDCDC;
  font-family: "Courier New", Courier, "Courier 10 Pitch", monospace;
}

div.diagram {
  border-style: solid; 
  border-width: 1px; 
  padding: 2pt; 
  margin-left: 4em;
  margin-right: 4em;
  background-color: #FFEBCD;
  font-family: "Courier New", Courier, "Courier 10 Pitch", monospace;
}

div.diagram li {
    margin-left: 0;
}

ul li p {
  margin-left: 0;
  margin-right: 0;
}

ol li p {
  margin-left: 0;
  margin-right: 0;
}

dl dd p {
  margin-left: 0;
  margin-right: 0;
}

div.indent p {
  margin-left: 0;
  margin-right: 0;
}

pre, code, tt {
  font-family: "Courier New", Courier, "Courier 10 Pitch", monospace;
}

body { font-family: serif; }

--></STYLE>
</HEAD>
<BODY BGCOLOR="#ffffff" LINK="#0000ff" VLINK="#0000ff" ALINK="#0000ff">
<CENTER><A HREF="#CONTENTS"><IMG SRC="swig16.png" BORDER="0" WIDTH="167" HEIGHT="85" ALT="SWIG-4.0 Documentation"><BR>
<H1>SWIG-4.0 Documentation</H1></A><BR>
</CENTER>
<HR NOSHADE>
<h1 ALIGN="CENTER"><a NAME="CONTENTS">Table of Contents</a></h1>
<br>
<br><b><a HREF="#Sections">SWIG-4.0 Documentation</a></b>
<ul>
<li><a HREF="#Sections_Sections">Sections</a>
<ul>
<li><a HREF="#Sections_core_docs">SWIG Core Documentation</a></li>
<li><a HREF="#Sections_language_modules">Supported Language Modules
 Documentation</a></li>
<li><a HREF="#Sections_experimental_language_modules">Experimental
 Language Modules Documentation</a></li>
<li><a HREF="#Sections_developers_docs">Developer Documentation</a></li>
</ul>
</li>
</ul>
<b><a HREF="#Preface">1 Preface</a></b>
<ul>
<li><a HREF="#Preface_nn2">1.1 Introduction</a></li>
<li><a HREF="#Preface_nn4">1.2 SWIG Versions</a></li>
<li><a HREF="#Preface_license">1.3 SWIG License</a></li>
<li><a HREF="#Preface_nn5">1.4 SWIG resources</a></li>
<li><a HREF="#Preface_nn6">1.5 Prerequisites</a></li>
<li><a HREF="#Preface_nn7">1.6 Organization of this manual</a></li>
<li><a HREF="#Preface_nn8">1.7 How to avoid reading the manual</a></li>
<li><a HREF="#Preface_nn9">1.8 Backwards compatibility</a></li>
<li><a HREF="#Preface_release_notes">1.9 Release notes</a></li>
<li><a HREF="#Preface_nn10">1.10 Credits</a></li>
<li><a HREF="#Preface_nn11">1.11 Bug reports</a></li>
<li><a HREF="#Preface_installation">1.12 Installation</a>
<ul>
<li><a HREF="#Preface_windows_installation">1.12.1 Windows installation</a>
</li>
<li><a HREF="#Preface_unix_installation">1.12.2 Unix installation</a></li>
<li><a HREF="#Preface_osx_installation">1.12.3 Macintosh OS X
 installation</a></li>
<li><a HREF="#Preface_testing">1.12.4 Testing</a></li>
<li><a HREF="#Preface_examples">1.12.5 Examples</a></li>
</ul>
</li>
</ul>
<b><a HREF="#Introduction">2 Introduction</a></b>
<ul>
<li><a HREF="#Introduction_nn2">2.1 What is SWIG?</a></li>
<li><a HREF="#Introduction_nn3">2.2 Why use SWIG?</a></li>
<li><a HREF="#Introduction_target_languages">2.3 Target languages</a>
<ul>
<li><a HREF="#Introduction_supported_status">2.3.1 Supported status</a></li>
<li><a HREF="#Introduction_experimental_status">2.3.2 Experimental
 status</a></li>
</ul>
</li>
<li><a HREF="#Introduction_nn4">2.4 A SWIG example</a>
<ul>
<li><a HREF="#Introduction_nn5">2.4.1 SWIG interface file</a></li>
<li><a HREF="#Introduction_nn6">2.4.2 The swig command</a></li>
<li><a HREF="#Introduction_nn7">2.4.3 Building a Perl5 module</a></li>
<li><a HREF="#Introduction_nn8">2.4.4 Building a Python module</a></li>
<li><a HREF="#Introduction_nn9">2.4.5 Shortcuts</a></li>
</ul>
</li>
<li><a HREF="#Introduction_nn10">2.5 Supported C/C++ language features</a>
</li>
<li><a HREF="#Introduction_nn11">2.6 Non-intrusive interface building</a>
</li>
<li><a HREF="#Introduction_build_system">2.7 Incorporating SWIG into a
 build system</a></li>
<li><a HREF="#Introduction_nn12">2.8 Hands off code generation</a></li>
<li><a HREF="#Introduction_nn13">2.9 SWIG and freedom</a></li>
</ul>
<b><a HREF="#Windows">3 Getting started on Windows</a></b>
<ul>
<li><a HREF="#Windows_installation">3.1 Installation on Windows</a>
<ul>
<li><a HREF="#Windows_executable">3.1.1 Windows Executable</a></li>
</ul>
</li>
<li><a HREF="#Windows_examples">3.2 SWIG Windows Examples</a>
<ul>
<li><a HREF="#Windows_visual_studio">3.2.1 Instructions for using the
 Examples with Visual Studio</a>
<ul>
<li><a HREF="#Windows_csharp">3.2.1.1 C#</a></li>
<li><a HREF="#Windows_java">3.2.1.2 Java</a></li>
<li><a HREF="#Windows_perl">3.2.1.3 Perl</a></li>
<li><a HREF="#Windows_python">3.2.1.4 Python</a></li>
<li><a HREF="#Windows_tcl">3.2.1.5 TCL</a></li>
<li><a HREF="#Windows_r">3.2.1.6 R</a></li>
<li><a HREF="#Windows_ruby">3.2.1.7 Ruby</a></li>
</ul>
</li>
<li><a HREF="#Windows_other_compilers">3.2.2 Instructions for using the
 Examples with other compilers</a></li>
</ul>
</li>
<li><a HREF="#Windows_cygwin_mingw">3.3 SWIG on Cygwin and MinGW</a>
<ul>
<li><a HREF="#Windows_swig_exe">3.3.1 Building swig.exe on Windows</a>
<ul>
<li><a HREF="#Windows_mingw_msys">3.3.1.1 Building swig.exe using MinGW
 and MSYS</a></li>
<li><a HREF="#Windows_cygwin">3.3.1.2 Building swig.exe using Cygwin</a></li>
<li><a HREF="#Windows_building_alternatives">3.3.1.3 Building swig.exe
 alternatives</a></li>
</ul>
</li>
<li><a HREF="#Windows_examples_cygwin">3.3.2 Running the examples on
 Windows using Cygwin</a></li>
</ul>
</li>
<li><a HREF="#Windows_interface_file">3.4 Microsoft extensions and other
 Windows quirks</a></li>
</ul>
<b><a HREF="#Scripting">4 Scripting Languages</a></b>
<ul>
<li><a HREF="#Scripting_nn2">4.1 The two language view of the world</a></li>
<li><a HREF="#Scripting_nn3">4.2 How does a scripting language talk to
 C?</a>
<ul>
<li><a HREF="#Scripting_nn4">4.2.1 Wrapper functions</a></li>
<li><a HREF="#Scripting_nn5">4.2.2 Variable linking</a></li>
<li><a HREF="#Scripting_nn6">4.2.3 Constants</a></li>
<li><a HREF="#Scripting_nn7">4.2.4 Structures and classes</a></li>
<li><a HREF="#Scripting_nn8">4.2.5 Proxy classes</a></li>
</ul>
</li>
<li><a HREF="#Scripting_nn9">4.3 Building scripting language extensions</a>
<ul>
<li><a HREF="#Scripting_nn10">4.3.1 Shared libraries and dynamic loading</a>
</li>
<li><a HREF="#Scripting_nn11">4.3.2 Linking with shared libraries</a></li>
<li><a HREF="#Scripting_nn12">4.3.3 Static linking</a></li>
</ul>
</li>
</ul>
<b><a HREF="#SWIG">5 SWIG Basics</a></b>
<ul>
<li><a HREF="#SWIG_nn2">5.1 Running SWIG</a>
<ul>
<li><a HREF="#SWIG_nn3">5.1.1 Input format</a></li>
<li><a HREF="#SWIG_output">5.1.2 SWIG Output</a></li>
<li><a HREF="#SWIG_nn5">5.1.3 Comments</a></li>
<li><a HREF="#SWIG_nn6">5.1.4 C Preprocessor</a></li>
<li><a HREF="#SWIG_nn7">5.1.5 SWIG Directives</a></li>
<li><a HREF="#SWIG_nn8">5.1.6 Parser Limitations</a></li>
</ul>
</li>
<li><a HREF="#SWIG_nn9">5.2 Wrapping Simple C Declarations</a>
<ul>
<li><a HREF="#SWIG_nn10">5.2.1 Basic Type Handling</a></li>
<li><a HREF="#SWIG_nn11">5.2.2 Global Variables</a></li>
<li><a HREF="#SWIG_nn12">5.2.3 Constants</a></li>
<li><a HREF="#SWIG_nn13">5.2.4 A brief word about const</a></li>
<li><a HREF="#SWIG_nn14">5.2.5 A cautionary tale of char *</a></li>
</ul>
</li>
<li><a HREF="#SWIG_nn15">5.3 Pointers and complex objects</a>
<ul>
<li><a HREF="#SWIG_nn16">5.3.1 Simple pointers</a></li>
<li><a HREF="#SWIG_nn17">5.3.2 Run time pointer type checking</a></li>
<li><a HREF="#SWIG_nn18">5.3.3 Derived types, structs, and classes</a></li>
<li><a HREF="#SWIG_nn19">5.3.4 Undefined datatypes</a></li>
<li><a HREF="#SWIG_nn20">5.3.5 Typedef</a></li>
</ul>
</li>
<li><a HREF="#SWIG_nn21">5.4 Other Practicalities</a>
<ul>
<li><a HREF="#SWIG_nn22">5.4.1 Passing structures by value</a></li>
<li><a HREF="#SWIG_nn23">5.4.2 Return by value</a></li>
<li><a HREF="#SWIG_nn24">5.4.3 Linking to structure variables</a></li>
<li><a HREF="#SWIG_nn25">5.4.4 Linking to char *</a></li>
<li><a HREF="#SWIG_nn26">5.4.5 Arrays</a></li>
<li><a HREF="#SWIG_readonly_variables">5.4.6 Creating read-only
 variables</a></li>
<li><a HREF="#SWIG_rename_ignore">5.4.7 Renaming and ignoring
 declarations</a>
<ul>
<li><a HREF="#SWIG_nn29">5.4.7.1 Simple renaming of specific identifiers</a>
</li>
<li><a HREF="#SWIG_advanced_renaming">5.4.7.2 Advanced renaming support</a>
</li>
<li><a HREF="#SWIG_limiting_renaming">5.4.7.3 Limiting global renaming
 rules</a></li>
<li><a HREF="#SWIG_chosen_unignore">5.4.7.4 Ignoring everything then
 wrapping a few selected symbols</a></li>
</ul>
</li>
<li><a HREF="#SWIG_default_args">5.4.8 Default/optional arguments</a></li>
<li><a HREF="#SWIG_nn30">5.4.9 Pointers to functions and callbacks</a></li>
</ul>
</li>
<li><a HREF="#SWIG_nn31">5.5 Structures and unions</a>
<ul>
<li><a HREF="#SWIG_nn32">5.5.1 Typedef and structures</a></li>
<li><a HREF="#SWIG_nn33">5.5.2 Character strings and structures</a></li>
<li><a HREF="#SWIG_nn34">5.5.3 Array members</a></li>
<li><a HREF="#SWIG_structure_data_members">5.5.4 Structure data members</a>
</li>
<li><a HREF="#SWIG_nn36">5.5.5 C constructors and destructors</a></li>
<li><a HREF="#SWIG_adding_member_functions">5.5.6 Adding member
 functions to C structures</a></li>
<li><a HREF="#SWIG_nested_structs">5.5.7 Nested structures</a></li>
<li><a HREF="#SWIG_nn39">5.5.8 Other things to note about structure
 wrapping</a></li>
</ul>
</li>
<li><a HREF="#SWIG_nn40">5.6 Code Insertion</a>
<ul>
<li><a HREF="#SWIG_nn41">5.6.1 The output of SWIG</a></li>
<li><a HREF="#SWIG_nn42">5.6.2 Code insertion blocks</a></li>
<li><a HREF="#SWIG_nn43">5.6.3 Inlined code blocks</a></li>
<li><a HREF="#SWIG_nn44">5.6.4 Initialization blocks</a></li>
</ul>
</li>
<li><a HREF="#SWIG_nn45">5.7 An Interface Building Strategy</a>
<ul>
<li><a HREF="#SWIG_nn46">5.7.1 Preparing a C program for SWIG</a></li>
<li><a HREF="#SWIG_nn47">5.7.2 The SWIG interface file</a></li>
<li><a HREF="#SWIG_nn48">5.7.3 Why use separate interface files?</a></li>
<li><a HREF="#SWIG_nn49">5.7.4 Getting the right header files</a></li>
<li><a HREF="#SWIG_nn50">5.7.5 What to do with main()</a></li>
</ul>
</li>
</ul>
<b><a HREF="#SWIGPlus">6 SWIG and C++</a></b>
<ul>
<li><a HREF="#SWIGPlus_nn2">6.1 Comments on C++ Wrapping</a></li>
<li><a HREF="#SWIGPlus_nn3">6.2 Approach</a></li>
<li><a HREF="#SWIGPlus_nn4">6.3 Supported C++ features</a></li>
<li><a HREF="#SWIGPlus_nn5">6.4 Command line options and compilation</a></li>
<li><a HREF="#SWIGPlus_nn38">6.5 Proxy classes</a>
<ul>
<li><a HREF="#SWIGPlus_nn39">6.5.1 Construction of proxy classes</a></li>
<li><a HREF="#SWIGPlus_nn40">6.5.2 Resource management in proxies</a></li>
<li><a HREF="#SWIGPlus_nn41">6.5.3 Language specific details</a></li>
</ul>
</li>
<li><a HREF="#SWIGPlus_nn6">6.6 Simple C++ wrapping</a>
<ul>
<li><a HREF="#SWIGPlus_nn7">6.6.1 Constructors and destructors</a></li>
<li><a HREF="#SWIGPlus_nn8">6.6.2 Default constructors, copy
 constructors and implicit destructors</a></li>
<li><a HREF="#SWIGPlus_nn9">6.6.3 When constructor wrappers aren't
 created</a></li>
<li><a HREF="#SWIGPlus_nn10">6.6.4 Copy constructors</a></li>
<li><a HREF="#SWIGPlus_nn11">6.6.5 Member functions</a></li>
<li><a HREF="#SWIGPlus_nn12">6.6.6 Static members</a></li>
<li><a HREF="#SWIGPlus_member_data">6.6.7 Member data</a></li>
</ul>
</li>
<li><a HREF="#SWIGPlus_nn15">6.7 Protection</a></li>
<li><a HREF="#SWIGPlus_nn16">6.8 Enums and constants</a></li>
<li><a HREF="#SWIGPlus_nn17">6.9 Friends</a></li>
<li><a HREF="#SWIGPlus_nn18">6.10 References and pointers</a></li>
<li><a HREF="#SWIGPlus_nn19">6.11 Pass and return by value</a></li>
<li><a HREF="#SWIGPlus_nn20">6.12 Inheritance</a></li>
<li><a HREF="#SWIGPlus_nn21">6.13 A brief discussion of multiple
 inheritance, pointers, and type checking</a></li>
<li><a HREF="#SWIGPlus_default_args">6.14 Default arguments</a></li>
<li><a HREF="#SWIGPlus_overloaded_methods">6.15 Overloaded functions and
 methods</a>
<ul>
<li><a HREF="#SWIGPlus_nn24">6.15.1 Dispatch function generation</a></li>
<li><a HREF="#SWIGPlus_nn25">6.15.2 Ambiguity in overloading</a></li>
<li><a HREF="#SWIGPlus_ambiguity_resolution_renaming">6.15.3 Renaming
 and ambiguity resolution</a></li>
<li><a HREF="#SWIGPlus_nn27">6.15.4 Comments on overloading</a></li>
</ul>
</li>
<li><a HREF="#SWIGPlus_nn28">6.16 Overloaded operators</a></li>
<li><a HREF="#SWIGPlus_class_extension">6.17 Class extension</a></li>
<li><a HREF="#SWIGPlus_nn30">6.18 Templates</a>
<ul>
<li><a HREF="#SWIGPlus_template_directive">6.18.1 The %template
 directive</a></li>
<li><a HREF="#SWIGPlus_template_functions">6.18.2 Function templates</a></li>
<li><a HREF="#SWIGPlus_template_classes">6.18.3 Default template
 arguments</a></li>
<li><a HREF="#SWIGPlus_template_class_inheritance">6.18.4 Template base
 classes</a></li>
<li><a HREF="#SWIGPlus_template_specialization">6.18.5 Template
 specialization</a></li>
<li><a HREF="#SWIGPlus_template_member">6.18.6 Member templates</a></li>
<li><a HREF="#SWIGPlus_template_scoping">6.18.7 Scoping and templates</a>
</li>
<li><a HREF="#SWIGPlus_template_more">6.18.8 More on templates</a></li>
</ul>
</li>
<li><a HREF="#SWIGPlus_namespaces">6.19 Namespaces</a>
<ul>
<li><a HREF="#SWIGPlus_nspace">6.19.1 The nspace feature for namespaces</a>
</li>
</ul>
</li>
<li><a HREF="#SWIGPlus_renaming_templated_types_namespaces">6.20
 Renaming templated types in namespaces</a></li>
<li><a HREF="#SWIGPlus_exception_specifications">6.21 Exception
 specifications</a></li>
<li><a HREF="#SWIGPlus_catches">6.22 Exception handling with %catches</a>
</li>
<li><a HREF="#SWIGPlus_nn33">6.23 Pointers to Members</a></li>
<li><a HREF="#SWIGPlus_smart_pointers">6.24 Smart pointers and
 operator-&gt;()</a></li>
<li><a HREF="#SWIGPlus_ref_unref">6.25 C++ reference counted objects -
 ref/unref feature</a></li>
<li><a HREF="#SWIGPlus_nn35">6.26 Using declarations and inheritance</a></li>
<li><a HREF="#SWIGPlus_nested_classes">6.27 Nested classes</a></li>
<li><a HREF="#SWIGPlus_const">6.28 A brief rant about const-correctness</a>
</li>
<li><a HREF="#SWIGPlus_target_language_callbacks">6.29 Callbacks to the
 target language</a>
<ul>
<li><a HREF="#SWIGPlus_director_classes_introduction">6.29.1
 Introduction to director classes</a></li>
<li><a HREF="#SWIGPlus_directors_for_function_pointers">6.29.2 Using
 directors and target language callbacks</a></li>
</ul>
</li>
<li><a HREF="#SWIGPlus_nn42">6.30 Where to go for more information</a></li>
</ul>
<b><a HREF="#CPlusPlus11">7 SWIG and C++11</a></b>
<ul>
<li><a HREF="#CPlusPlus11_introduction">7.1 Introduction</a></li>
<li><a HREF="#CPlusPlus11_core_language_changes">7.2 Core language
 changes</a>
<ul>
<li><a HREF="#CPlusPlus11_rvalue_reference_and_move_semantics">7.2.1
 Rvalue reference and move semantics</a></li>
<li><a HREF="#CPlusPlus11_generalized_constant_expressions">7.2.2
 Generalized constant expressions</a></li>
<li><a HREF="#CPlusPlus11_extern_template">7.2.3 Extern template</a></li>
<li><a HREF="#CPlusPlus11_initializer_lists">7.2.4 Initializer lists</a></li>
<li><a HREF="#CPlusPlus11_uniform_initialization">7.2.5 Uniform
 initialization</a></li>
<li><a HREF="#CPlusPlus11_type_inference">7.2.6 Type inference</a></li>
<li><a HREF="#CPlusPlus11_range_based_for_loop">7.2.7 Range-based
 for-loop</a></li>
<li><a HREF="#CPlusPlus11_lambda_functions_and_expressions">7.2.8 Lambda
 functions and expressions</a></li>
<li><a HREF="#CPlusPlus11_alternate_function_syntax">7.2.9 Alternate
 function syntax</a></li>
<li><a HREF="#CPlusPlus11_object_construction_improvement">7.2.10 Object
 construction improvement</a></li>
<li><a HREF="#CPlusPlus11_explicit_overrides_final">7.2.11 Explicit
 overrides and final</a></li>
<li><a HREF="#CPlusPlus11_null_pointer_constant">7.2.12 Null pointer
 constant</a></li>
<li><a HREF="#CPlusPlus11_strongly_typed_enumerations">7.2.13 Strongly
 typed enumerations</a></li>
<li><a HREF="#CPlusPlus11_double_angle_brackets">7.2.14 Double angle
 brackets</a></li>
<li><a HREF="#CPlusPlus11_explicit_conversion_operators">7.2.15 Explicit
 conversion operators</a></li>
<li><a HREF="#CPlusPlus11_alias_templates">7.2.16 Type alias and alias
 templates</a></li>
<li><a HREF="#CPlusPlus11_unrestricted_unions">7.2.17 Unrestricted
 unions</a></li>
<li><a HREF="#CPlusPlus11_variadic_templates">7.2.18 Variadic templates</a>
</li>
<li><a HREF="#CPlusPlus11_new_char_literals">7.2.19 New character
 literals</a></li>
<li><a HREF="#CPlusPlus11_new_string_literals">7.2.20 New string
 literals</a></li>
<li><a HREF="#CPlusPlus11_user_defined_literals">7.2.21 User-defined
 literals</a></li>
<li><a HREF="#CPlusPlus11_thread_local_storage">7.2.22 Thread-local
 storage</a></li>
<li><a HREF="#CPlusPlus11_defaulted_deleted">7.2.23 Explicitly defaulted
 functions and deleted functions</a></li>
<li><a HREF="#CPlusPlus11_type_long_long_int">7.2.24 Type long long int</a>
</li>
<li><a HREF="#CPlusPlus11_static_assertions">7.2.25 Static assertions</a>
</li>
<li><a HREF="#CPlusPlus11_sizeof">7.2.26 Allow sizeof to work on members
 of classes without an explicit object</a></li>
<li><a HREF="#CPlusPlus11_noexcept">7.2.27 Exception specifications and
 noexcept</a></li>
<li><a HREF="#CPlusPlus11_alignment">7.2.28 Control and query object
 alignment</a></li>
<li><a HREF="#CPlusPlus11_attributes">7.2.29 Attributes</a></li>
<li><a HREF="#CPlusPlus11_ref_qualifiers">7.2.30 Methods with
 ref-qualifiers</a></li>
</ul>
</li>
<li><a HREF="#CPlusPlus11_standard_library_changes">7.3 Standard library
 changes</a>
<ul>
<li><a HREF="#CPlusPlus11_threading_facilities">7.3.1 Threading
 facilities</a></li>
<li><a HREF="#CPlusPlus11_tuple_types">7.3.2 Tuple types</a></li>
<li><a HREF="#CPlusPlus11_hash_tables">7.3.3 Hash tables</a></li>
<li><a HREF="#CPlusPlus11_regular_expressions">7.3.4 Regular expressions</a>
</li>
<li><a HREF="#CPlusPlus11_general_purpose_smart_pointers">7.3.5
 General-purpose smart pointers</a></li>
<li><a HREF="#CPlusPlus11_extensible_random_number_facility">7.3.6
 Extensible random number facility</a></li>
<li><a HREF="#CPlusPlus11_wrapper_reference">7.3.7 Wrapper reference</a></li>
<li><a HREF="#CPlusPlus11_polymorphous_wrappers_for_function_objects">
7.3.8 Polymorphic wrappers for function objects</a></li>
<li><a HREF="#CPlusPlus11_type_traits_for_metaprogramming">7.3.9 Type
 traits for metaprogramming</a></li>
<li><a HREF="#CPlusPlus11_uniform_method_for_computing_return_type_of_function_objects">
7.3.10 Uniform method for computing return type of function objects</a></li>
</ul>
</li>
</ul>
<b><a HREF="#CPlusPlus14">8 SWIG and C++14</a></b>
<ul>
<li><a HREF="#CPlusPlus14_introduction">8.1 Introduction</a></li>
<li><a HREF="#CPlusPlus14_core_language_changes">8.2 Core language
 changes</a>
<ul>
<li><a HREF="#CPlusPlus14_binary_literals">8.2.1 Binary integer literals</a>
</li>
</ul>
</li>
<li><a HREF="#CPlusPlus14_standard_library_changes">8.3 Standard library
 changes</a></li>
</ul>
<b><a HREF="#CPlusPlus17">9 SWIG and C++17</a></b>
<ul>
<li><a HREF="#CPlusPlus17_introduction">9.1 Introduction</a></li>
<li><a HREF="#CPlusPlus17_core_language_changes">9.2 Core language
 changes</a>
<ul>
<li><a HREF="#CPlusPlus17_nested_namespaces">9.2.1 Nested namespace
 definitions</a></li>
<li><a HREF="#CPlusPlus17_u8_char_literals">9.2.2 UTF-8 character
 literals</a></li>
<li><a HREF="#CPlusPlus17_hexadecimal_floating_literals">9.2.3
 Hexadecimal floating literals</a></li>
</ul>
</li>
<li><a HREF="#CPlusPlus17_standard_library_changes">9.3 Standard library
 changes</a></li>
</ul>
<b><a HREF="#Preprocessor">10 Preprocessing</a></b>
<ul>
<li><a HREF="#Preprocessor_nn2">10.1 File inclusion</a></li>
<li><a HREF="#Preprocessor_nn3">10.2 File imports</a></li>
<li><a HREF="#Preprocessor_condition_compilation">10.3 Conditional
 Compilation</a></li>
<li><a HREF="#Preprocessor_nn5">10.4 Macro Expansion</a></li>
<li><a HREF="#Preprocessor_nn6">10.5 SWIG Macros</a></li>
<li><a HREF="#Preprocessor_nn7">10.6 C99 and GNU Extensions</a></li>
<li><a HREF="#Preprocessor_delimiters">10.7 Preprocessing and delimiters</a>
<ul>
<li><a HREF="#Preprocessor_nn8">10.7.1 Preprocessing and %{ ... %} &amp; &quot;
 ... &quot; delimiters</a></li>
<li><a HREF="#Preprocessor_nn9">10.7.2 Preprocessing and { ... }
 delimiters</a></li>
</ul>
</li>
<li><a HREF="#Preprocessor_typemap_delimiters">10.8 Preprocessor and
 Typemaps</a></li>
<li><a HREF="#Preprocessor_nn10">10.9 Viewing preprocessor output</a></li>
<li><a HREF="#Preprocessor_warning_error">10.10 The #error and #warning
 directives</a></li>
</ul>
<b><a HREF="#Library">11 SWIG library</a></b>
<ul>
<li><a HREF="#Library_nn2">11.1 The %include directive and library
 search path</a></li>
<li><a HREF="#Library_nn3">11.2 C arrays and pointers</a>
<ul>
<li><a HREF="#Library_nn4">11.2.1 cpointer.i</a></li>
<li><a HREF="#Library_carrays">11.2.2 carrays.i</a></li>
<li><a HREF="#Library_nn6">11.2.3 cmalloc.i</a></li>
<li><a HREF="#Library_nn7">11.2.4 cdata.i</a></li>
</ul>
</li>
<li><a HREF="#Library_nn8">11.3 C string handling</a>
<ul>
<li><a HREF="#Library_nn9">11.3.1 Default string handling</a></li>
<li><a HREF="#Library_nn10">11.3.2 Passing binary data</a></li>
<li><a HREF="#Library_nn11">11.3.3 Using %newobject to release memory</a>
</li>
<li><a HREF="#Library_nn12">11.3.4 cstring.i</a></li>
</ul>
</li>
<li><a HREF="#Library_stl_cpp_library">11.4 STL/C++ library</a>
<ul>
<li><a HREF="#Library_std_string">11.4.1 std::string</a></li>
<li><a HREF="#Library_std_vector">11.4.2 std::vector</a></li>
<li><a HREF="#Library_stl_exceptions">11.4.3 STL exceptions</a></li>
<li><a HREF="#Library_std_shared_ptr">11.4.4 shared_ptr smart pointer</a>
<ul>
<li><a HREF="#Library_shared_ptr_basics">11.4.4.1 shared_ptr basics</a></li>
<li><a HREF="#Library_shared_ptr_inheritance">11.4.4.2 shared_ptr and
 inheritance</a></li>
<li><a HREF="#Library_shared_ptr_overloading">11.4.4.3 shared_ptr and
 method overloading</a></li>
<li><a HREF="#Library_shared_ptr_templates">11.4.4.4 shared_ptr and
 templates</a></li>
<li><a HREF="#Library_shared_ptr_directors">11.4.4.5 shared_ptr and
 directors</a></li>
</ul>
</li>
<li><a HREF="#Library_std_auto_ptr">11.4.5 auto_ptr smart pointer</a></li>
</ul>
</li>
<li><a HREF="#Library_nn16">11.5 Utility Libraries</a>
<ul>
<li><a HREF="#Library_nn17">11.5.1 exception.i</a></li>
</ul>
</li>
</ul>
<b><a HREF="#Arguments">12 Argument Handling</a></b>
<ul>
<li><a HREF="#Arguments_nn2">12.1 The typemaps.i library</a>
<ul>
<li><a HREF="#Arguments_nn3">12.1.1 Introduction</a></li>
<li><a HREF="#Arguments_nn4">12.1.2 Input parameters</a></li>
<li><a HREF="#Arguments_nn5">12.1.3 Output parameters</a></li>
<li><a HREF="#Arguments_nn6">12.1.4 Input/Output parameters</a></li>
<li><a HREF="#Arguments_nn7">12.1.5 Using different names</a></li>
</ul>
</li>
<li><a HREF="#Arguments_nn8">12.2 Applying constraints to input values</a>
<ul>
<li><a HREF="#Arguments_nn9">12.2.1 Simple constraint example</a></li>
<li><a HREF="#Arguments_nn10">12.2.2 Constraint methods</a></li>
<li><a HREF="#Arguments_nn11">12.2.3 Applying constraints to new
 datatypes</a></li>
</ul>
</li>
</ul>
<b><a HREF="#Typemaps">13 Typemaps</a></b>
<ul>
<li><a HREF="#Typemaps_nn2">13.1 Introduction</a>
<ul>
<li><a HREF="#Typemaps_nn3">13.1.1 Type conversion</a></li>
<li><a HREF="#Typemaps_nn4">13.1.2 Typemaps</a></li>
<li><a HREF="#Typemaps_nn5">13.1.3 Pattern matching</a></li>
<li><a HREF="#Typemaps_nn6">13.1.4 Reusing typemaps</a></li>
<li><a HREF="#Typemaps_nn7">13.1.5 What can be done with typemaps?</a></li>
<li><a HREF="#Typemaps_nn8">13.1.6 What can't be done with typemaps?</a></li>
<li><a HREF="#Typemaps_aspects">13.1.7 Similarities to Aspect Oriented
 Programming</a></li>
<li><a HREF="#Typemaps_nn9">13.1.8 The rest of this chapter</a></li>
</ul>
</li>
<li><a HREF="#Typemaps_nn10">13.2 Typemap specifications</a>
<ul>
<li><a HREF="#Typemaps_defining">13.2.1 Defining a typemap</a></li>
<li><a HREF="#Typemaps_nn12">13.2.2 Typemap scope</a></li>
<li><a HREF="#Typemaps_nn13">13.2.3 Copying a typemap</a></li>
<li><a HREF="#Typemaps_nn14">13.2.4 Deleting a typemap</a></li>
<li><a HREF="#Typemaps_nn15">13.2.5 Placement of typemaps</a></li>
</ul>
</li>
<li><a HREF="#Typemaps_pattern_matching">13.3 Pattern matching rules</a>
<ul>
<li><a HREF="#Typemaps_nn17">13.3.1 Basic matching rules</a></li>
<li><a HREF="#Typemaps_typedef_reductions">13.3.2 Typedef reductions
 matching</a></li>
<li><a HREF="#Typemaps_nn19">13.3.3 Default typemap matching rules</a></li>
<li><a HREF="#Typemaps_multi_argument_typemaps_patterns">13.3.4
 Multi-arguments typemaps</a></li>
<li><a HREF="#Typemaps_matching_template_comparison">13.3.5 Matching
 rules compared to C++ templates</a></li>
<li><a HREF="#Typemaps_debugging_search">13.3.6 Debugging typemap
 pattern matching</a></li>
</ul>
</li>
<li><a HREF="#Typemaps_nn21">13.4 Code generation rules</a>
<ul>
<li><a HREF="#Typemaps_nn22">13.4.1 Scope</a></li>
<li><a HREF="#Typemaps_nn23">13.4.2 Declaring new local variables</a></li>
<li><a HREF="#Typemaps_special_variables">13.4.3 Special variables</a></li>
<li><a HREF="#Typemaps_special_variable_macros">13.4.4 Special variable
 macros</a>
<ul>
<li><a HREF="#Typemaps_special_macro_descriptor">13.4.4.1
 $descriptor(type)</a></li>
<li><a HREF="#Typemaps_special_macro_typemap">13.4.4.2 $typemap(method,
 typepattern)</a></li>
</ul>
</li>
<li><a HREF="#Typemaps_special_variable_attributes">13.4.5 Special
 variables and typemap attributes</a></li>
<li><a HREF="#Typemaps_special_variables_and_macros">13.4.6 Special
 variables combined with special variable macros</a></li>
</ul>
</li>
<li><a HREF="#Typemaps_nn25">13.5 Common typemap methods</a>
<ul>
<li><a HREF="#Typemaps_nn26">13.5.1 &quot;in&quot; typemap</a></li>
<li><a HREF="#Typemaps_nn27">13.5.2 &quot;typecheck&quot; typemap</a></li>
<li><a HREF="#Typemaps_nn28">13.5.3 &quot;out&quot; typemap</a></li>
<li><a HREF="#Typemaps_nn29">13.5.4 &quot;arginit&quot; typemap</a></li>
<li><a HREF="#Typemaps_nn30">13.5.5 &quot;default&quot; typemap</a></li>
<li><a HREF="#Typemaps_nn31">13.5.6 &quot;check&quot; typemap</a></li>
<li><a HREF="#Typemaps_nn32">13.5.7 &quot;argout&quot; typemap</a></li>
<li><a HREF="#Typemaps_nn33">13.5.8 &quot;freearg&quot; typemap</a></li>
<li><a HREF="#Typemaps_nn34">13.5.9 &quot;newfree&quot; typemap</a></li>
<li><a HREF="#Typemaps_ret">13.5.10 &quot;ret&quot; typemap</a></li>
<li><a HREF="#Typemaps_nn35">13.5.11 &quot;memberin&quot; typemap</a></li>
<li><a HREF="#Typemaps_nn36">13.5.12 &quot;varin&quot; typemap</a></li>
<li><a HREF="#Typemaps_nn37">13.5.13 &quot;varout&quot; typemap</a></li>
<li><a HREF="#Typemaps_throws_typemap">13.5.14 &quot;throws&quot; typemap</a></li>
</ul>
</li>
<li><a HREF="#Typemaps_nn39">13.6 Some typemap examples</a>
<ul>
<li><a HREF="#Typemaps_nn40">13.6.1 Typemaps for arrays</a></li>
<li><a HREF="#Typemaps_nn41">13.6.2 Implementing constraints with
 typemaps</a></li>
</ul>
</li>
<li><a HREF="#Typemaps_nn43">13.7 Typemaps for multiple target languages</a>
</li>
<li><a HREF="#Typemaps_optimal">13.8 Optimal code generation when
 returning by value</a></li>
<li><a HREF="#Typemaps_multi_argument_typemaps">13.9 Multi-argument
 typemaps</a></li>
<li><a HREF="#Typemaps_warnings">13.10 Typemap warnings</a></li>
<li><a HREF="#Typemaps_fragments">13.11 Typemap fragments</a>
<ul>
<li><a HREF="#Typemaps_fragment_type_specialization">13.11.1 Fragment
 type specialization</a></li>
<li><a HREF="#Typemaps_automatic_specialization">13.11.2 Fragments and
 automatic typemap specialization</a></li>
</ul>
</li>
<li><a HREF="#Typemaps_runtime_type_checker">13.12 The run-time type
 checker</a>
<ul>
<li><a HREF="#Typemaps_nn45">13.12.1 Implementation</a></li>
<li><a HREF="#Typemaps_runtime_type_checker_usage">13.12.2 Usage</a></li>
</ul>
</li>
<li><a HREF="#Typemaps_overloading">13.13 Typemaps and overloading</a>
<ul>
<li><a HREF="#Typemaps_typecheck_pointer">13.13.1 SWIG_TYPECHECK_POINTER
 precedence level and the typecheck typemap</a></li>
</ul>
</li>
<li><a HREF="#Typemaps_nn48">13.14 More about %apply and %clear</a></li>
<li><a HREF="#Typemaps_nn47">13.15 Passing data between typemaps</a></li>
<li><a HREF="#Typemaps_nn52">13.16 C++ &quot;this&quot; pointer</a></li>
<li><a HREF="#Typemaps_nn51">13.17 Where to go for more information?</a></li>
</ul>
<b><a HREF="#Customization">14 Customization Features</a></b>
<ul>
<li><a HREF="#Customization_exception">14.1 Exception handling with
 %exception</a>
<ul>
<li><a HREF="#Customization_nn3">14.1.1 Handling exceptions in C code</a>
</li>
<li><a HREF="#Customization_nn4">14.1.2 Exception handling with
 longjmp()</a></li>
<li><a HREF="#Customization_nn5">14.1.3 Handling C++ exceptions</a></li>
<li><a HREF="#Customization_allowexcept">14.1.4 Exception handlers for
 variables</a></li>
<li><a HREF="#Customization_nn6">14.1.5 Defining different exception
 handlers</a></li>
<li><a HREF="#Customization_exception_special_variables">14.1.6 Special
 variables for %exception</a></li>
<li><a HREF="#Customization_nn7">14.1.7 Using The SWIG exception library</a>
</li>
</ul>
</li>
<li><a HREF="#Customization_ownership">14.2 Object ownership and
 %newobject</a></li>
<li><a HREF="#Customization_features">14.3 Features and the %feature
 directive</a>
<ul>
<li><a HREF="#Customization_feature_attributes">14.3.1 Feature
 attributes</a></li>
<li><a HREF="#Customization_feature_flags">14.3.2 Feature flags</a></li>
<li><a HREF="#Customization_clearing_features">14.3.3 Clearing features</a>
</li>
<li><a HREF="#Customization_features_default_args">14.3.4 Features and
 default arguments</a></li>
<li><a HREF="#Customization_features_example">14.3.5 Feature example</a></li>
</ul>
</li>
</ul>
<b><a HREF="#Contract">15 Contracts</a></b>
<ul>
<li><a HREF="#Contract_nn2">15.1 The %contract directive</a></li>
<li><a HREF="#Contract_nn3">15.2 %contract and classes</a></li>
<li><a HREF="#Contract_nn4">15.3 Constant aggregation and
 %aggregate_check</a></li>
<li><a HREF="#Contract_nn5">15.4 Notes</a></li>
</ul>
<b><a HREF="#Varargs">16 Variable Length Arguments</a></b>
<ul>
<li><a HREF="#Varargs_nn2">16.1 Introduction</a></li>
<li><a HREF="#Varargs_nn3">16.2 The Problem</a></li>
<li><a HREF="#Varargs_nn4">16.3 Default varargs support</a></li>
<li><a HREF="#Varargs_nn5">16.4 Argument replacement using %varargs</a></li>
<li><a HREF="#Varargs_nn6">16.5 Varargs and typemaps</a></li>
<li><a HREF="#Varargs_nn7">16.6 Varargs wrapping with libffi</a></li>
<li><a HREF="#Varargs_nn8">16.7 Wrapping of va_list</a></li>
<li><a HREF="#Varargs_nn9">16.8 C++ Issues</a></li>
<li><a HREF="#Varargs_nn10">16.9 Discussion</a></li>
</ul>
<b><a HREF="#Doxygen">17 SWIG and Doxygen Translation</a></b>
<ul>
<li><a HREF="#Doxygen_translation_overview">17.1 Doxygen translation
 overview</a></li>
<li><a HREF="#Doxygen_file_preparation">17.2 Preparations</a>
<ul>
<li><a HREF="#Doxygen_running_swig">17.2.1 Enabling Doxygen translation</a>
</li>
<li><a HREF="#Doxygen_features">17.2.2 Doxygen-specific %feature
 directives</a>
<ul>
<li><a HREF="#Doxygen_notranslate">17.2.2.1 doxygen:notranslate</a></li>
<li><a HREF="#Doxygen_alias">17.2.2.2 doxygen:alias:&lt;command-name&gt;</a></li>
<li><a HREF="#Doxygen_ignore">17.2.2.3 doxygen:ignore:&lt;command-name&gt;</a></li>
<li><a HREF="#Doxygen_nolinktranslate">17.2.2.4 doxygen:nolinktranslate</a>
</li>
<li><a HREF="#Doxygen_nostripparams">17.2.2.5 doxygen:nostripparams</a></li>
</ul>
</li>
<li><a HREF="#Doxygen_additional_options">17.2.3 Additional command line
 options</a></li>
</ul>
</li>
<li><a HREF="#Doxygen_to_javadoc">17.3 Doxygen to Javadoc</a>
<ul>
<li><a HREF="#Doxygen_basic_example">17.3.1 Basic example</a></li>
<li><a HREF="#Doxygen_javadoc_tags">17.3.2 Javadoc tags</a></li>
<li><a HREF="#Doxygen_unsupported_tags">17.3.3 Unsupported tags</a></li>
<li><a HREF="#Doxygen_further_details">17.3.4 Further details</a></li>
</ul>
</li>
<li><a HREF="#Doxygen_to_pydoc">17.4 Doxygen to Pydoc</a>
<ul>
<li><a HREF="#Doxygen_python_basic_example">17.4.1 Basic example</a></li>
<li><a HREF="#Doxygen_pydoc_tags">17.4.2 Pydoc translator</a></li>
<li><a HREF="#Doxygen_python_unsupported_tags">17.4.3 Unsupported tags</a>
</li>
<li><a HREF="#Doxygen_python_further_details">17.4.4 Further details</a></li>
</ul>
</li>
<li><a HREF="#Doxygen_troubleshooting">17.5 Troubleshooting</a>
<ul>
<li><a HREF="#troubleshooting_ifndef">17.5.1 Problem with conditional
 compilation</a></li>
</ul>
</li>
<li><a HREF="#Doxygen_developer_details">17.6 Developer information</a>
<ul>
<li><a HREF="#Doxygen_translator_design">17.6.1 Doxygen translator
 design</a></li>
<li><a HREF="#Doxygen_debugging_commands">17.6.2 Debugging the Doxygen
 parser and translator</a></li>
<li><a HREF="#Doxygen_tests">17.6.3 Tests</a></li>
</ul>
</li>
<li><a HREF="#Doxygen_language_extension">17.7 Extending to other
 languages</a></li>
</ul>
<b><a HREF="#Warnings">18 Warning Messages</a></b>
<ul>
<li><a HREF="#Warnings_nn2">18.1 Introduction</a></li>
<li><a HREF="#Warnings_suppression">18.2 Warning message suppression</a></li>
<li><a HREF="#Warnings_nn4">18.3 Enabling extra warnings</a></li>
<li><a HREF="#Warnings_nn5">18.4 Issuing a warning message</a></li>
<li><a HREF="#Warnings_symbolic_symbols">18.5 Symbolic symbols</a></li>
<li><a HREF="#Warnings_nn6">18.6 Commentary</a></li>
<li><a HREF="#Warnings_nn7">18.7 Warnings as errors</a></li>
<li><a HREF="#Warnings_nn8">18.8 Message output format</a></li>
<li><a HREF="#Warnings_nn9">18.9 Warning number reference</a>
<ul>
<li><a HREF="#Warnings_nn10">18.9.1 Deprecated features (100-199)</a></li>
<li><a HREF="#Warnings_nn11">18.9.2 Preprocessor (200-299)</a></li>
<li><a HREF="#Warnings_nn12">18.9.3 C/C++ Parser (300-399)</a></li>
<li><a HREF="#Warnings_nn13">18.9.4 Types and typemaps (400-499)</a></li>
<li><a HREF="#Warnings_nn14">18.9.5 Code generation (500-559)</a></li>
<li><a HREF="#Warnings_doxygen">18.9.6 Doxygen comments (560-599)</a></li>
<li><a HREF="#Warnings_nn15">18.9.7 Language module specific (700-899)</a>
</li>
<li><a HREF="#Warnings_nn16">18.9.8 User defined (900-999)</a></li>
</ul>
</li>
<li><a HREF="#Warnings_nn17">18.10 History</a></li>
</ul>
<b><a HREF="#Modules">19 Working with Modules</a></b>
<ul>
<li><a HREF="#Modules_introduction">19.1 Modules Introduction</a></li>
<li><a HREF="#Modules_nn1">19.2 Basics</a></li>
<li><a HREF="#Modules_nn2">19.3 The SWIG runtime code</a></li>
<li><a HREF="#Modules_external_run_time">19.4 External access to the
 runtime</a></li>
<li><a HREF="#Modules_nn4">19.5 A word of caution about static libraries</a>
</li>
<li><a HREF="#Modules_nn5">19.6 References</a></li>
<li><a HREF="#Modules_nn6">19.7 Reducing the wrapper file size</a></li>
</ul>
<b><a HREF="#CCache">20 Using SWIG with ccache - ccache-swig(1) manpage</a>
</b>
<ul>
<li><a HREF="#CCache_nn2">20.1 NAME</a></li>
<li><a HREF="#CCache_nn3">20.2 SYNOPSIS</a></li>
<li><a HREF="#CCache_nn4">20.3 DESCRIPTION</a></li>
<li><a HREF="#CCache_nn5">20.4 OPTIONS SUMMARY</a></li>
<li><a HREF="#CCache_nn6">20.5 OPTIONS</a></li>
<li><a HREF="#CCache_nn7">20.6 INSTALLATION</a></li>
<li><a HREF="#CCache_nn8">20.7 EXTRA OPTIONS</a></li>
<li><a HREF="#CCache_nn9">20.8 ENVIRONMENT VARIABLES</a></li>
<li><a HREF="#CCache_nn10">20.9 CACHE SIZE MANAGEMENT</a></li>
<li><a HREF="#CCache_nn11">20.10 CACHE COMPRESSION</a></li>
<li><a HREF="#CCache_nn12">20.11 HOW IT WORKS</a></li>
<li><a HREF="#CCache_nn13">20.12 USING CCACHE WITH DISTCC</a></li>
<li><a HREF="#CCache_nn14">20.13 SHARING A CACHE</a></li>
<li><a HREF="#CCache_nn15">20.14 HISTORY</a></li>
<li><a HREF="#CCache_nn16">20.15 DIFFERENCES FROM COMPILERCACHE</a></li>
<li><a HREF="#CCache_nn17">20.16 CREDITS</a></li>
<li><a HREF="#CCache_nn18">20.17 AUTHOR</a></li>
</ul>
<b><a HREF="#Android">21 SWIG and Android</a></b>
<ul>
<li><a HREF="#Android_overview">21.1 Overview</a></li>
<li><a HREF="#Android_examples">21.2 Android examples</a>
<ul>
<li><a HREF="#Android_examples_intro">21.2.1 Examples introduction</a></li>
<li><a HREF="#Android_example_simple">21.2.2 Simple C example</a></li>
<li><a HREF="#Android_example_class">21.2.3 C++ class example</a></li>
<li><a HREF="#Android_examples_other">21.2.4 Other examples</a></li>
</ul>
</li>
<li><a HREF="#Android_stl">21.3 C++ STL</a></li>
</ul>
<b><a HREF="#CSharp">22 SWIG and C#</a></b>
<ul>
<li><a HREF="#CSharp_introduction">22.1 Introduction</a>
<ul>
<li><a HREF="#CSharp_introduction_swig2_compatibility">22.1.1 SWIG 2
 Compatibility</a></li>
<li><a HREF="#CSharp_commandline">22.1.2 Additional command line options</a>
</li>
</ul>
</li>
<li><a HREF="#CSharp_differences_java">22.2 Differences to the Java
 module</a></li>
<li><a HREF="#CSharp_void_pointers">22.3 Void pointers</a></li>
<li><a HREF="#CSharp_arrays">22.4 C# Arrays</a>
<ul>
<li><a HREF="#CSharp_arrays_swig_library">22.4.1 The SWIG C arrays
 library</a></li>
<li><a HREF="#CSharp_arrays_pinvoke_default_array_marshalling">22.4.2
 Managed arrays using P/Invoke default array marshalling</a></li>
<li><a HREF="#CSharp_arrays_pinning">22.4.3 Managed arrays using pinning</a>
</li>
</ul>
</li>
<li><a HREF="#CSharp_exceptions">22.5 C# Exceptions</a>
<ul>
<li><a HREF="#CSharp_exception_example_check_typemap">22.5.1 C#
 exception example using &quot;check&quot; typemap</a></li>
<li><a HREF="#CSharp_exception_example_percent_exception">22.5.2 C#
 exception example using %exception</a></li>
<li><a HREF="#CSharp_exception_example_exception_specifications">22.5.3
 C# exception example using exception specifications</a></li>
<li><a HREF="#CSharp_custom_application_exception">22.5.4 Custom C#
 ApplicationException example</a></li>
</ul>
</li>
<li><a HREF="#CSharp_directors">22.6 C# Directors</a>
<ul>
<li><a HREF="#CSharp_directors_example">22.6.1 Directors example</a></li>
<li><a HREF="#CSharp_directors_implementation">22.6.2 Directors
 implementation</a></li>
<li><a HREF="#CSharp_director_caveats">22.6.3 Director caveats</a></li>
</ul>
</li>
<li><a HREF="#CSharp_multiple_modules">22.7 Multiple modules</a></li>
<li><a HREF="#CSharp_typemap_examples">22.8 C# Typemap examples</a>
<ul>
<li><a HREF="#CSharp_memory_management_member_variables">22.8.1 Memory
 management when returning references to member variables</a></li>
<li><a HREF="#CSharp_memory_management_objects">22.8.2 Memory management
 for objects passed to the C++ layer</a></li>
<li><a HREF="#CSharp_date_marshalling">22.8.3 Date marshalling using the
 csin typemap and associated attributes</a></li>
<li><a HREF="#CSharp_date_properties">22.8.4 A date example
 demonstrating marshalling of C# properties</a></li>
<li><a HREF="#CSharp_date_pre_post_directors">22.8.5 Date example
 demonstrating the 'pre' and 'post' typemap attributes for directors</a></li>
<li><a HREF="#CSharp_partial_classes">22.8.6 Turning proxy classes into
 partial classes</a></li>
<li><a HREF="#CSharp_sealed_proxy_class">22.8.7 Turning proxy classes
 into sealed classes</a></li>
<li><a HREF="#CSharp_extending_proxy_class">22.8.8 Extending proxy
 classes with additional C# code</a></li>
<li><a HREF="#CSharp_enum_underlying_type">22.8.9 Underlying type for
 enums</a></li>
</ul>
</li>
</ul>
<b><a HREF="#D">23 SWIG and D</a></b>
<ul>
<li><a HREF="#D_introduction">23.1 Introduction</a></li>
<li><a HREF="#D_command_line_invocation">23.2 Command line invocation</a>
</li>
<li><a HREF="#D_typemaps">23.3 Typemaps</a>
<ul>
<li><a HREF="#D_typemap_name_comparison">23.3.1 C# &lt;-&gt; D name comparison</a>
</li>
<li><a HREF="#D_ctype_imtype_dtype">23.3.2 ctype, imtype, dtype</a></li>
<li><a HREF="#D_in_out_directorin_direcetorout">23.3.3 in, out,
 directorin, directorout</a></li>
<li><a HREF="#D_din_dout_ddirectorin_ddirectorout">23.3.4 din, dout,
 ddirectorin, ddirectorout</a></li>
<li><a HREF="#D_typecheck_typemaps">23.3.5 typecheck typemaps</a></li>
<li><a HREF="#D_code_injection_typemaps">23.3.6 Code injection typemaps</a>
</li>
<li><a HREF="#D_special_variables">23.3.7 Special variable macros</a></li>
</ul>
</li>
<li><a HREF="#D_features">23.4 D and %feature</a></li>
<li><a HREF="#D_pragmas">23.5 Pragmas</a></li>
<li><a HREF="#D_exceptions">23.6 D Exceptions</a></li>
<li><a HREF="#D_directors">23.7 D Directors</a></li>
<li><a HREF="#D_other_features">23.8 Other features</a>
<ul>
<li><a HREF="#D_nspace">23.8.1 Extended namespace support (nspace)</a></li>
<li><a HREF="#D_native_pointer_support">23.8.2 Native pointer support</a>
</li>
<li><a HREF="#D_operator_overloading">23.8.3 Operator overloading</a></li>
<li><a HREF="#D_test_suite">23.8.4 Running the test-suite</a></li>
</ul>
</li>
<li><a HREF="#D_typemap_examples">23.9 D Typemap examples</a></li>
<li><a HREF="#D_planned_features">23.10 Work in progress and planned
 features</a></li>
</ul>
<b><a HREF="#Go">24 SWIG and Go</a></b>
<ul>
<li><a HREF="#Go_overview">24.1 Overview</a></li>
<li><a HREF="#Go_examples">24.2 Examples</a></li>
<li><a HREF="#Go_running_swig">24.3 Running SWIG with Go</a>
<ul>
<li><a HREF="#Go_commandline">24.3.1 Go-specific Commandline Options</a></li>
<li><a HREF="#Go_outputs">24.3.2 Generated Wrapper Files</a></li>
</ul>
</li>
<li><a HREF="#Go_basic_tour">24.4 A tour of basic C/C++ wrapping</a>
<ul>
<li><a HREF="#Go_package">24.4.1 Go Package Name</a></li>
<li><a HREF="#Go_names">24.4.2 Go Names</a></li>
<li><a HREF="#Go_constants">24.4.3 Go Constants</a></li>
<li><a HREF="#Go_enumerations">24.4.4 Go Enumerations</a></li>
<li><a HREF="#Go_classes">24.4.5 Go Classes</a>
<ul>
<li><a HREF="#Go_class_memory">24.4.5.1 Go Class Memory Management</a></li>
<li><a HREF="#Go_class_inheritance">24.4.5.2 Go Class Inheritance</a></li>
</ul>
</li>
<li><a HREF="#Go_templates">24.4.6 Go Templates</a></li>
<li><a HREF="#Go_director_classes">24.4.7 Go Director Classes</a>
<ul>
<li><a HREF="#Go_director_example_cpp_code">24.4.7.1 Example C++ code</a>
</li>
<li><a HREF="#Go_director_enable">24.4.7.2 Enable director feature</a></li>
<li><a HREF="#Go_director_ctor_dtor">24.4.7.3 Constructor and destructor</a>
</li>
<li><a HREF="#Go_director_overriding">24.4.7.4 Override virtual methods</a>
</li>
<li><a HREF="#Go_director_base_methods">24.4.7.5 Call base methods</a></li>
<li><a HREF="#Go_director_subclass">24.4.7.6 Subclass via embedding</a></li>
<li><a HREF="#Go_director_finalizer">24.4.7.7 Memory management with
 runtime.SetFinalizer</a></li>
<li><a HREF="#Go_director_foobargo_class">24.4.7.8 Complete FooBarGo
 example class</a></li>
</ul>
</li>
<li><a HREF="#Go_primitive_type_mappings">24.4.8 Default Go primitive
 type mappings</a></li>
<li><a HREF="#Go_output_arguments">24.4.9 Output arguments</a></li>
<li><a HREF="#Go_adding_additional_code">24.4.10 Adding additional go
 code</a></li>
<li><a HREF="#Go_typemaps">24.4.11 Go typemaps</a></li>
</ul>
</li>
</ul>
<b><a HREF="#Guile">25 SWIG and Guile</a></b>
<ul>
<li><a HREF="#Guile_nn1">25.1 Supported Guile Versions</a></li>
<li><a HREF="#Guile_nn2">25.2 Meaning of &quot;Module&quot;</a></li>
<li><a HREF="#Guile_nn3">25.3 Old GH Guile API</a></li>
<li><a HREF="#Guile_nn4">25.4 Linkage</a>
<ul>
<li><a HREF="#Guile_nn5">25.4.1 Simple Linkage</a></li>
<li><a HREF="#Guile_nn6">25.4.2 Passive Linkage</a></li>
<li><a HREF="#Guile_nn7">25.4.3 Native Guile Module Linkage</a></li>
<li><a HREF="#Guile_nn8">25.4.4 Old Auto-Loading Guile Module Linkage</a>
</li>
<li><a HREF="#Guile_nn9">25.4.5 Hobbit4D Linkage</a></li>
</ul>
</li>
<li><a HREF="#Guile_nn10">25.5 Underscore Folding</a></li>
<li><a HREF="#Guile_nn11">25.6 Typemaps</a></li>
<li><a HREF="#Guile_nn12">25.7 Representation of pointers as smobs</a>
<ul>
<li><a HREF="#Guile_nn14">25.7.1 Smobs</a></li>
<li><a HREF="#Guile_nn15">25.7.2 Garbage Collection</a></li>
</ul>
</li>
<li><a HREF="#Guile_nn16">25.8 Native Guile pointers</a></li>
<li><a HREF="#Guile_nn17">25.9 Exception Handling</a></li>
<li><a HREF="#Guile_nn18">25.10 Procedure documentation</a></li>
<li><a HREF="#Guile_nn19">25.11 Procedures with setters</a></li>
<li><a HREF="#Guile_nn20">25.12 GOOPS Proxy Classes</a>
<ul>
<li><a HREF="#Guile_nn21">25.12.1 Naming Issues</a></li>
<li><a HREF="#Guile_nn22">25.12.2 Linking</a></li>
</ul>
</li>
</ul>
<b><a HREF="#Java">26 SWIG and Java</a></b>
<ul>
<li><a HREF="#Java_overview">26.1 Overview</a></li>
<li><a HREF="#Java_preliminaries">26.2 Preliminaries</a>
<ul>
<li><a HREF="#Java_running_swig">26.2.1 Running SWIG</a></li>
<li><a HREF="#Java_commandline">26.2.2 Additional Commandline Options</a>
</li>
<li><a HREF="#Java_getting_right_headers">26.2.3 Getting the right
 header files</a></li>
<li><a HREF="#Java_compiling_dynamic">26.2.4 Compiling a dynamic module</a>
</li>
<li><a HREF="#Java_using_module">26.2.5 Using your module</a></li>
<li><a HREF="#Java_dynamic_linking_problems">26.2.6 Dynamic linking
 problems</a></li>
<li><a HREF="#Java_compilation_problems_cpp">26.2.7 Compilation problems
 and compiling with C++</a></li>
<li><a HREF="#Java_building_windows">26.2.8 Building on Windows</a>
<ul>
<li><a HREF="#Java_visual_studio">26.2.8.1 Running SWIG from Visual
 Studio</a></li>
<li><a HREF="#Java_nmake">26.2.8.2 Using NMAKE</a></li>
</ul>
</li>
</ul>
</li>
<li><a HREF="#Java_basic_tour">26.3 A tour of basic C/C++ wrapping</a>
<ul>
<li><a HREF="#Java_module_packages_classes">26.3.1 Modules, packages and
 generated Java classes</a></li>
<li><a HREF="#Java_functions">26.3.2 Functions</a></li>
<li><a HREF="#Java_global_variables">26.3.3 Global variables</a></li>
<li><a HREF="#Java_constants">26.3.4 Constants</a></li>
<li><a HREF="#Java_enumerations">26.3.5 Enumerations</a>
<ul>
<li><a HREF="#Java_anonymous_enums">26.3.5.1 Anonymous enums</a></li>
<li><a HREF="#Java_typesafe_enums">26.3.5.2 Typesafe enums</a></li>
<li><a HREF="#Java_proper_enums">26.3.5.3 Proper Java enums</a></li>
<li><a HREF="#Java_typeunsafe_enums">26.3.5.4 Type unsafe enums</a></li>
<li><a HREF="#Java_simple_enums">26.3.5.5 Simple enums</a></li>
</ul>
</li>
<li><a HREF="#Java_pointers">26.3.6 Pointers</a></li>
<li><a HREF="#Java_structures">26.3.7 Structures</a></li>
<li><a HREF="#Java_classes">26.3.8 C++ classes</a></li>
<li><a HREF="#Java_inheritance">26.3.9 C++ inheritance</a></li>
<li><a HREF="#Java_pointers_refs_arrays">26.3.10 Pointers, references,
 arrays and pass by value</a>
<ul>
<li><a HREF="#Java_null_pointers">26.3.10.1 Null pointers</a></li>
</ul>
</li>
<li><a HREF="#Java_overloaded_functions">26.3.11 C++ overloaded
 functions</a></li>
<li><a HREF="#Java_default_arguments">26.3.12 C++ default arguments</a></li>
<li><a HREF="#Java_namespaces">26.3.13 C++ namespaces</a></li>
<li><a HREF="#Java_templates">26.3.14 C++ templates</a></li>
<li><a HREF="#Java_smart_pointers">26.3.15 C++ Smart Pointers</a>
<ul>
<li><a HREF="#Java_smart_pointers_shared_ptr">26.3.15.1 The shared_ptr
 Smart Pointer</a></li>
<li><a HREF="#Java_smart_pointers_generic">26.3.15.2 Generic Smart
 Pointers</a></li>
</ul>
</li>
</ul>
</li>
<li><a HREF="#Java_further_details">26.4 Further details on the
 generated Java classes</a>
<ul>
<li><a HREF="#Java_imclass">26.4.1 The intermediary JNI class</a>
<ul>
<li><a HREF="#Java_imclass_pragmas">26.4.1.1 The intermediary JNI class
 pragmas</a></li>
</ul>
</li>
<li><a HREF="#Java_module_class">26.4.2 The Java module class</a>
<ul>
<li><a HREF="#Java_module_class_pragmas">26.4.2.1 The Java module class
 pragmas</a></li>
</ul>
</li>
<li><a HREF="#Java_proxy_classes">26.4.3 Java proxy classes</a>
<ul>
<li><a HREF="#Java_memory_management">26.4.3.1 Memory management</a></li>
<li><a HREF="#Java_inheritance_mirroring">26.4.3.2 Inheritance</a></li>
<li><a HREF="#Java_proxy_classes_gc">26.4.3.3 Proxy classes and garbage
 collection</a></li>
<li><a HREF="#Java_pgcpp">26.4.3.4 The premature garbage collection
 prevention parameter for proxy class marshalling</a></li>
<li><a HREF="#Java_multithread_libraries">26.4.3.5 Single threaded
 applications and thread safety</a></li>
</ul>
</li>
<li><a HREF="#Java_type_wrapper_classes">26.4.4 Type wrapper classes</a></li>
<li><a HREF="#Java_enum_classes">26.4.5 Enum classes</a>
<ul>
<li><a HREF="#Java_typesafe_enums_classes">26.4.5.1 Typesafe enum
 classes</a></li>
<li><a HREF="#Java_proper_enums_classes">26.4.5.2 Proper Java enum
 classes</a></li>
<li><a HREF="#Java_typeunsafe_enums_classes">26.4.5.3 Type unsafe enum
 classes</a></li>
</ul>
</li>
<li><a HREF="#Java_interfaces">26.4.6 Interfaces</a></li>
</ul>
</li>
<li><a HREF="#Java_directors">26.5 Cross language polymorphism using
 directors</a>
<ul>
<li><a HREF="#Java_enabling_directors">26.5.1 Enabling directors</a></li>
<li><a HREF="#Java_directors_classes">26.5.2 Director classes</a></li>
<li><a HREF="#Java_directors_overhead">26.5.3 Overhead and code bloat</a>
</li>
<li><a HREF="#Java_directors_example">26.5.4 Simple directors example</a>
</li>
<li><a HREF="#Java_directors_threading">26.5.5 Director threading issues</a>
</li>
<li><a HREF="#Java_directors_performance">26.5.6 Director performance
 tuning</a></li>
<li><a HREF="#Java_exceptions_from_directors">26.5.7 Java exceptions
 from directors</a>
<ul>
<li><a HREF="#Java_customizing_director_exceptions">26.5.7.1 Customizing
 director exceptions</a></li>
</ul>
</li>
</ul>
</li>
<li><a HREF="#Java_allprotected">26.6 Accessing protected members</a></li>
<li><a HREF="#Java_common_customization">26.7 Common customization
 features</a>
<ul>
<li><a HREF="#Java_helper_functions">26.7.1 C/C++ helper functions</a></li>
<li><a HREF="#Java_class_extension">26.7.2 Class extension with %extend</a>
</li>
<li><a HREF="#Java_proxycode">26.7.3 Class extension with %proxycode</a></li>
<li><a HREF="#Java_exception_handling">26.7.4 Exception handling with
 %exception and %javaexception</a></li>
<li><a HREF="#Java_method_access">26.7.5 Method access with
 %javamethodmodifiers</a></li>
</ul>
</li>
<li><a HREF="#Java_tips_techniques">26.8 Tips and techniques</a>
<ul>
<li><a HREF="#Java_input_output_parameters">26.8.1 Input and output
 parameters using primitive pointers and references</a></li>
<li><a HREF="#Java_simple_pointers">26.8.2 Simple pointers</a></li>
<li><a HREF="#Java_c_arrays">26.8.3 Wrapping C arrays with Java arrays</a>
</li>
<li><a HREF="#Java_unbounded_c_arrays">26.8.4 Unbounded C Arrays</a></li>
<li><a HREF="#Java_binary_char">26.8.5 Binary data vs Strings</a></li>
<li><a HREF="#Java_heap_allocations">26.8.6 Overriding new and delete to
 allocate from Java heap</a></li>
</ul>
</li>
<li><a HREF="#Java_typemaps">26.9 Java typemaps</a>
<ul>
<li><a HREF="#Java_default_primitive_type_mappings">26.9.1 Default
 primitive type mappings</a></li>
<li><a HREF="#Java_default_non_primitive_typemaps">26.9.2 Default
 typemaps for non-primitive types</a></li>
<li><a HREF="#Java_jvm64">26.9.3 Sixty four bit JVMs</a></li>
<li><a HREF="#Java_what_is_typemap">26.9.4 What is a typemap?</a></li>
<li><a HREF="#Java_typemaps_c_to_java_types">26.9.5 Typemaps for mapping
 C/C++ types to Java types</a></li>
<li><a HREF="#Java_typemap_attributes">26.9.6 Java typemap attributes</a>
</li>
<li><a HREF="#Java_special_variables">26.9.7 Java special variables</a></li>
<li><a HREF="#Java_typemaps_for_c_and_cpp">26.9.8 Typemaps for both C
 and C++ compilation</a></li>
<li><a HREF="#Java_code_typemaps">26.9.9 Java code typemaps</a></li>
<li><a HREF="#Java_directors_typemaps">26.9.10 Director specific
 typemaps</a></li>
</ul>
</li>
<li><a HREF="#Java_typemap_examples">26.10 Typemap Examples</a>
<ul>
<li><a HREF="#Java_simpler_enum_classes">26.10.1 Simpler Java enums for
 enums without initializers</a></li>
<li><a HREF="#Java_exception_typemap">26.10.2 Handling C++ exception
 specifications as Java exceptions</a></li>
<li><a HREF="#Java_nan_exception_typemap">26.10.3 NaN Exception -
 exception handling for a particular type</a></li>
<li><a HREF="#Java_converting_java_string_arrays">26.10.4 Converting
 Java String arrays to char **</a></li>
<li><a HREF="#Java_expanding_java_object">26.10.5 Expanding a Java
 object to multiple arguments</a></li>
<li><a HREF="#Java_using_typemaps_return_arguments">26.10.6 Using
 typemaps to return arguments</a></li>
<li><a HREF="#Java_adding_downcasts">26.10.7 Adding Java downcasts to
 polymorphic return types</a></li>
<li><a HREF="#Java_adding_equals_method">26.10.8 Adding an equals method
 to the Java classes</a></li>
<li><a HREF="#Java_void_pointers">26.10.9 Void pointers and a common
 Java base class</a></li>
<li><a HREF="#Java_struct_pointer_pointer">26.10.10 Struct pointer to
 pointer</a></li>
<li><a HREF="#Java_memory_management_member_variables">26.10.11 Memory
 management when returning references to member variables</a></li>
<li><a HREF="#Java_memory_management_objects">26.10.12 Memory management
 for objects passed to the C++ layer</a></li>
<li><a HREF="#Java_date_marshalling">26.10.13 Date marshalling using the
 javain typemap and associated attributes</a></li>
</ul>
</li>
<li><a HREF="#Java_directors_faq">26.11 Living with Java Directors</a></li>
<li><a HREF="#Java_odds_ends">26.12 Odds and ends</a>
<ul>
<li><a HREF="#Java_javadoc_comments">26.12.1 JavaDoc comments</a></li>
<li><a HREF="#Java_functional_interface">26.12.2 Functional interface
 without proxy classes</a></li>
<li><a HREF="#Java_using_own_jni_functions">26.12.3 Using your own JNI
 functions</a></li>
<li><a HREF="#Java_performance">26.12.4 Performance concerns and hints</a>
</li>
<li><a HREF="#Java_debugging">26.12.5 Debugging</a></li>
</ul>
</li>
<li><a HREF="#Java_examples">26.13 Java Examples</a></li>
</ul>
<b><a HREF="#Javascript">27 SWIG and Javascript</a></b>
<ul>
<li><a HREF="#Javascript_overview">27.1 Overview</a></li>
<li><a HREF="#Javascript_preliminaries">27.2 Preliminaries</a>
<ul>
<li><a HREF="#Javascript_running_swig">27.2.1 Running SWIG</a></li>
<li><a HREF="#Javascript_running_tests_examples">27.2.2 Running Tests
 and Examples</a></li>
<li><a HREF="#Javascript_known_issues">27.2.3 Known Issues</a></li>
</ul>
</li>
<li><a HREF="#Javascript_integration">27.3 Integration</a>
<ul>
<li><a HREF="#Javascript_node_extensions">27.3.1 Creating node.js
 Extensions</a>
<ul>
<li><a HREF="#Javascript_troubleshooting">27.3.1.1 Troubleshooting</a></li>
</ul>
</li>
<li><a HREF="#Javascript_embedded_webkit">27.3.2 Embedded Webkit</a>
<ul>
<li><a HREF="#Javascript_osx">27.3.2.1 Mac OS X</a></li>
<li><a HREF="#Javascript_gtk">27.3.2.2 GTK</a></li>
</ul>
</li>
<li><a HREF="#Javascript_applications_webkit">27.3.3 Creating
 Applications with node-webkit</a></li>
</ul>
</li>
<li><a HREF="#Javascript_examples">27.4 Examples</a>
<ul>
<li><a HREF="#Javascript_simple_example">27.4.1 Simple</a></li>
<li><a HREF="#Javascript_class_example">27.4.2 Class</a></li>
</ul>
</li>
<li><a HREF="#Javascript_implementation">27.5 Implementation</a>
<ul>
<li><a HREF="#Javascript_source_code">27.5.1 Source Code</a></li>
<li><a HREF="#Javascript_code_templates">27.5.2 Code Templates</a></li>
<li><a HREF="#Javascript_emitter">27.5.3 Emitter</a></li>
<li><a HREF="#Javascript_emitter_states">27.5.4 Emitter states</a></li>
<li><a HREF="#Javascript_jsc_exceptions">27.5.5 Handling Exceptions in
 JavascriptCore</a></li>
</ul>
</li>
</ul>
<b><a HREF="#Lua">28 SWIG and Lua</a></b>
<ul>
<li><a HREF="#Lua_nn2">28.1 Preliminaries</a></li>
<li><a HREF="#Lua_nn3">28.2 Running SWIG</a>
<ul>
<li><a HREF="#Lua_commandline">28.2.1 Additional command line options</a>
</li>
<li><a HREF="#Lua_nn4">28.2.2 Compiling and Linking and Interpreter</a></li>
<li><a HREF="#Lua_nn5">28.2.3 Compiling a dynamic module</a></li>
<li><a HREF="#Lua_nn6">28.2.4 Using your module</a></li>
</ul>
</li>
<li><a HREF="#Lua_nn7">28.3 A tour of basic C/C++ wrapping</a>
<ul>
<li><a HREF="#Lua_nn8">28.3.1 Modules</a></li>
<li><a HREF="#Lua_nn9">28.3.2 Functions</a></li>
<li><a HREF="#Lua_nn10">28.3.3 Global variables</a></li>
<li><a HREF="#Lua_nn11">28.3.4 Constants and enums</a>
<ul>
<li><a HREF="#Lua_nn13">28.3.4.1 Constants/enums and classes/structures</a>
</li>
</ul>
</li>
<li><a HREF="#Lua_nn12">28.3.5 Pointers</a></li>
<li><a HREF="#Lua_structures">28.3.6 Structures</a></li>
<li><a HREF="#Lua_nn14">28.3.7 C++ classes</a></li>
<li><a HREF="#Lua_nn15">28.3.8 C++ inheritance</a></li>
<li><a HREF="#Lua_nn16">28.3.9 Pointers, references, values, and arrays</a>
</li>
<li><a HREF="#Lua_nn17">28.3.10 C++ overloaded functions</a></li>
<li><a HREF="#Lua_nn18">28.3.11 C++ operators</a></li>
<li><a HREF="#Lua_nn19">28.3.12 Class extension with %extend</a></li>
<li><a HREF="#Lua_nn20">28.3.13 Using %newobject to release memory</a></li>
<li><a HREF="#Lua_nn21">28.3.14 C++ templates</a></li>
<li><a HREF="#Lua_nn22">28.3.15 C++ Smart Pointers</a></li>
<li><a HREF="#Lua_nn23">28.3.16 C++ Exceptions</a></li>
<li><a HREF="#Lua_namespaces">28.3.17 Namespaces</a>
<ul>
<li><a HREF="#Lua_nn27">28.3.17.1 Compatibility Note</a></li>
<li><a HREF="#Lua_nn29">28.3.17.2 Names</a></li>
<li><a HREF="#Lua_nn30">28.3.17.3 Inheritance</a></li>
</ul>
</li>
</ul>
</li>
<li><a HREF="#Lua_nn24">28.4 Typemaps</a>
<ul>
<li><a HREF="#Lua_nn25">28.4.1 What is a typemap?</a></li>
<li><a HREF="#Lua_nn26">28.4.2 Using typemaps</a></li>
<li><a HREF="#Lua_typemap_arrays">28.4.3 Typemaps and arrays</a></li>
<li><a HREF="#Lua_typemaps_ptr_ptr_functions">28.4.4 Typemaps and
 pointer-pointer functions</a></li>
</ul>
</li>
<li><a HREF="#Lua_writing_typemaps">28.5 Writing typemaps</a>
<ul>
<li><a HREF="#Lua_typemaps_write">28.5.1 Typemaps you can write</a></li>
<li><a HREF="#Lua_nn31">28.5.2 SWIG's Lua-C API</a></li>
</ul>
</li>
<li><a HREF="#Lua_nn32">28.6 Customization of your Bindings</a>
<ul>
<li><a HREF="#Lua_nn33">28.6.1 Writing your own custom wrappers</a></li>
<li><a HREF="#Lua_nn34">28.6.2 Adding additional Lua code</a></li>
</ul>
</li>
<li><a HREF="#Lua_nn35">28.7 Details on the Lua binding</a>
<ul>
<li><a HREF="#Lua_nn36">28.7.1 Binding global data into the module.</a></li>
<li><a HREF="#Lua_nn37">28.7.2 Userdata and Metatables</a></li>
<li><a HREF="#Lua_nn38">28.7.3 Memory management</a></li>
</ul>
</li>
</ul>
<b><a HREF="#Octave">29 SWIG and Octave</a></b>
<ul>
<li><a HREF="#Octave_nn2">29.1 Preliminaries</a></li>
<li><a HREF="#Octave_nn3">29.2 Running SWIG</a>
<ul>
<li><a HREF="#Octave_nn4">29.2.1 Command-line options</a></li>
<li><a HREF="#Octave_nn5">29.2.2 Compiling a dynamic module</a></li>
<li><a HREF="#Octave_nn6">29.2.3 Using your module</a></li>
</ul>
</li>
<li><a HREF="#Octave_nn7">29.3 A tour of basic C/C++ wrapping</a>
<ul>
<li><a HREF="#Octave_nn8">29.3.1 Modules</a></li>
<li><a HREF="#Octave_nn9">29.3.2 Functions</a></li>
<li><a HREF="#Octave_nn10">29.3.3 Global variables</a></li>
<li><a HREF="#Octave_nn11">29.3.4 Constants and enums</a></li>
<li><a HREF="#Octave_nn12">29.3.5 Pointers</a></li>
<li><a HREF="#Octave_nn13">29.3.6 Structures and C++ classes</a></li>
<li><a HREF="#Octave_nn15">29.3.7 C++ inheritance</a></li>
<li><a HREF="#Octave_nn17">29.3.8 C++ overloaded functions</a></li>
<li><a HREF="#Octave_nn18">29.3.9 C++ operators</a></li>
<li><a HREF="#Octave_nn19">29.3.10 Class extension with %extend</a></li>
<li><a HREF="#Octave_nn20">29.3.11 C++ templates</a></li>
<li><a HREF="#Octave_nn21">29.3.12 C++ Smart Pointers</a>
<ul>
<li><a HREF="#Octave_smart_pointers_shared_ptr">29.3.12.1 The shared_ptr
 Smart Pointer</a></li>
<li><a HREF="#Octave_smart_pointers_generic">29.3.12.2 Generic Smart
 Pointers</a></li>
</ul>
</li>
<li><a HREF="#Octave_nn22">29.3.13 Directors (calling Octave from C++
 code)</a></li>
<li><a HREF="#Octave_nn23">29.3.14 Threads</a></li>
<li><a HREF="#Octave_nn24">29.3.15 Memory management</a></li>
<li><a HREF="#Octave_nn25">29.3.16 STL support</a></li>
<li><a HREF="#Octave_nn26">29.3.17 Matrix typemaps</a></li>
</ul>
</li>
</ul>
<b><a HREF="#Perl5">30 SWIG and Perl5</a></b>
<ul>
<li><a HREF="#Perl5_nn2">30.1 Overview</a></li>
<li><a HREF="#Perl5_nn3">30.2 Preliminaries</a>
<ul>
<li><a HREF="#Perl5_nn4">30.2.1 Getting the right header files</a></li>
<li><a HREF="#Perl5_nn5">30.2.2 Compiling a dynamic module</a></li>
<li><a HREF="#Perl5_nn6">30.2.3 Building a dynamic module with MakeMaker</a>
</li>
<li><a HREF="#Perl5_nn7">30.2.4 Building a static version of Perl</a></li>
<li><a HREF="#Perl5_nn8">30.2.5 Using the module</a></li>
<li><a HREF="#Perl5_nn9">30.2.6 Compilation problems and compiling with
 C++</a></li>
<li><a HREF="#Perl5_nn10">30.2.7 Compiling for 64-bit platforms</a></li>
</ul>
</li>
<li><a HREF="#Perl5_nn11">30.3 Building Perl Extensions under Windows</a>
<ul>
<li><a HREF="#Perl5_nn12">30.3.1 Running SWIG from Developer Studio</a></li>
<li><a HREF="#Perl5_nn13">30.3.2 Using other compilers</a></li>
</ul>
</li>
<li><a HREF="#Perl5_nn14">30.4 The low-level interface</a>
<ul>
<li><a HREF="#Perl5_nn15">30.4.1 Functions</a></li>
<li><a HREF="#Perl5_nn16">30.4.2 Global variables</a></li>
<li><a HREF="#Perl5_nn17">30.4.3 Constants</a></li>
<li><a HREF="#Perl5_nn18">30.4.4 Pointers</a></li>
<li><a HREF="#Perl5_nn19">30.4.5 Structures</a></li>
<li><a HREF="#Perl5_nn20">30.4.6 C++ classes</a></li>
<li><a HREF="#Perl5_nn21">30.4.7 C++ classes and type-checking</a></li>
<li><a HREF="#Perl5_nn22">30.4.8 C++ overloaded functions</a></li>
<li><a HREF="#Perl5_nn23">30.4.9 Operators</a></li>
<li><a HREF="#Perl5_nn24">30.4.10 Modules and packages</a></li>
</ul>
</li>
<li><a HREF="#Perl5_nn25">30.5 Input and output parameters</a></li>
<li><a HREF="#Perl5_nn26">30.6 Exception handling</a></li>
<li><a HREF="#Perl5_nn27">30.7 Remapping datatypes with typemaps</a>
<ul>
<li><a HREF="#Perl5_nn28">30.7.1 A simple typemap example</a></li>
<li><a HREF="#Perl5_nn29">30.7.2 Perl5 typemaps</a></li>
<li><a HREF="#Perl5_nn30">30.7.3 Typemap variables</a></li>
<li><a HREF="#Perl5_nn31">30.7.4 Useful functions</a></li>
</ul>
</li>
<li><a HREF="#Perl5_nn32">30.8 Typemap Examples</a>
<ul>
<li><a HREF="#Perl5_nn33">30.8.1 Converting a Perl5 array to a char **</a>
</li>
<li><a HREF="#Perl5_nn34">30.8.2 Return values</a></li>
<li><a HREF="#Perl5_nn35">30.8.3 Returning values from arguments</a></li>
<li><a HREF="#Perl5_nn36">30.8.4 Accessing array structure members</a></li>
<li><a HREF="#Perl5_nn37">30.8.5 Turning Perl references into C pointers</a>
</li>
<li><a HREF="#Perl5_nn38">30.8.6 Pointer handling</a></li>
</ul>
</li>
<li><a HREF="#Perl5_nn39">30.9 Proxy classes</a>
<ul>
<li><a HREF="#Perl5_nn40">30.9.1 Preliminaries</a></li>
<li><a HREF="#Perl5_nn41">30.9.2 Structure and class wrappers</a></li>
<li><a HREF="#Perl5_nn42">30.9.3 Object Ownership</a></li>
<li><a HREF="#Perl5_nn43">30.9.4 Nested Objects</a></li>
<li><a HREF="#Perl5_nn44">30.9.5 Proxy Functions</a></li>
<li><a HREF="#Perl5_nn45">30.9.6 Inheritance</a></li>
<li><a HREF="#Perl5_nn46">30.9.7 Modifying the proxy methods</a></li>
</ul>
</li>
<li><a HREF="#Perl5_nn47">30.10 Adding additional Perl code</a></li>
<li><a HREF="#Perl5_directors">30.11 Cross language polymorphism</a>
<ul>
<li><a HREF="#Perl5_nn48">30.11.1 Enabling directors</a></li>
<li><a HREF="#Perl5_nn49">30.11.2 Director classes</a></li>
<li><a HREF="#Perl5_nn50">30.11.3 Ownership and object destruction</a></li>
<li><a HREF="#Perl5_nn51">30.11.4 Exception unrolling</a></li>
<li><a HREF="#Perl5_nn52">30.11.5 Overhead and code bloat</a></li>
<li><a HREF="#Perl5_nn53">30.11.6 Typemaps</a></li>
</ul>
</li>
</ul>
<b><a HREF="#Php">31 SWIG and PHP</a></b>
<ul>
<li><a HREF="#Php_nn1">31.1 Generating PHP Extensions</a>
<ul>
<li><a HREF="#Php_nn1_1">31.1.1 Building a loadable extension</a></li>
<li><a HREF="#Php_nn1_3">31.1.2 Using PHP Extensions</a></li>
</ul>
</li>
<li><a HREF="#Php_nn2">31.2 Basic PHP interface</a>
<ul>
<li><a HREF="#Php_nn2_1">31.2.1 Constants</a></li>
<li><a HREF="#Php_nn2_2">31.2.2 Global Variables</a></li>
<li><a HREF="#Php_nn2_3">31.2.3 Functions</a></li>
<li><a HREF="#Php_nn2_4">31.2.4 Overloading</a></li>
<li><a HREF="#Php_nn2_5">31.2.5 Pointers and References</a></li>
<li><a HREF="#Php_nn2_6">31.2.6 Structures and C++ classes</a>
<ul>
<li><a HREF="#Php_nn2_6_1">31.2.6.1 Using -noproxy</a></li>
<li><a HREF="#Php_nn2_6_2">31.2.6.2 Constructors and Destructors</a></li>
<li><a HREF="#Php_nn2_6_3">31.2.6.3 Static Member Variables</a></li>
<li><a HREF="#Php_nn2_6_4">31.2.6.4 Static Member Functions</a></li>
<li><a HREF="#Php_nn2_6_5">31.2.6.5 Specifying Implemented Interfaces</a>
</li>
</ul>
</li>
<li><a HREF="#Php_nn2_7">31.2.7 PHP Pragmas, Startup and Shutdown code</a>
</li>
</ul>
</li>
<li><a HREF="#Php_nn3">31.3 Cross language polymorphism</a>
<ul>
<li><a HREF="#Php_nn3_1">31.3.1 Enabling directors</a></li>
<li><a HREF="#Php_nn3_2">31.3.2 Director classes</a></li>
<li><a HREF="#Php_nn3_3">31.3.3 Ownership and object destruction</a></li>
<li><a HREF="#Php_nn3_4">31.3.4 Exception unrolling</a></li>
<li><a HREF="#Php_nn3_5">31.3.5 Overhead and code bloat</a></li>
<li><a HREF="#Php_nn3_6">31.3.6 Typemaps</a></li>
<li><a HREF="#Php_nn3_7">31.3.7 Miscellaneous</a></li>
</ul>
</li>
</ul>
<b><a HREF="#Python">32 SWIG and Python</a></b>
<ul>
<li><a HREF="#Python_nn2">32.1 Overview</a></li>
<li><a HREF="#Python_nn3">32.2 Preliminaries</a>
<ul>
<li><a HREF="#Python_nn4">32.2.1 Running SWIG</a></li>
<li><a HREF="#Python_nn6">32.2.2 Using distutils</a></li>
<li><a HREF="#Python_nn7">32.2.3 Hand compiling a dynamic module</a></li>
<li><a HREF="#Python_nn8">32.2.4 Static linking</a></li>
<li><a HREF="#Python_nn9">32.2.5 Using your module</a></li>
<li><a HREF="#Python_nn10">32.2.6 Compilation of C++ extensions</a></li>
<li><a HREF="#Python_nn11">32.2.7 Compiling for 64-bit platforms</a></li>
<li><a HREF="#Python_nn12">32.2.8 Building Python extensions under
 Windows</a></li>
<li><a HREF="#Python_commandline">32.2.9 Additional Python commandline
 options</a></li>
</ul>
</li>
<li><a HREF="#Python_nn13">32.3 A tour of basic C/C++ wrapping</a>
<ul>
<li><a HREF="#Python_nn14">32.3.1 Modules</a></li>
<li><a HREF="#Python_nn15">32.3.2 Functions</a></li>
<li><a HREF="#Python_nn16">32.3.3 Global variables</a></li>
<li><a HREF="#Python_nn17">32.3.4 Constants and enums</a></li>
<li><a HREF="#Python_nn18">32.3.5 Pointers</a></li>
<li><a HREF="#Python_nn19">32.3.6 Structures</a></li>
<li><a HREF="#Python_nn20">32.3.7 C++ classes</a></li>
<li><a HREF="#Python_nn21">32.3.8 C++ inheritance</a></li>
<li><a HREF="#Python_nn22">32.3.9 Pointers, references, values, and
 arrays</a></li>
<li><a HREF="#Python_nn23">32.3.10 C++ overloaded functions</a></li>
<li><a HREF="#Python_nn24">32.3.11 C++ operators</a></li>
<li><a HREF="#Python_nn25">32.3.12 C++ namespaces</a></li>
<li><a HREF="#Python_nn26">32.3.13 C++ templates</a></li>
<li><a HREF="#Python_nn27">32.3.14 C++ Smart Pointers</a>
<ul>
<li><a HREF="#Python_smart_pointers_shared_ptr">32.3.14.1 The shared_ptr
 Smart Pointer</a></li>
<li><a HREF="#Python_smart_pointers_generic">32.3.14.2 Generic Smart
 Pointers</a></li>
</ul>
</li>
<li><a HREF="#Python_nn27a">32.3.15 C++ reference counted objects</a></li>
</ul>
</li>
<li><a HREF="#Python_nn28">32.4 Further details on the Python class
 interface</a>
<ul>
<li><a HREF="#Python_nn29">32.4.1 Proxy classes</a></li>
<li><a HREF="#Python_builtin_types">32.4.2 Built-in Types</a>
<ul>
<li><a HREF="#Python_builtin_limitations">32.4.2.1 Limitations</a></li>
<li><a HREF="#Python_builtin_overloads">32.4.2.2 Operator overloads and
 slots -- use them!</a></li>
</ul>
</li>
<li><a HREF="#Python_nn30">32.4.3 Memory management</a></li>
</ul>
</li>
<li><a HREF="#Python_directors">32.5 Cross language polymorphism</a>
<ul>
<li><a HREF="#Python_nn33">32.5.1 Enabling directors</a></li>
<li><a HREF="#Python_nn34">32.5.2 Director classes</a></li>
<li><a HREF="#Python_nn35">32.5.3 Ownership and object destruction</a></li>
<li><a HREF="#Python_nn36">32.5.4 Exception unrolling</a></li>
<li><a HREF="#Python_nn37">32.5.5 Overhead and code bloat</a></li>
<li><a HREF="#Python_nn38">32.5.6 Typemaps</a></li>
<li><a HREF="#Python_nn39">32.5.7 Miscellaneous</a></li>
</ul>
</li>
<li><a HREF="#Python_nn40">32.6 Common customization features</a>
<ul>
<li><a HREF="#Python_nn41">32.6.1 C/C++ helper functions</a></li>
<li><a HREF="#Python_nn42">32.6.2 Adding additional Python code</a></li>
<li><a HREF="#Python_nn43">32.6.3 Class extension with %extend</a></li>
<li><a HREF="#Python_nn44">32.6.4 Exception handling with %exception</a></li>
<li><a HREF="#Python_optimization">32.6.5 Optimization options</a>
<ul>
<li><a HREF="#Python_fastproxy">32.6.5.1 -fastproxy</a></li>
</ul>
</li>
</ul>
</li>
<li><a HREF="#Python_nn45">32.7 Tips and techniques</a>
<ul>
<li><a HREF="#Python_nn46">32.7.1 Input and output parameters</a></li>
<li><a HREF="#Python_nn47">32.7.2 Simple pointers</a></li>
<li><a HREF="#Python_nn48">32.7.3 Unbounded C Arrays</a></li>
<li><a HREF="#Python_nn49">32.7.4 String handling</a></li>
<li><a HREF="#Python_default_args">32.7.5 Default arguments</a></li>
</ul>
</li>
<li><a HREF="#Python_nn53">32.8 Typemaps</a>
<ul>
<li><a HREF="#Python_nn54">32.8.1 What is a typemap?</a></li>
<li><a HREF="#Python_nn55">32.8.2 Python typemaps</a></li>
<li><a HREF="#Python_nn56">32.8.3 Typemap variables</a></li>
<li><a HREF="#Python_nn57">32.8.4 Useful Python Functions</a></li>
</ul>
</li>
<li><a HREF="#Python_nn58">32.9 Typemap Examples</a>
<ul>
<li><a HREF="#Python_nn59">32.9.1 Converting Python list to a char **</a>
</li>
<li><a HREF="#Python_nn60">32.9.2 Expanding a Python object into
 multiple arguments</a></li>
<li><a HREF="#Python_nn61">32.9.3 Using typemaps to return arguments</a></li>
<li><a HREF="#Python_nn62">32.9.4 Mapping Python tuples into small
 arrays</a></li>
<li><a HREF="#Python_nn63">32.9.5 Mapping sequences to C arrays</a></li>
<li><a HREF="#Python_nn64">32.9.6 Pointer handling</a></li>
<li><a HREF="#Python_memory_management_member_variables">32.9.7 Memory
 management when returning references to member variables</a></li>
</ul>
</li>
<li><a HREF="#Python_nn65">32.10 Docstring Features</a>
<ul>
<li><a HREF="#Python_nn66">32.10.1 Module docstring</a></li>
<li><a HREF="#Python_nn67">32.10.2 %feature(&quot;autodoc&quot;)</a>
<ul>
<li><a HREF="#Python_nn68">32.10.2.1 %feature(&quot;autodoc&quot;, &quot;0&quot;)</a></li>
<li><a HREF="#Python_nn69">32.10.2.2 %feature(&quot;autodoc&quot;, &quot;1&quot;)</a></li>
<li><a HREF="#Python_autodoc2">32.10.2.3 %feature(&quot;autodoc&quot;, &quot;2&quot;)</a></li>
<li><a HREF="#Python_autodoc3">32.10.2.4 %feature(&quot;autodoc&quot;, &quot;3&quot;)</a></li>
<li><a HREF="#Python_nn70">32.10.2.5 %feature(&quot;autodoc&quot;, &quot;docstring&quot;)</a>
</li>
</ul>
</li>
<li><a HREF="#Python_nn71">32.10.3 %feature(&quot;docstring&quot;)</a></li>
</ul>
</li>
<li><a HREF="#Python_nn72">32.11 Python Packages</a>
<ul>
<li><a HREF="#Python_modulepackage">32.11.1 Setting the Python package</a>
</li>
<li><a HREF="#Python_absrelimports">32.11.2 Absolute and relative
 imports</a></li>
<li><a HREF="#Python_absimport">32.11.3 Enforcing absolute import
 semantics</a></li>
<li><a HREF="#Python_importfrominit">32.11.4 Importing from __init__.py</a>
</li>
<li><a HREF="#Python_implicit_namespace_packages">32.11.5 Implicit
 namespace packages</a></li>
<li><a HREF="#Python_package_search">32.11.6 Location of modules</a>
<ul>
<li><a HREF="#Python_package_search_both_package_modules">32.11.6.1 Both
 modules in the same package</a></li>
<li><a HREF="#Python_package_search_both_global_modules">32.11.6.2 Both
 modules are global</a></li>
<li><a HREF="#Python_package_search_wrapper_split">32.11.6.3 Split
 modules custom configuration</a></li>
<li><a HREF="#Python_custom_module_import">32.11.6.4 More on customizing
 the module import code</a></li>
<li><a HREF="#Python_package_search_static">32.11.6.5 Statically linked
 C modules</a></li>
</ul>
</li>
</ul>
</li>
<li><a HREF="#Python_python3support">32.12 Python 3 Support</a>
<ul>
<li><a HREF="#Python_nn74">32.12.1 Function annotation</a></li>
<li><a HREF="#Python_nn75">32.12.2 Buffer interface</a></li>
<li><a HREF="#Python_nn76">32.12.3 Abstract base classes</a></li>
<li><a HREF="#Python_nn77">32.12.4 Byte string output conversion</a></li>
<li><a HREF="#Python_2_unicode">32.12.5 Python 2 Unicode</a></li>
</ul>
</li>
<li><a HREF="#Python_multithreaded">32.13 Support for Multithreaded
 Applications</a>
<ul>
<li><a HREF="#Python_thread_UI">32.13.1 UI for Enabling Multithreading
 Support</a></li>
<li><a HREF="#Python_thread_performance">32.13.2 Multithread Performance</a>
</li>
</ul>
</li>
</ul>
<b><a HREF="#R">33 SWIG and R</a></b>
<ul>
<li><a HREF="#R_nn2">33.1 Bugs</a></li>
<li><a HREF="#R_nn3">33.2 Using R and SWIG</a></li>
<li><a HREF="#R_nn4">33.3 Precompiling large R files</a></li>
<li><a HREF="#R_nn5">33.4 General policy</a></li>
<li><a HREF="#R_language_conventions">33.5 Language conventions</a></li>
<li><a HREF="#R_nn6">33.6 C++ classes</a>
<ul>
<li><a HREF="#R_class_examples">33.6.1 Examples</a></li>
</ul>
</li>
<li><a HREF="#R_nn7">33.7 Enumerations</a></li>
</ul>
<b><a HREF="#Ruby">34 SWIG and Ruby</a></b>
<ul>
<li><a HREF="#Ruby_nn2">34.1 Preliminaries</a>
<ul>
<li><a HREF="#Ruby_nn3">34.1.1 Running SWIG</a></li>
<li><a HREF="#Ruby_nn4">34.1.2 Getting the right header files</a></li>
<li><a HREF="#Ruby_nn5">34.1.3 Compiling a dynamic module</a></li>
<li><a HREF="#Ruby_nn6">34.1.4 Using your module</a></li>
<li><a HREF="#Ruby_nn7">34.1.5 Static linking</a></li>
<li><a HREF="#Ruby_nn8">34.1.6 Compilation of C++ extensions</a></li>
</ul>
</li>
<li><a HREF="#Ruby_nn9">34.2 Building Ruby Extensions under Windows
 95/NT</a>
<ul>
<li><a HREF="#Ruby_nn10">34.2.1 Running SWIG from Developer Studio</a></li>
</ul>
</li>
<li><a HREF="#Ruby_nn11">34.3 The Ruby-to-C/C++ Mapping</a>
<ul>
<li><a HREF="#Ruby_nn12">34.3.1 Modules</a></li>
<li><a HREF="#Ruby_nn13">34.3.2 Functions</a></li>
<li><a HREF="#Ruby_nn14">34.3.3 Variable Linking</a></li>
<li><a HREF="#Ruby_nn15">34.3.4 Constants</a></li>
<li><a HREF="#Ruby_nn16">34.3.5 Pointers</a></li>
<li><a HREF="#Ruby_nn17">34.3.6 Structures</a></li>
<li><a HREF="#Ruby_nn18">34.3.7 C++ classes</a></li>
<li><a HREF="#Ruby_nn19">34.3.8 C++ Inheritance</a></li>
<li><a HREF="#Ruby_nn20">34.3.9 C++ Overloaded Functions</a></li>
<li><a HREF="#Ruby_nn21">34.3.10 C++ Operators</a></li>
<li><a HREF="#Ruby_nn22">34.3.11 C++ namespaces</a></li>
<li><a HREF="#Ruby_nn23">34.3.12 C++ templates</a></li>
<li><a HREF="#Ruby_nn23_1">34.3.13 C++ Standard Template Library (STL)</a>
</li>
<li><a HREF="#Ruby_C_STL_Functors">34.3.14 C++ STL Functors</a></li>
<li><a HREF="#Ruby_C_Iterators">34.3.15 C++ STL Iterators</a></li>
<li><a HREF="#Ruby_nn24">34.3.16 C++ Smart Pointers</a>
<ul>
<li><a HREF="#Ruby_smart_pointers_shared_ptr">34.3.16.1 The shared_ptr
 Smart Pointer</a></li>
<li><a HREF="#Ruby_smart_pointers_generic">34.3.16.2 Generic Smart
 Pointers</a></li>
</ul>
</li>
<li><a HREF="#Ruby_nn25">34.3.17 Cross-Language Polymorphism</a>
<ul>
<li><a HREF="#Ruby_nn26">34.3.17.1 Exception Unrolling</a></li>
</ul>
</li>
</ul>
</li>
<li><a HREF="#Ruby_nn27">34.4 Naming</a>
<ul>
<li><a HREF="#Ruby_nn28">34.4.1 Defining Aliases</a></li>
<li><a HREF="#Ruby_nn29">34.4.2 Predicate Methods</a></li>
<li><a HREF="#Ruby_nn30">34.4.3 Bang Methods</a></li>
<li><a HREF="#Ruby_nn31">34.4.4 Getters and Setters</a></li>
</ul>
</li>
<li><a HREF="#Ruby_nn32">34.5 Input and output parameters</a></li>
<li><a HREF="#Ruby_nn33">34.6 Exception handling</a>
<ul>
<li><a HREF="#Ruby_nn34">34.6.1 Using the %exception directive</a></li>
<li><a HREF="#Ruby_nn34_2">34.6.2 Handling Ruby Blocks</a></li>
<li><a HREF="#Ruby_nn35">34.6.3 Raising exceptions</a></li>
<li><a HREF="#Ruby_nn36">34.6.4 Exception classes</a></li>
</ul>
</li>
<li><a HREF="#Ruby_nn37">34.7 Typemaps</a>
<ul>
<li><a HREF="#Ruby_nn38">34.7.1 What is a typemap?</a></li>
<li><a HREF="#Ruby_Typemap_scope">34.7.2 Typemap scope</a></li>
<li><a HREF="#Ruby_Copying_a_typemap">34.7.3 Copying a typemap</a></li>
<li><a HREF="#Ruby_Deleting_a_typemap">34.7.4 Deleting a typemap</a></li>
<li><a HREF="#Ruby_Placement_of_typemaps">34.7.5 Placement of typemaps</a>
</li>
<li><a HREF="#Ruby_nn39">34.7.6 Ruby typemaps</a>
<ul>
<li><a HREF="#Ruby_in_typemap">34.7.6.1 &quot;in&quot; typemap</a></li>
<li><a HREF="#Ruby_typecheck_typemap">34.7.6.2 &quot;typecheck&quot; typemap</a></li>
<li><a HREF="#Ruby_out_typemap">34.7.6.3 &quot;out&quot; typemap</a></li>
<li><a HREF="#Ruby_arginit_typemap">34.7.6.4 &quot;arginit&quot; typemap</a></li>
<li><a HREF="#Ruby_default_typemap">34.7.6.5 &quot;default&quot; typemap</a></li>
<li><a HREF="#Ruby_check_typemap">34.7.6.6 &quot;check&quot; typemap</a></li>
<li><a HREF="#Ruby_argout_typemap_">34.7.6.7 &quot;argout&quot; typemap</a></li>
<li><a HREF="#Ruby_freearg_typemap_">34.7.6.8 &quot;freearg&quot; typemap</a></li>
<li><a HREF="#Ruby_newfree_typemap">34.7.6.9 &quot;newfree&quot; typemap</a></li>
<li><a HREF="#Ruby_memberin_typemap">34.7.6.10 &quot;memberin&quot; typemap</a></li>
<li><a HREF="#Ruby_varin_typemap">34.7.6.11 &quot;varin&quot; typemap</a></li>
<li><a HREF="#Ruby_varout_typemap_">34.7.6.12 &quot;varout&quot; typemap</a></li>
<li><a HREF="#Ruby_throws_typemap">34.7.6.13 &quot;throws&quot; typemap</a></li>
<li><a HREF="#Ruby_directorin_typemap">34.7.6.14 directorin typemap</a></li>
<li><a HREF="#Ruby_directorout_typemap">34.7.6.15 directorout typemap</a>
</li>
<li><a HREF="#Ruby_directorargout_typemap">34.7.6.16 directorargout
 typemap</a></li>
<li><a HREF="#Ruby_ret_typemap">34.7.6.17 ret typemap</a></li>
<li><a HREF="#Ruby_globalin_typemap">34.7.6.18 globalin typemap</a></li>
</ul>
</li>
<li><a HREF="#Ruby_nn40">34.7.7 Typemap variables</a></li>
<li><a HREF="#Ruby_nn41">34.7.8 Useful Functions</a>
<ul>
<li><a HREF="#Ruby_nn42">34.7.8.1 C Datatypes to Ruby Objects</a></li>
<li><a HREF="#Ruby_nn43">34.7.8.2 Ruby Objects to C Datatypes</a></li>
<li><a HREF="#Ruby_nn44">34.7.8.3 Macros for VALUE</a></li>
<li><a HREF="#Ruby_nn45">34.7.8.4 Exceptions</a></li>
<li><a HREF="#Ruby_nn46">34.7.8.5 Iterators</a></li>
</ul>
</li>
<li><a HREF="#Ruby_nn47">34.7.9 Typemap Examples</a></li>
<li><a HREF="#Ruby_nn48">34.7.10 Converting a Ruby array to a char **</a>
</li>
<li><a HREF="#Ruby_nn49">34.7.11 Collecting arguments in a hash</a></li>
<li><a HREF="#Ruby_nn50">34.7.12 Pointer handling</a>
<ul>
<li><a HREF="#Ruby_nn51">34.7.12.1 Ruby Datatype Wrapping</a></li>
</ul>
</li>
<li><a HREF="#Ruby_nn52">34.7.13 Example: STL Vector to Ruby Array</a></li>
</ul>
</li>
<li><a HREF="#Ruby_nn65">34.8 Docstring Features</a>
<ul>
<li><a HREF="#Ruby_nn66">34.8.1 Module docstring</a></li>
<li><a HREF="#Ruby_nn67">34.8.2 %feature(&quot;autodoc&quot;)</a>
<ul>
<li><a HREF="#Ruby_nn68">34.8.2.1 %feature(&quot;autodoc&quot;, &quot;0&quot;)</a></li>
<li><a HREF="#Ruby_autodoc1">34.8.2.2 %feature(&quot;autodoc&quot;, &quot;1&quot;)</a></li>
<li><a HREF="#Ruby_autodoc2">34.8.2.3 %feature(&quot;autodoc&quot;, &quot;2&quot;)</a></li>
<li><a HREF="#Ruby_feature_autodoc3">34.8.2.4 %feature(&quot;autodoc&quot;, &quot;3&quot;)</a>
</li>
<li><a HREF="#Ruby_nn70">34.8.2.5 %feature(&quot;autodoc&quot;, &quot;docstring&quot;)</a></li>
</ul>
</li>
<li><a HREF="#Ruby_nn71">34.8.3 %feature(&quot;docstring&quot;)</a></li>
</ul>
</li>
<li><a HREF="#Ruby_nn53">34.9 Advanced Topics</a>
<ul>
<li><a HREF="#Ruby_operator_overloading">34.9.1 Operator overloading</a></li>
<li><a HREF="#Ruby_nn55">34.9.2 Creating Multi-Module Packages</a></li>
<li><a HREF="#Ruby_nn56">34.9.3 Specifying Mixin Modules</a></li>
</ul>
</li>
<li><a HREF="#Ruby_nn57">34.10 Memory Management</a>
<ul>
<li><a HREF="#Ruby_nn58">34.10.1 Mark and Sweep Garbage Collector</a></li>
<li><a HREF="#Ruby_nn59">34.10.2 Object Ownership</a></li>
<li><a HREF="#Ruby_nn60">34.10.3 Object Tracking</a></li>
<li><a HREF="#Ruby_nn61">34.10.4 Mark Functions</a></li>
<li><a HREF="#Ruby_nn62">34.10.5 Free Functions</a></li>
<li><a HREF="#Ruby_nn63">34.10.6 Embedded Ruby and the C++ Stack</a></li>
</ul>
</li>
</ul>
<b><a HREF="#Scilab">35 SWIG and Scilab</a></b>
<ul>
<li><a HREF="#Scilab_preliminaries">35.1 Preliminaries</a></li>
<li><a HREF="#Scilab_running_swig">35.2 Running SWIG</a>
<ul>
<li><a HREF="#Scilab_running_swig_generating_module">35.2.1 Generating
 the module</a></li>
<li><a HREF="#Scilab_running_swig_building_module">35.2.2 Building the
 module</a></li>
<li><a HREF="#Scilab_running_swig_loading_module">35.2.3 Loading the
 module</a></li>
<li><a HREF="#Scilab_running_swig_using_module">35.2.4 Using the module</a>
</li>
<li><a HREF="#Scilab_running_swig_options">35.2.5 Scilab command line
 options</a></li>
</ul>
</li>
<li><a HREF="#Scilab_wrapping">35.3 A basic tour of C/C++ wrapping</a>
<ul>
<li><a HREF="#Scilab_wrapping_overview">35.3.1 Overview</a></li>
<li><a HREF="#Scilab_wrapping_identifiers">35.3.2 Identifiers</a></li>
<li><a HREF="#Scilab_wrapping_functions">35.3.3 Functions</a>
<ul>
<li><a HREF="#Scilab_nn13">35.3.3.1 Argument passing</a></li>
<li><a HREF="#Scilab_nn14">35.3.3.2 Multiple output arguments</a></li>
</ul>
</li>
<li><a HREF="#Scilab_wrapping_global_variables">35.3.4 Global variables</a>
</li>
<li><a HREF="#Scilab_wrapping_constants_and_enums">35.3.5 Constants and
 enumerations</a>
<ul>
<li><a HREF="#Scilab_wrapping_constants">35.3.5.1 Constants</a></li>
<li><a HREF="#Scilab_wrapping_enums">35.3.5.2 Enumerations</a></li>
</ul>
</li>
<li><a HREF="#Scilab_wrapping_pointers">35.3.6 Pointers</a>
<ul>
<li><a HREF="#Scilab_wrapping_pointers_utility_functions">35.3.6.1
 Utility functions</a></li>
<li><a HREF="#Scilab_wrapping_pointers_null_pointers">35.3.6.2 Null
 pointers:</a></li>
</ul>
</li>
<li><a HREF="#Scilab_wrapping_structs">35.3.7 Structures</a></li>
<li><a HREF="#Scilab_wrapping_cpp_classes">35.3.8 C++ classes</a></li>
<li><a HREF="#Scilab_wrapping_cpp_inheritance">35.3.9 C++ inheritance</a>
</li>
<li><a HREF="#Scilab_wrapping_cpp_overloading">35.3.10 C++ overloading</a>
</li>
<li><a HREF="#Scilab_wrapping_pointers_references_values_arrays">35.3.11
 Pointers, references, values, and arrays</a></li>
<li><a HREF="#Scilab_wrapping_cpp_templates">35.3.12 C++ templates</a></li>
<li><a HREF="#Scilab_wrapping_cpp_operators">35.3.13 C++ operators</a></li>
<li><a HREF="#Scilab_wrapping_cpp_namespaces">35.3.14 C++ namespaces</a></li>
<li><a HREF="#Scilab_wrapping_cpp_exceptions">35.3.15 C++ exceptions</a></li>
<li><a HREF="#Scilab_wrapping_cpp_stl">35.3.16 C++ STL</a></li>
</ul>
</li>
<li><a HREF="#Scilab_typemaps">35.4 Type mappings and libraries</a>
<ul>
<li><a HREF="#Scilab_typemaps_primitive_types">35.4.1 Default primitive
 type mappings</a></li>
<li><a HREF="#Scilab_typemaps_arrays">35.4.2 Arrays</a></li>
<li><a HREF="#Scilab_typemaps_pointer-to-pointers">35.4.3
 Pointer-to-pointers</a></li>
<li><a HREF="#Scilab_typemaps_matrices">35.4.4 Matrices</a></li>
<li><a HREF="#Scilab_typemaps_stl">35.4.5 STL</a></li>
</ul>
</li>
<li><a HREF="#Scilab_module_initialization">35.5 Module initialization</a>
</li>
<li><a HREF="#Scilab_building_modes">35.6 Building modes</a>
<ul>
<li><a HREF="#Scilab_building_modes_nobuilder_mode">35.6.1 No-builder
 mode</a></li>
<li><a HREF="#Scilab_building_modes_builder_mode">35.6.2 Builder mode</a>
</li>
</ul>
</li>
<li><a HREF="#Scilab_generated_scripts">35.7 Generated scripts</a>
<ul>
<li><a HREF="#Scilab_generated_scripts_builder_script">35.7.1 Builder
 script</a></li>
<li><a HREF="#Scilab_generated_scripts_loader_script">35.7.2 Loader
 script</a></li>
</ul>
</li>
<li><a HREF="#Scilab_other_resources">35.8 Other resources</a></li>
</ul>
<b><a HREF="#Tcl">36 SWIG and Tcl</a></b>
<ul>
<li><a HREF="#Tcl_nn2">36.1 Preliminaries</a>
<ul>
<li><a HREF="#Tcl_nn3">36.1.1 Getting the right header files</a></li>
<li><a HREF="#Tcl_nn4">36.1.2 Compiling a dynamic module</a></li>
<li><a HREF="#Tcl_nn5">36.1.3 Static linking</a></li>
<li><a HREF="#Tcl_nn6">36.1.4 Using your module</a></li>
<li><a HREF="#Tcl_nn7">36.1.5 Compilation of C++ extensions</a></li>
<li><a HREF="#Tcl_nn8">36.1.6 Compiling for 64-bit platforms</a></li>
<li><a HREF="#Tcl_nn9">36.1.7 Setting a package prefix</a></li>
<li><a HREF="#Tcl_nn10">36.1.8 Using namespaces</a></li>
</ul>
</li>
<li><a HREF="#Tcl_nn11">36.2 Building Tcl/Tk Extensions under Windows
 95/NT</a>
<ul>
<li><a HREF="#Tcl_nn12">36.2.1 Running SWIG from Developer Studio</a></li>
<li><a HREF="#Tcl_nn13">36.2.2 Using NMAKE</a></li>
</ul>
</li>
<li><a HREF="#Tcl_nn14">36.3 A tour of basic C/C++ wrapping</a>
<ul>
<li><a HREF="#Tcl_nn15">36.3.1 Modules</a></li>
<li><a HREF="#Tcl_nn16">36.3.2 Functions</a></li>
<li><a HREF="#Tcl_nn17">36.3.3 Global variables</a></li>
<li><a HREF="#Tcl_nn18">36.3.4 Constants and enums</a></li>
<li><a HREF="#Tcl_nn19">36.3.5 Pointers</a></li>
<li><a HREF="#Tcl_nn20">36.3.6 Structures</a></li>
<li><a HREF="#Tcl_nn21">36.3.7 C++ classes</a></li>
<li><a HREF="#Tcl_nn22">36.3.8 C++ inheritance</a></li>
<li><a HREF="#Tcl_nn23">36.3.9 Pointers, references, values, and arrays</a>
</li>
<li><a HREF="#Tcl_nn24">36.3.10 C++ overloaded functions</a></li>
<li><a HREF="#Tcl_nn25">36.3.11 C++ operators</a></li>
<li><a HREF="#Tcl_nn26">36.3.12 C++ namespaces</a></li>
<li><a HREF="#Tcl_nn27">36.3.13 C++ templates</a></li>
<li><a HREF="#Tcl_nn28">36.3.14 C++ Smart Pointers</a></li>
</ul>
</li>
<li><a HREF="#Tcl_nn29">36.4 Further details on the Tcl class interface</a>
<ul>
<li><a HREF="#Tcl_nn30">36.4.1 Proxy classes</a></li>
<li><a HREF="#Tcl_nn31">36.4.2 Memory management</a></li>
</ul>
</li>
<li><a HREF="#Tcl_nn32">36.5 Input and output parameters</a></li>
<li><a HREF="#Tcl_nn33">36.6 Exception handling</a></li>
<li><a HREF="#Tcl_nn34">36.7 Typemaps</a>
<ul>
<li><a HREF="#Tcl_nn35">36.7.1 What is a typemap?</a></li>
<li><a HREF="#Tcl_nn36">36.7.2 Tcl typemaps</a></li>
<li><a HREF="#Tcl_nn37">36.7.3 Typemap variables</a></li>
<li><a HREF="#Tcl_nn38">36.7.4 Converting a Tcl list to a char **</a></li>
<li><a HREF="#Tcl_nn39">36.7.5 Returning values in arguments</a></li>
<li><a HREF="#Tcl_nn40">36.7.6 Useful functions</a></li>
<li><a HREF="#Tcl_nn41">36.7.7 Standard typemaps</a></li>
<li><a HREF="#Tcl_nn42">36.7.8 Pointer handling</a></li>
</ul>
</li>
<li><a HREF="#Tcl_nn43">36.8 Turning a SWIG module into a Tcl Package.</a>
</li>
<li><a HREF="#Tcl_nn44">36.9 Building new kinds of Tcl interfaces (in
 Tcl)</a>
<ul>
<li><a HREF="#Tcl_nn45">36.9.1 Proxy classes</a></li>
</ul>
</li>
<li><a HREF="#Tcl_nn46">36.10 Tcl/Tk Stubs</a></li>
</ul>
<b><a HREF="#Mzscheme">37 SWIG and MzScheme/Racket</a></b>
<ul>
<li><a HREF="#MzScheme_nn2">37.1 Creating native structures</a></li>
<li><a HREF="#MzScheme_simple">37.2 Simple example</a></li>
<li><a HREF="#MzScheme_external_docs">37.3 External documentation</a></li>
</ul>
<b><a HREF="#Ocaml">38 SWIG and OCaml</a></b>
<ul>
<li><a HREF="#Ocaml_nn2">38.1 Preliminaries</a>
<ul>
<li><a HREF="#Ocaml_nn3">38.1.1 Running SWIG</a></li>
<li><a HREF="#Ocaml_nn4">38.1.2 Compiling the code</a></li>
<li><a HREF="#Ocaml_nn5">38.1.3 The camlp4 module</a></li>
<li><a HREF="#Ocaml_nn6">38.1.4 Using your module</a></li>
<li><a HREF="#Ocaml_nn7">38.1.5 Compilation problems and compiling with
 C++</a></li>
</ul>
</li>
<li><a HREF="#Ocaml_nn8">38.2 The low-level Ocaml/C interface</a>
<ul>
<li><a HREF="#Ocaml_nn9">38.2.1 The generated module</a></li>
<li><a HREF="#Ocaml_nn10">38.2.2 Enums</a>
<ul>
<li><a HREF="#Ocaml_nn11">38.2.2.1 Enum typing in Ocaml</a></li>
</ul>
</li>
<li><a HREF="#Ocaml_nn12">38.2.3 Arrays</a>
<ul>
<li><a HREF="#Ocaml_nn13">38.2.3.1 Simple types of bounded arrays</a></li>
<li><a HREF="#Ocaml_nn14">38.2.3.2 Complex and unbounded arrays</a></li>
<li><a HREF="#Ocaml_nn15">38.2.3.3 Using an object</a></li>
<li><a HREF="#Ocaml_nn16">38.2.3.4 Example typemap for a function taking
 float * and int</a></li>
</ul>
</li>
<li><a HREF="#Ocaml_nn17">38.2.4 C++ Classes</a>
<ul>
<li><a HREF="#Ocaml_nn18">38.2.4.1 STL vector and string Example</a></li>
<li><a HREF="#Ocaml_nn19">38.2.4.2 C++ Class Example</a></li>
<li><a HREF="#Ocaml_nn20">38.2.4.3 Compiling the example</a></li>
<li><a HREF="#Ocaml_nn21">38.2.4.4 Sample Session</a></li>
</ul>
</li>
<li><a HREF="#Ocaml_nn22">38.2.5 Director Classes</a>
<ul>
<li><a HREF="#Ocaml_nn23">38.2.5.1 Director Introduction</a></li>
<li><a HREF="#Ocaml_nn24">38.2.5.2 Overriding Methods in Ocaml</a></li>
<li><a HREF="#Ocaml_nn25">38.2.5.3 Director Usage Example</a></li>
<li><a HREF="#Ocaml_nn26">38.2.5.4 Creating director objects</a></li>
<li><a HREF="#Ocaml_nn27">38.2.5.5 Typemaps for directors, directorin,
 directorout, directorargout</a></li>
<li><a HREF="#Ocaml_nn28">38.2.5.6 directorin typemap</a></li>
<li><a HREF="#Ocaml_nn29">38.2.5.7 directorout typemap</a></li>
<li><a HREF="#Ocaml_nn30">38.2.5.8 directorargout typemap</a></li>
</ul>
</li>
<li><a HREF="#Ocaml_nn31">38.2.6 Exceptions</a></li>
</ul>
</li>
<li><a HREF="#Ocaml_nn32">38.3 Documentation Features</a>
<ul>
<li><a HREF="#Ocaml_nn33">38.3.1 Module docstring</a></li>
</ul>
</li>
</ul>
<b><a HREF="#Extending">39 Extending SWIG to support new languages</a></b>
<ul>
<li><a HREF="#Extending_nn2">39.1 Introduction</a></li>
<li><a HREF="#Extending_nn3">39.2 Prerequisites</a></li>
<li><a HREF="#Extending_nn4">39.3 The Big Picture</a></li>
<li><a HREF="#Extending_nn5">39.4 Execution Model</a>
<ul>
<li><a HREF="#Extending_nn6">39.4.1 Preprocessing</a></li>
<li><a HREF="#Extending_nn7">39.4.2 Parsing</a></li>
<li><a HREF="#Extending_nn8">39.4.3 Parse Trees</a></li>
<li><a HREF="#Extending_nn9">39.4.4 Attribute namespaces</a></li>
<li><a HREF="#Extending_nn10">39.4.5 Symbol Tables</a></li>
<li><a HREF="#Extending_nn11">39.4.6 The %feature directive</a></li>
<li><a HREF="#Extending_nn12">39.4.7 Code Generation</a></li>
<li><a HREF="#Extending_nn13">39.4.8 SWIG and XML</a></li>
</ul>
</li>
<li><a HREF="#Extending_nn14">39.5 Primitive Data Structures</a>
<ul>
<li><a HREF="#Extending_nn15">39.5.1 Strings</a></li>
<li><a HREF="#Extending_nn16">39.5.2 Hashes</a></li>
<li><a HREF="#Extending_nn17">39.5.3 Lists</a></li>
<li><a HREF="#Extending_nn18">39.5.4 Common operations</a></li>
<li><a HREF="#Extending_nn19">39.5.5 Iterating over Lists and Hashes</a></li>
<li><a HREF="#Extending_nn20">39.5.6 I/O</a></li>
</ul>
</li>
<li><a HREF="#Extending_nn21">39.6 Navigating and manipulating parse
 trees</a></li>
<li><a HREF="#Extending_nn22">39.7 Working with attributes</a></li>
<li><a HREF="#Extending_nn23">39.8 Type system</a>
<ul>
<li><a HREF="#Extending_nn24">39.8.1 String encoding of types</a></li>
<li><a HREF="#Extending_nn25">39.8.2 Type construction</a></li>
<li><a HREF="#Extending_nn26">39.8.3 Type tests</a></li>
<li><a HREF="#Extending_nn27">39.8.4 Typedef and inheritance</a></li>
<li><a HREF="#Extending_nn28">39.8.5 Lvalues</a></li>
<li><a HREF="#Extending_nn29">39.8.6 Output functions</a></li>
</ul>
</li>
<li><a HREF="#Extending_nn30">39.9 Parameters</a></li>
<li><a HREF="#Extending_nn31">39.10 Writing a Language Module</a>
<ul>
<li><a HREF="#Extending_nn32">39.10.1 Execution model</a></li>
<li><a HREF="#Extending_starting_out">39.10.2 Starting out</a></li>
<li><a HREF="#Extending_nn34">39.10.3 Command line options</a></li>
<li><a HREF="#Extending_nn35">39.10.4 Configuration and preprocessing</a>
</li>
<li><a HREF="#Extending_nn36">39.10.5 Entry point to code generation</a></li>
<li><a HREF="#Extending_nn37">39.10.6 Module I/O and wrapper skeleton</a>
</li>
<li><a HREF="#Extending_nn38">39.10.7 Low-level code generators</a></li>
<li><a HREF="#Extending_configuration_files">39.10.8 Configuration files</a>
</li>
<li><a HREF="#Extending_nn40">39.10.9 Runtime support</a></li>
<li><a HREF="#Extending_nn41">39.10.10 Standard library files</a></li>
<li><a HREF="#Extending_nn42">39.10.11 User examples</a></li>
<li><a HREF="#Extending_test_suite">39.10.12 Test driven development and
 the test-suite</a>
<ul>
<li><a HREF="#Extending_running_test_suite">39.10.12.1 Running the
 test-suite</a></li>
</ul>
</li>
<li><a HREF="#Extending_nn43">39.10.13 Documentation</a></li>
<li><a HREF="#Extending_coding_style_guidelines">39.10.14 Coding style
 guidelines</a></li>
<li><a HREF="#Extending_language_status">39.10.15 Target language status</a>
<ul>
<li><a HREF="#Extending_supported_status">39.10.15.1 Supported status</a>
</li>
<li><a HREF="#Extending_experimental_status">39.10.15.2 Experimental
 status</a></li>
</ul>
</li>
<li><a HREF="#Extending_prerequisites">39.10.16 Prerequisites for adding
 a new language module to the SWIG distribution</a></li>
</ul>
</li>
<li><a HREF="#Extending_debugging_options">39.11 Debugging Options</a></li>
<li><a HREF="#Extending_nn46">39.12 Guide to parse tree nodes</a></li>
<li><a HREF="#Extending_further_info">39.13 Further Development
 Information</a></li>
</ul>
<HR NOSHADE>
<h1><a name="Sections">SWIG-4.0 Documentation</a></h1>
<p> Last update : SWIG-4.0.2 (8 Jun 2020)</p>
<h2><a name="Sections_Sections">Sections</a></h2>
<h3><a name="Sections_core_docs">SWIG Core Documentation</a></h3>
<ul>
<li><a href="#Preface">Preface</a></li>
<li><a href="#Introduction">Introduction</a></li>
<li><a href="#Windows">Getting started on Windows</a></li>
<li><a href="#Scripting">Scripting</a></li>
<li><a href="#SWIG">SWIG Basics</a> (Read this!)</li>
<li><a href="#SWIGPlus">SWIG and C++</a></li>
<li><a href="#CPlusPlus11">SWIG and C++11</a></li>
<li><a href="#CPlusPlus14">SWIG and C++14</a></li>
<li><a href="#CPlusPlus17">SWIG and C++17</a></li>
<li><a href="#Preprocessor">The SWIG preprocessor</a></li>
<li><a href="#Library">The SWIG library</a></li>
<li><a href="#Arguments">Argument handling</a></li>
<li><a href="#Typemaps">Typemaps</a></li>
<li><a href="#Customization">Customization features</a></li>
<li><a href="#Contract">Contracts</a></li>
<li><a href="#Varargs">Variable length arguments</a></li>
<li><a href="#Doxygen">Doxygen documentation comments</a></li>
<li><a href="#Warnings">Warning messages</a></li>
<li><a href="#Modules">Working with Modules</a></li>
<li><a href="#CCache">Using SWIG with ccache</a></li>
</ul>
<h3><a name="Sections_language_modules">Supported Language Modules
 Documentation</a></h3>
<ul>
<li><a href="#Android">Android support</a></li>
<li><a href="#CSharp">C# support</a></li>
<li><a href="#D">D support</a></li>
<li><a href="#Go">Go support</a></li>
<li><a href="#Guile">Guile support</a></li>
<li><a href="#Java">Java support</a></li>
<li><a href="#Javascript">Javascript support</a></li>
<li><a href="#Lua">Lua support</a></li>
<li><a href="#Octave">Octave support</a></li>
<li><a href="#Perl5">Perl5 support</a></li>
<li><a href="#Php">PHP support</a></li>
<li><a href="#Python">Python support</a></li>
<li><a href="#R">R support</a></li>
<li><a href="#Ruby">Ruby support</a></li>
<li><a href="#Scilab">Scilab support</a></li>
<li><a href="#Tcl">Tcl support</a></li>
</ul>
<h3><a name="Sections_experimental_language_modules">Experimental
 Language Modules Documentation</a></h3>
<ul>
<li><a href="#Mzscheme">MzScheme/Racket support</a></li>
<li><a href="#Ocaml">OCaml support</a></li>
</ul>
<h3><a name="Sections_developers_docs">Developer Documentation</a></h3>
<ul>
<li><a href="#Extending">Extending SWIG</a></li>
</ul>
<HR NOSHADE>
<h1><a name="Preface">1 Preface</a></h1>

<!-- INDEX -->
<div class="sectiontoc">
<ul>
<li><a href="#Preface_nn2">Introduction</a></li>
<li><a href="#Preface_nn4">SWIG Versions</a></li>
<li><a href="#Preface_license">SWIG License</a></li>
<li><a href="#Preface_nn5">SWIG resources</a></li>
<li><a href="#Preface_nn6">Prerequisites</a></li>
<li><a href="#Preface_nn7">Organization of this manual</a></li>
<li><a href="#Preface_nn8">How to avoid reading the manual</a></li>
<li><a href="#Preface_nn9">Backwards compatibility</a></li>
<li><a href="#Preface_release_notes">Release notes</a></li>
<li><a href="#Preface_nn10">Credits</a></li>
<li><a href="#Preface_nn11">Bug reports</a></li>
<li><a href="#Preface_installation">Installation</a>
<ul>
<li><a href="#Preface_windows_installation">Windows installation</a></li>
<li><a href="#Preface_unix_installation">Unix installation</a></li>
<li><a href="#Preface_osx_installation">Macintosh OS X installation</a></li>
<li><a href="#Preface_testing">Testing</a></li>
<li><a href="#Preface_examples">Examples</a></li>
</ul>
</li>
</ul>
</div>
<!-- INDEX -->
<h2><a name="Preface_nn2">1.1 Introduction</a></h2>
<p> SWIG (Simplified Wrapper and Interface Generator) is a software
 development tool for building scripting language interfaces to C and
 C++ programs. Originally developed in 1995, SWIG was first used by
 scientists in the Theoretical Physics Division at Los Alamos National
 Laboratory for building user interfaces to simulation codes running on
 the Connection Machine 5 supercomputer. In this environment, scientists
 needed to work with huge amounts of simulation data, complex hardware,
 and a constantly changing code base. The use of a scripting language
 interface provided a simple yet highly flexible foundation for solving
 these types of problems. SWIG simplifies development by largely
 automating the task of scripting language integration--allowing
 developers and users to focus on more important problems.</p>
<p> Although SWIG was originally developed for scientific applications,
 it has since evolved into a general purpose tool that is used in a wide
 variety of applications--in fact almost anything where C/C++
 programming is involved.</p>
<h2><a name="Preface_nn4">1.2 SWIG Versions</a></h2>
<p> In the late 1990's, the most stable version of SWIG was release
 1.1p5. Versions 1.3.x were officially development versions and these
 were released over a period of 10 years starting from the year 2000.
 The final version in the 1.3.x series was 1.3.40, but in truth the
 1.3.x series had been stable for many years. An official stable version
 was released along with the decision to make SWIG license changes and
 this gave rise to version 2.0.0 in 2010. Version 3.0.0 was released in
 2014 focusing on adding C++11 support and C++ nested classes. Version
 4.0.0 was released in 2019 to add in Doxygen support. Some target
 languages were disabled as part of a clean up and others were given a
 new status of either 'Supported' or 'Experimental'.</p>
<h2><a name="Preface_license">1.3 SWIG License</a></h2>
<p> The LICENSE file shipped with SWIG in the top level directory
 contains the SWIG license. For further insight into the license
 including the license of SWIG's output code, please visit the SWIG
 legal page - <a href="http://www.swig.org/legal.html">
http://www.swig.org/legal.html</a>.</p>
<p> The license was clarified in version 2.0.0 so that the code that
 SWIG generated could be distributed under license terms of the user's
 choice/requirements and at the same time the SWIG source was placed
 under the GNU General Public License version 3.</p>
<h2><a name="Preface_nn5">1.4 SWIG resources</a></h2>
<p> The official location of SWIG related material is</p>
<div class="shell">
<pre>
<a href="http://www.swig.org">http://www.swig.org</a>
</pre>
</div>
<p> This site contains the latest version of the software, users guide,
 and information regarding bugs, installation problems, and
 implementation tricks.</p>
<p> You can also subscribe to the swig-user mailing list by visiting the
 page</p>
<div class="shell">
<pre>
<a href="http://www.swig.org/mail.html">http://www.swig.org/mail.html</a>
</pre>
</div>
<p> The mailing list often discusses some of the more technical aspects
 of SWIG along with information about beta releases and future work.</p>
<p> Git and Subversion access to the latest version of SWIG is also
 available. More information about this can be obtained at:</p>
<div class="shell">
<pre>
<a href="http://www.swig.org/svn.html">SWIG Bleeding Edge</a>
</pre>
</div>
<h2><a name="Preface_nn6">1.5 Prerequisites</a></h2>
<p> This manual assumes that you know how to write C/C++ programs and
 that you have at least heard of scripting languages such as Tcl,
 Python, and Perl. A detailed knowledge of these scripting languages is
 not required although some familiarity won't hurt. No prior experience
 with building C extensions to these languages is required---after all,
 this is what SWIG does automatically. However, you should be reasonably
 familiar with the use of compilers, linkers, and makefiles since making
 scripting language extensions is somewhat more complicated than writing
 a normal C program.</p>
<p> Over time SWIG releases have become significantly more capable in
 their C++ handling--especially support for advanced features like
 namespaces, overloaded operators, and templates. Whenever possible,
 this manual tries to cover the technicalities of this interface.
 However, this isn't meant to be a tutorial on C++ programming. For many
 of the gory details, you will almost certainly want to consult a good
 C++ reference. If you don't program in C++, you may just want to skip
 those parts of the manual.</p>
<h2><a name="Preface_nn7">1.6 Organization of this manual</a></h2>
<p> The first few chapters of this manual describe SWIG in general and
 provide an overview of its capabilities. The remaining chapters are
 devoted to specific SWIG language modules and are self contained. Thus,
 if you are using SWIG to build Python interfaces, you can probably skip
 to that chapter and find almost everything you need to know.</p>
<h2><a name="Preface_nn8">1.7 How to avoid reading the manual</a></h2>
<p> If you hate reading manuals, glance at the &quot;Introduction&quot; which
 contains a few simple examples. These examples contain about 95% of
 everything you need to know to use SWIG. After that, simply use the
 language-specific chapters as a reference. The SWIG distribution also
 comes with a large directory of examples that illustrate different
 topics.</p>
<h2><a name="Preface_nn9">1.8 Backwards compatibility</a></h2>
<p> If you are a previous user of SWIG, don't expect SWIG to provide
 complete backwards compatibility. Although the developers strive to the
 utmost to keep backwards compatibility, this isn't always possible as
 the primary goal over time is to make SWIG better---a process that
 would simply be impossible if the developers are constantly bogged down
 with backwards compatibility issues. Potential incompatibilities are
 clearly marked in the detailed <a href="#Preface_release_notes">release
 notes</a>.</p>
<p> If you need to work with different versions of SWIG and backwards
 compatibility is an issue, you can use the SWIG_VERSION preprocessor
 symbol which holds the version of SWIG being executed. SWIG_VERSION is
 a hexadecimal integer such as 0x010311 (corresponding to SWIG-1.3.11).
 This can be used in an interface file to define different typemaps,
 take advantage of different features etc:</p>
<div class="code">
<pre>
#if SWIG_VERSION &gt;= 0x010311
/* Use some fancy new feature */
#endif
</pre>
</div>
<p> Note: The version symbol is not defined in the generated SWIG
 wrapper file. The SWIG preprocessor has defined SWIG_VERSION since
 SWIG-1.3.11.</p>
<h2><a name="Preface_release_notes">1.9 Release notes</a></h2>
<p> The CHANGES.current, CHANGES and RELEASENOTES files shipped with
 SWIG in the top level directory contain, respectively, detailed release
 notes for the current version, detailed release notes for previous
 releases and summary release notes from SWIG-1.3.22 onwards.</p>
<h2><a name="Preface_nn10">1.10 Credits</a></h2>
<p> SWIG is an unfunded project that would not be possible without the
 contributions of many people working in their spare time. If you have
 benefitted from using SWIG, please consider <a href="http://www.swig.org/donate.html">
Donating to SWIG</a> to keep development going. There have been a large
 varied number of people who have made contributions at all levels over
 time. Contributors are mentioned either in the COPYRIGHT file or
 CHANGES files shipped with SWIG or in submitted bugs.</p>
<h2><a name="Preface_nn11">1.11 Bug reports</a></h2>
<p> Although every attempt has been made to make SWIG bug-free, we are
 also trying to make feature improvements that may introduce bugs. To
 report a bug, either send mail to the SWIG developer list at the <a href="http://www.swig.org/mail.html">
swig-devel mailing list</a> or report a bug at the <a href="http://www.swig.org/bugs.html">
SWIG bug tracker</a>. In your report, be as specific as possible,
 including (if applicable), error messages, tracebacks (if a core dump
 occurred), corresponding portions of the SWIG interface file used, and
 any important pieces of the SWIG generated wrapper code. We can only
 fix bugs if we know about them.</p>
<h2><a name="Preface_installation">1.12 Installation</a></h2>
<h3><a name="Preface_windows_installation">1.12.1 Windows installation</a>
</h3>
<p> Please see the dedicated <a href="#Windows">Windows chapter</a> for
 instructions on installing SWIG on Windows and running the examples.
 The Windows distribution is called swigwin and includes a prebuilt SWIG
 executable, swig.exe, included in the top level directory. Otherwise it
 is exactly the same as the main SWIG distribution. There is no need to
 download anything else.</p>
<h3><a name="Preface_unix_installation">1.12.2 Unix installation</a></h3>
<p> These installation instructions are for using the distributed
 tarball, for example, <tt>swig-3.0.8.tar.gz</tt>. If you wish to build
 and install from source on Github, extra steps are required. Please see
 the <a href="http://swig.org/svn.html">Bleeding Edge</a> page on the
 SWIG website.</p>
<p> You must use <a href="http://www.gnu.org/software/make/">GNU make</a>
 to build and install SWIG.</p>
<p> <a href="http://www.pcre.org/">PCRE</a> needs to be installed on
 your system to build SWIG, in particular pcre-config must be available.
 If you have PCRE headers and libraries but not pcre-config itself or,
 alternatively, wish to override the compiler or linker flags returned
 by pcre-config, you may set PCRE_LIBS and PCRE_CFLAGS variables to be
 used instead. And if you don't have PCRE at all, the configure script
 will provide instructions for obtaining it.</p>
<p> To build and install SWIG, simply type the following:</p>
<div class="shell">
<pre>
$ ./configure
$ make
$ make install
</pre>
</div>
<p> By default SWIG installs itself in /usr/local. If you need to
 install SWIG in a different location or in your home directory, use the
 <tt>--prefix</tt> option to <tt>./configure</tt>. For example:</p>
<div class="shell">
<pre>
$ ./configure --prefix=/home/yourname/projects
$ make
$ make install
</pre>
</div>
<p> Note: the directory given to <tt>--prefix</tt> must be an absolute
 pathname. Do<b> not</b> use the ~ shell-escape to refer to your home
 directory. SWIG won't work properly if you do this.</p>
<p> The INSTALL file shipped in the top level directory details more
 about using configure. Also try</p>
<div class="shell">
<pre>
$ ./configure --help.
</pre>
</div>
<p> The configure script will attempt to locate various packages on your
 machine including Tcl, Perl5, Python and all the other target languages
 that SWIG supports. Don't panic if you get 'not found' messages -- SWIG
 does not need these packages to compile or run. The configure script is
 actually looking for these packages so that you can try out the SWIG
 examples contained in the 'Examples' directory without having to hack
 Makefiles. Note that the <tt>--without-xxx</tt> options, where xxx is a
 target language, have minimal effect. All they do is reduce the amount
 of testing done with 'make check'. The SWIG executable and library
 files installed cannot currently be configured with a subset of target
 languages.</p>
<p> SWIG used to include a set of runtime libraries for some languages
 for working with multiple modules. These are no longer built during the
 installation stage. However, users can build them just like any wrapper
 module as described in the <a href="#Modules">Modules chapter</a>. The
 CHANGES file shipped with SWIG in the top level directory also lists
 some examples which build the runtime library.</p>
<p> Note:</p>
<ul>
<li> If you checked the code out via Git, you will have to run <tt>
./autogen.sh</tt> before <tt>./configure</tt>. In addition, a full build
 of SWIG requires a number of packages to be installed. Full
 instructions at <a href="http://www.swig.org/svn.html">SWIG bleeding
 edge</a>.</li>
</ul>
<h3><a name="Preface_osx_installation">1.12.3 Macintosh OS X
 installation</a></h3>
<p> SWIG is known to work on various flavors of OS X. Follow the Unix
 installation instructions above. However, as of this writing, there is
 still great deal of inconsistency with how shared libraries are handled
 by various scripting languages on OS X.</p>
<p> Users of OS X should be aware that Darwin handles shared libraries
 and linking in a radically different way than most Unix systems. In
 order to test SWIG and run the examples, SWIG configures itself to use
 flat namespaces and to allow undefined symbols (<tt>-flat_namespace
 -undefined suppress</tt>). This mostly closely follows the Unix model
 and makes it more likely that the SWIG examples will work with whatever
 installation of software you might have. However, this is generally not
 the recommended technique for building larger extension modules.
 Instead, you should utilize Darwin's two-level namespaces. Some details
 about this can be found here <a href="https://developer.apple.com/library/mac/documentation/Porting/Conceptual/PortingUnix/compiling/compiling.html#//apple_ref/doc/uid/TP40002850-BCIHJBBF">
Understanding Two-Level Namespaces</a>.</p>
<p> Needless to say, you might have to experiment a bit to get things
 working at first.</p>
<h3><a name="Preface_testing">1.12.4 Testing</a></h3>
<p> If you want to test SWIG after building it, a check can be performed
 on Unix operating systems. Type the following:</p>
<div class="shell">
<pre>
    $ make -k check
</pre>
</div>
<p> This step can be performed either before or after installation. The
 check requires at least one of the target languages to be installed. If
 it fails, it may mean that you have an uninstalled language module or
 that the file 'Examples/Makefile' has been incorrectly configured. It
 may also fail due to compiler issues such as a broken C++ compiler.
 Even if the check fails, there is a pretty good chance SWIG still works
 correctly --- you will just have to mess around with one of the
 examples and some makefiles to get it to work. Some tests may also fail
 due to missing dependency packages, eg PCRE or Boost, but this will
 require careful analysis of the configure output done during
 configuration.</p>
<p> The test suite executed by the check is designed to stress-test many
 parts of the implementation including obscure corner cases. If some of
 these tests fail or generate warning messages, there is no reason for
 alarm --- the test may be related to some new SWIG feature or a
 difficult bug that we're trying to resolve. Chances are that SWIG will
 work just fine for you. Note that if you have more than one CPU/core,
 then you can use parallel make to speed up the check as it does take
 quite some time to run, for example:</p>
<div class="shell">
<pre>
    $ make -j2 -k check
</pre>
</div>
<p> Also, SWIG's support for C++ is sufficiently advanced that certain
 tests may fail on older C++ compilers (for instance if your compiler
 does not support member templates). These errors are harmless if you
 don't intend to use these features in your own programs.</p>
<p> Note: The test-suite currently contains over 600 tests. If you have
 many different target languages installed and a slow machine, it might
 take more than an hour to run the test-suite.</p>
<h3><a name="Preface_examples">1.12.5 Examples</a></h3>
<p> The Examples directory contains a variety of examples of using SWIG
 and it has some browsable documentation. Simply point your browser to
 the file &quot;Example/index.html&quot;.</p>
<p> The Examples directory also includes Visual C++ project 6 (.dsp)
 files for building some of the examples on Windows. Later versions of
 Visual Studio will convert these old style project files into a current
 solution file.</p>
<HR NOSHADE>
<h1><a name="Introduction">2 Introduction</a></h1>

<!-- INDEX -->
<div class="sectiontoc">
<ul>
<li><a href="#Introduction_nn2">What is SWIG?</a></li>
<li><a href="#Introduction_nn3">Why use SWIG?</a></li>
<li><a href="#Introduction_target_languages">Target languages</a>
<ul>
<li><a href="#Introduction_supported_status">Supported status</a></li>
<li><a href="#Introduction_experimental_status">Experimental status</a></li>
</ul>
</li>
<li><a href="#Introduction_nn4">A SWIG example</a>
<ul>
<li><a href="#Introduction_nn5">SWIG interface file</a></li>
<li><a href="#Introduction_nn6">The swig command</a></li>
<li><a href="#Introduction_nn7">Building a Perl5 module</a></li>
<li><a href="#Introduction_nn8">Building a Python module</a></li>
<li><a href="#Introduction_nn9">Shortcuts</a></li>
</ul>
</li>
<li><a href="#Introduction_nn10">Supported C/C++ language features</a></li>
<li><a href="#Introduction_nn11">Non-intrusive interface building</a></li>
<li><a href="#Introduction_build_system">Incorporating SWIG into a build
 system</a></li>
<li><a href="#Introduction_nn12">Hands off code generation</a></li>
<li><a href="#Introduction_nn13">SWIG and freedom</a></li>
</ul>
</div>
<!-- INDEX -->
<h2><a name="Introduction_nn2">2.1 What is SWIG?</a></h2>
<p> SWIG is a software development tool that simplifies the task of
 interfacing different languages to C and C++ programs. In a nutshell,
 SWIG is a compiler that takes C/C++ declarations and creates the
 wrappers needed to access those declarations from other languages
 including Perl, Python, Tcl, Ruby, Guile, and Java. SWIG normally
 requires no modifications to existing code and can often be used to
 build a usable interface in only a few minutes. Possible applications
 of SWIG include:</p>
<ul>
<li>Building interpreted interfaces to existing C programs.</li>
<li>Rapid prototyping and application development.</li>
<li>Interactive debugging.</li>
<li>Reengineering or refactoring of legacy software into scripting
 language components.</li>
<li>Making a graphical user interface (using Tk for example).</li>
<li>Testing of C libraries and programs (using scripts).</li>
<li>Building high performance C modules for scripting languages.</li>
<li>Making C programming more enjoyable (or tolerable depending on your
 point of view).</li>
<li>Impressing your friends.</li>
<li>Obtaining vast sums of research funding (although obviously not
 applicable to the author).</li>
</ul>
<p> SWIG was originally designed to make it extremely easy for
 scientists and engineers to build extensible scientific software
 without having to get a degree in software engineering. Because of
 this, the use of SWIG tends to be somewhat informal and ad-hoc (e.g.,
 SWIG does not require users to provide formal interface specifications
 as you would find in a dedicated IDL compiler). Although this style of
 development isn't appropriate for every project, it is particularly
 well suited to software development in the small; especially the
 research and development work that is commonly found in scientific and
 engineering projects. However, nowadays SWIG is known to be used in
 many large open source and commercial projects.</p>
<h2><a name="Introduction_nn3">2.2 Why use SWIG?</a></h2>
<p> As stated in the previous section, the primary purpose of SWIG is to
 simplify the task of integrating C/C++ with other programming
 languages. However, why would anyone want to do that? To answer that
 question, it is useful to list a few strengths of C/C++ programming:</p>
<ul>
<li>Excellent support for writing programming libraries.</li>
<li>High performance (number crunching, data processing, graphics,
 etc.).</li>
<li>Systems programming and systems integration.</li>
<li>Large user community and software base.</li>
</ul>
<p> Next, let's list a few problems with C/C++ programming</p>
<ul>
<li>Writing a user interface is rather painful (i.e., consider
 programming with MFC, X11, GTK, or any number of other libraries).</li>
<li>Testing is time consuming (the compile/debug cycle).</li>
<li>Not easy to reconfigure or customize without recompilation.</li>
<li>Modularization can be tricky.</li>
<li>Security concerns (buffer overflows for instance).</li>
</ul>
<p> To address these limitations, many programmers have arrived at the
 conclusion that it is much easier to use different programming
 languages for different tasks. For instance, writing a graphical user
 interface may be significantly easier in a scripting language like
 Python or Tcl (consider the reasons why millions of programmers have
 used languages like Visual Basic if you need more proof). An
 interactive interpreter might also serve as a useful debugging and
 testing tool. Other languages like Java might greatly simplify the task
 of writing distributed computing software. The key point is that
 different programming languages offer different strengths and
 weaknesses. Moreover, it is extremely unlikely that any programming is
 ever going to be perfect. Therefore, by combining languages together,
 you can utilize the best features of each language and greatly simplify
 certain aspects of software development.</p>
<p> From the standpoint of C/C++, a lot of people use SWIG because they
 want to break out of the traditional monolithic C programming model
 which usually results in programs that resemble this:</p>
<ul>
<li>A collection of functions and variables that do something useful.</li>
<li>A <tt>main()</tt> program that starts everything.</li>
<li>A horrible collection of hacks that form some kind of user interface
 (but which no-one really wants to touch).</li>
</ul>
<p> Instead of going down that route, incorporating C/C++ into a higher
 level language often results in a more modular design, less code,
 better flexibility, and increased programmer productivity.</p>
<p> SWIG tries to make the problem of C/C++ integration as painless as
 possible. This allows you to focus on the underlying C program and
 using the high-level language interface, but not the tedious and
 complex chore of making the two languages talk to each other. At the
 same time, SWIG recognizes that all applications are different.
 Therefore, it provides a wide variety of customization features that
 let you change almost every aspect of the language bindings. This is
 the main reason why SWIG has such a large user manual ;-).</p>
<h2><a name="Introduction_target_languages">2.3 Target languages</a></h2>
<p> SWIG in essence is a tool to generate code for making C/C++ code
 available to various other programming languages. These higher level
 programming languages are the target languages for the SWIG code
 generator and C or C++ are the input languages. A single target
 language must be specified when SWIG is run. This results in generating
 code for C/C++ and the specified target language to interface with each
 other. SWIG can be invoked multiple times, but with a different target
 language specified on each invocation. This ability to interface C/C++
 to many different target languages is one of SWIG's core strengths and
 features.</p>
<p> SWIG is very broadly composed of two components. A core component
 creates a parse tree from the input ISO C/C++ and SWIG directives
 (extensions to the C/C++ standards). The parse tree is then passed to a
 second component, one of the target language modules for generating
 code specific to a higher level language. SWIG supports many different
 target languages. These target languages are given a status of either
 Supported or Experimental. This status is provided to indicate the
 level of maturity to expect when using a particular target language as
 not all target languages are fully developed.</p>
<p> The second part of the SWIG documentation contains a chapter for
 each target level language. Each chapter will state the status
 (Supported or Experimental) for that language.</p>
<h3><a name="Introduction_supported_status">2.3.1 Supported status</a></h3>
<p> A target language is given the 'Supported' status when</p>
<ul>
<li>It is in a mature, well functioning state.</li>
<li>It has its own comprehensive chapter in the documentation.</li>
<li>It passes all of the main SWIG test-suite and has a range of working
 examples.</li>
<li>It supports the vast majority of SWIG features.</li>
<li>It provides strong backwards compatibility between releases.</li>
</ul>
<p> The above is a short summary and further details are outlined in the
 <a href="#Extending_supported_status">Supported status</a> section in
 the Extending chapter. The good news is that all the well-known and
 most popular languages have this status.</p>
<h3><a name="Introduction_experimental_status">2.3.2 Experimental status</a>
</h3>
<p> A target language is given the 'Experimental' status when</p>
<ul>
<li>It is of sub-standard quality, failing to meet the above 'Supported'
 status.</li>
<li>It is somewhere between the mid to mature stage of development.</li>
<li>It does not guarantee any backwards compatibility between releases.</li>
<li>It is in need of help to finish development.</li>
</ul>
<p> Anyone using an experimental target language is strongly urged to
 assist with development of the target language module if they wish to
 use it.</p>
<p> SWIG displays a warning when an experimental target language is used
 in order to set expectations and emphasize the experimental status of
 the target language. The usual <a href="#Warnings_suppression">warning
 suppression</a> techniques can be used if required.</p>
<p> The above is a short summary and further details are outlined in the
 <a href="#Extending_experimental_status">Experimental status</a>
 section in the Extending chapter.</p>
<h2><a name="Introduction_nn4">2.4 A SWIG example</a></h2>
<p> The best way to illustrate SWIG is with a simple example. Consider
 the following C code:</p>
<div class="code">
<pre>
/* File : example.c */

double My_variable = 3.0;

/* Compute factorial of n */
int fact(int n) {
  if (n &lt;= 1)
    return 1;
  else
    return n*fact(n-1);
}

/* Compute n mod m */
int my_mod(int n, int m) {
  return(n % m);
}
</pre>
</div>
<p> Suppose that you wanted to access these functions and the global
 variable <tt>My_variable</tt> from Tcl. You start by making a SWIG
 interface file as shown below (by convention, these files carry a .i
 suffix) :</p>
<h3><a name="Introduction_nn5">2.4.1 SWIG interface file</a></h3>
<div class="code">
<pre>
/* File : example.i */
%module example
%{
/* Put headers and other declarations here */
extern double My_variable;
extern int    fact(int);
extern int    my_mod(int n, int m);
%}

extern double My_variable;
extern int    fact(int);
extern int    my_mod(int n, int m);
</pre>
</div>
<p> The interface file contains ISO C function prototypes and variable
 declarations. The <tt>%module</tt> directive defines the name of the
 module that will be created by SWIG. The <tt>%{ %}</tt> block provides
 a location for inserting additional code, such as C header files or
 additional C declarations, into the generated C wrapper code.</p>
<h3><a name="Introduction_nn6">2.4.2 The swig command</a></h3>
<p> SWIG is invoked using the <tt>swig</tt> command. We can use this to
 build a Tcl module (under Linux) as follows :</p>
<div class="shell">
<pre>
unix &gt; <b>swig -tcl example.i</b>
unix &gt; <b>gcc -c -fpic example.c example_wrap.c -I/usr/local/include</b>
unix &gt; <b>gcc -shared example.o example_wrap.o -o example.so</b>
unix &gt; <b>tclsh</b>
% <b>load ./example.so</b>
% <b>fact 4</b>
24
% <b>my_mod 23 7</b>
2
% <b>expr $My_variable + 4.5</b>
7.5
%
</pre>
</div>
<p> The <tt>swig</tt> command produced a new file called <tt>
example_wrap.c</tt> that should be compiled along with the <tt>example.c</tt>
 file. Most operating systems and scripting languages now support
 dynamic loading of modules. In our example, our Tcl module has been
 compiled into a shared library that can be loaded into Tcl. When
 loaded, Tcl can now access the functions and variables declared in the
 SWIG interface. A look at the file <tt>example_wrap.c</tt> reveals a
 hideous mess. However, you almost never need to worry about it.</p>
<h3><a name="Introduction_nn7">2.4.3 Building a Perl5 module</a></h3>
<p> Now, let's turn these functions into a Perl5 module. Without making
 any changes type the following (shown for Solaris):</p>
<div class="shell">
<pre>
unix &gt; <b>swig -perl5 example.i</b>
unix &gt; <b>gcc -c example.c example_wrap.c \
        -I/usr/local/lib/perl5/sun4-solaris/5.003/CORE</b>
unix &gt; <b>ld -G example.o example_wrap.o -o example.so</b> # This is for Solaris
unix &gt; <b>perl5.003
use example;
print example::fact(4), &quot;\n&quot;;
print example::my_mod(23, 7), &quot;\n&quot;;
print $example::My_variable + 4.5, &quot;\n&quot;;
&lt;ctrl-d&gt;</b>
24
2
7.5
unix &gt;
</pre>
</div>
<h3><a name="Introduction_nn8">2.4.4 Building a Python module</a></h3>
<p> Finally, let's build a module for Python (shown for Irix).</p>
<div class="shell">
<pre>
unix &gt; <b>swig -python example.i</b>
unix &gt; <b>gcc -c -fpic example.c example_wrap.c -I/usr/local/include/python2.0</b>
unix &gt; <b>gcc -shared example.o example_wrap.o -o _example.so</b>
unix &gt; <b>python</b>
Python 2.0 (#6, Feb 21 2001, 13:29:45)
[GCC egcs-2.91.66 19990314/Linux (egcs-1.1.2 release)] on linux2
Type &quot;copyright&quot;, &quot;credits&quot; or &quot;license&quot; for more information.     
&gt;&gt;&gt; <b>import example</b>
&gt;&gt;&gt; <b>example.fact(4)</b>
24
&gt;&gt;&gt; <b>example.my_mod(23, 7)</b>
2
&gt;&gt;&gt; <b>example.cvar.My_variable + 4.5</b>
7.5
</pre>
</div>
<h3><a name="Introduction_nn9">2.4.5 Shortcuts</a></h3>
<p> To the truly lazy programmer, one may wonder why we needed the extra
 interface file at all. As it turns out, you can often do without it.
 For example, you could also build a Perl5 module by just running SWIG
 on the C header file and specifying a module name as follows</p>
<div class="shell">
<pre>
unix &gt; <b>swig -perl5 -module example example.h</b>
unix &gt; <b>gcc -c example.c example_wrap.c \
        -I/usr/local/lib/perl5/sun4-solaris/5.003/CORE</b>
unix &gt; <b>ld -G example.o example_wrap.o -o example.so</b>
unix &gt; <b>perl5.003
use example;
print example::fact(4), &quot;\n&quot;;
print example::my_mod(23, 7), &quot;\n&quot;;
print $example::My_variable + 4.5, &quot;\n&quot;;
&lt;ctrl-d&gt;</b>
24
2
7.5
</pre>
</div>
<h2><a name="Introduction_nn10">2.5 Supported C/C++ language features</a>
</h2>
<p> A primary goal of the SWIG project is to make the language binding
 process extremely easy. Although a few simple examples have been shown,
 SWIG is quite capable in supporting most of C++. Some of the major
 features include:</p>
<ul>
<li>Full C99 preprocessing.</li>
<li>All ISO C and C++ datatypes.</li>
<li>Functions, variables, and constants.</li>
<li>Classes.</li>
<li>Single and multiple inheritance.</li>
<li>Overloaded functions and methods.</li>
<li>Overloaded operators.</li>
<li>C++ templates (including member templates, specialization, and
 partial specialization).</li>
<li>Namespaces.</li>
<li>Variable length arguments.</li>
<li>C++ smart pointers.</li>
</ul>
<p> Most of C++11 is also supported. Details are in the <a href="#CPlusPlus11">
C++11</a> chapter. C++14 support is covered in the <a href="#CPlusPlus14">
C++14</a> chapter. C++17 support is covered in the <a href="#CPlusPlus17">
C++17</a> chapter.</p>
<p> It is important to stress that SWIG is not a simplistic C++ lexing
 tool like several apparently similar wrapper generation tools. SWIG not
 only parses C++, it implements the full C++ type system and it is able
 to understand C++ semantics. SWIG generates its wrappers with full
 knowledge of this information. As a result, you will find SWIG to be
 just as capable of dealing with nasty corner cases as it is in wrapping
 simple C++ code. In fact, SWIG is able to handle C++ code that stresses
 the very limits of many C++ compilers.</p>
<h2><a name="Introduction_nn11">2.6 Non-intrusive interface building</a></h2>
<p> When used as intended, SWIG requires minimal (if any) modification
 to existing C or C++ code. This makes SWIG extremely easy to use with
 existing packages and promotes software reuse and modularity. By making
 the C/C++ code independent of the high level interface, you can change
 the interface and reuse the code in other applications. It is also
 possible to support different types of interfaces depending on the
 application.</p>
<h2><a name="Introduction_build_system">2.7 Incorporating SWIG into a
 build system</a></h2>
<p> SWIG is a command line tool and as such can be incorporated into any
 build system that supports invoking external tools/compilers. SWIG is
 most commonly invoked from within a Makefile, but is also known to be
 invoked from popular IDEs such as Microsoft Visual Studio.</p>
<p> If you are using the GNU Autotools (<a href="http://www.gnu.org/software/autoconf/">
Autoconf</a>/ <a href="http://www.gnu.org/software/automake/">Automake</a>
/ <a href="http://www.gnu.org/software/libtool/">Libtool</a>) to
 configure SWIG use in your project, the SWIG Autoconf macros can be
 used. The primary macro is <tt>ax_pkg_swig</tt>, see <a href="http://www.gnu.org/software/autoconf-archive/ax_pkg_swig.html#ax_pkg_swig">
http://www.gnu.org/software/autoconf-archive/ax_pkg_swig.html#ax_pkg_swig
</a>. The <tt>ax_python_devel</tt> macro is also helpful for generating
 Python extensions. See the <a href="http://www.gnu.org/software/autoconf-archive/">
Autoconf Archive</a> for further information on this and other Autoconf
 macros.</p>
<p> There is growing support for SWIG in some build tools, for example <a
href="https://cmake.org">CMake</a> is a cross-platform, open-source
 build manager with built in support for SWIG. CMake can detect the SWIG
 executable and many of the target language libraries for linking
 against. CMake knows how to build shared libraries and loadable modules
 on many different operating systems. This allows easy cross platform
 SWIG development. It can also generate the custom commands necessary
 for driving SWIG from IDEs and makefiles. All of this can be done from
 a single cross platform input file. The following example is a CMake
 input file for creating a Python wrapper for the SWIG interface file,
 example.i:</p>
<div class="code">
<pre>

# This is a CMake example for Python

FIND_PACKAGE(SWIG REQUIRED)
INCLUDE(${SWIG_USE_FILE})

FIND_PACKAGE(PythonLibs)
INCLUDE_DIRECTORIES(${PYTHON_INCLUDE_PATH})

INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR})

SET(CMAKE_SWIG_FLAGS &quot;&quot;)

SET_SOURCE_FILES_PROPERTIES(example.i PROPERTIES CPLUSPLUS ON)
SET_SOURCE_FILES_PROPERTIES(example.i PROPERTIES SWIG_FLAGS &quot;-includeall&quot;)
SWIG_ADD_MODULE(example python example.i example.cxx)
SWIG_LINK_LIBRARIES(example ${PYTHON_LIBRARIES})

</pre>
</div>
<p> The above example will generate native build files such as
 makefiles, nmake files and Visual Studio projects which will invoke
 SWIG and compile the generated C++ files into _example.so (UNIX) or
 _example.pyd (Windows). For other target languages on Windows a dll,
 instead of a .pyd file, is usually generated.</p>
<h2><a name="Introduction_nn12">2.8 Hands off code generation</a></h2>
<p> SWIG is designed to produce working code that needs no
 hand-modification (in fact, if you look at the output, you probably
 won't want to modify it). You should think of your target language
 interface being defined entirely by the input to SWIG, not the
 resulting output file. While this approach may limit flexibility for
 hard-core hackers, it allows others to forget about the low-level
 implementation details.</p>
<h2><a name="Introduction_nn13">2.9 SWIG and freedom</a></h2>
<p> No, this isn't a special section on the sorry state of world
 politics. However, it may be useful to know that SWIG was written with
 a certain &quot;philosophy&quot; about programming---namely that programmers are
 smart and that tools should just stay out of their way. Because of
 that, you will find that SWIG is extremely permissive in what it lets
 you get away with. In fact, you can use SWIG to go well beyond
 &quot;shooting yourself in the foot&quot; if dangerous programming is your goal.
 On the other hand, this kind of freedom may be exactly what is needed
 to work with complicated and unusual C/C++ applications.</p>
<p> Ironically, the freedom that SWIG provides is countered by an
 extremely conservative approach to code generation. At its core, SWIG
 tries to distill even the most advanced C++ code down to a small
 well-defined set of interface building techniques based on ISO C
 programming. Because of this, you will find that SWIG interfaces can be
 easily compiled by virtually every C/C++ compiler and that they can be
 used on any platform. Again, this is an important part of staying out
 of the programmer's way----the last thing any developer wants to do is
 to spend their time debugging the output of a tool that relies on
 non-portable or unreliable programming features. Dependencies are often
 a source of incompatibilities and problems and so additional third
 party libraries are not used in the generated code. SWIG will also
 generally avoid generating code that introduces a dependency on the C++
 Standard Template Library (STL). SWIG will generate code that depends
 on the C libraries though.</p>
<HR NOSHADE>
<h1><a name="Windows">3 Getting started on Windows</a></h1>

<!-- INDEX -->
<div class="sectiontoc">
<ul>
<li><a href="#Windows_installation">Installation on Windows</a>
<ul>
<li><a href="#Windows_executable">Windows Executable</a></li>
</ul>
</li>
<li><a href="#Windows_examples">SWIG Windows Examples</a>
<ul>
<li><a href="#Windows_visual_studio">Instructions for using the Examples
 with Visual Studio</a>
<ul>
<li><a href="#Windows_csharp">C#</a></li>
<li><a href="#Windows_java">Java</a></li>
<li><a href="#Windows_perl">Perl</a></li>
<li><a href="#Windows_python">Python</a></li>
<li><a href="#Windows_tcl">TCL</a></li>
<li><a href="#Windows_r">R</a></li>
<li><a href="#Windows_ruby">Ruby</a></li>
</ul>
</li>
<li><a href="#Windows_other_compilers">Instructions for using the
 Examples with other compilers</a></li>
</ul>
</li>
<li><a href="#Windows_cygwin_mingw">SWIG on Cygwin and MinGW</a>
<ul>
<li><a href="#Windows_swig_exe">Building swig.exe on Windows</a>
<ul>
<li><a href="#Windows_mingw_msys">Building swig.exe using MinGW and MSYS</a>
</li>
<li><a href="#Windows_cygwin">Building swig.exe using Cygwin</a></li>
<li><a href="#Windows_building_alternatives">Building swig.exe
 alternatives</a></li>
</ul>
</li>
<li><a href="#Windows_examples_cygwin">Running the examples on Windows
 using Cygwin</a></li>
</ul>
</li>
<li><a href="#Windows_interface_file">Microsoft extensions and other
 Windows quirks</a></li>
</ul>
</div>
<!-- INDEX -->
<p> This chapter describes SWIG usage on Microsoft Windows. Installing
 SWIG and running the examples is covered as well as building the SWIG
 executable. Usage within the Unix like environments MinGW and Cygwin is
 also detailed.</p>
<h2><a name="Windows_installation">3.1 Installation on Windows</a></h2>
<p> SWIG does not come with the usual Windows type installation program,
 however it is quite easy to get started. The main steps are:</p>
<ul>
<li>Download the swigwin zip package from the <a href="http://www.swig.org">
SWIG website</a> and unzip into a directory. This is all that needs
 downloading for the Windows platform.</li>
<li>Set environment variables as described in the <a href="#Windows_examples">
SWIG Windows Examples</a> section in order to run examples using Visual
 C++.</li>
</ul>
<h3><a name="Windows_executable">3.1.1 Windows Executable</a></h3>
<p> The swigwin distribution contains the SWIG Windows 32-bit
 executable, swig.exe, which will run on both 32-bit and 64-bit versions
 of Windows. If you want to build your own swig.exe have a look at <a href="#Windows_swig_exe">
Building swig.exe on Windows</a>.</p>
<h2><a name="Windows_examples">3.2 SWIG Windows Examples</a></h2>
<p> Using Microsoft Visual C++ is the most common approach to compiling
 and linking SWIG's output. The Examples directory has a few Visual C++
 project files (.dsp files). These were produced by Visual C++ 6. Newer
 versions of Visual Studio should be able to open and convert these
 project files. Each C# example comes with a Visual Studio 2005 solution
 and associated project files instead of Visual C++ 6 project files. The
 project files have been set up to execute SWIG in a custom build rule
 for the SWIG interface (.i) file. Alternatively run the <a href="#Windows_examples_cygwin">
examples using Cygwin</a>.</p>
<p> More information on each of the examples is available with the
 examples distributed with SWIG (Examples/index.html).</p>
<h3><a name="Windows_visual_studio">3.2.1 Instructions for using the
 Examples with Visual Studio</a></h3>
<p> Ensure the SWIG executable is as supplied in the SWIG root directory
 in order for the examples to work. Most languages require some
 environment variables to be set<b> before</b> running Visual C++. Note
 that Visual C++ must be re-started to pick up any changes in
 environment variables. Open up an example .dsp file, Visual C++ will
 create a workspace for you (.dsw file). Ensure the Release build is
 selected then do a Rebuild All from the Build menu. The required
 environment variables are displayed with their current values.</p>
<p> The list of required environment variables for each module language
 is also listed below. They are usually set from the Control Panel and
 System properties, but this depends on which flavour of Windows you are
 running. If you don't want to use environment variables then change all
 occurrences of the environment variables in the .dsp files with hard
 coded values. If you are interested in how the project files are set up
 there is explanatory information in some of the language module's
 documentation.</p>
<h4><a name="Windows_csharp">3.2.1.1 C#</a></h4>
<p> The C# examples do not require any environment variables to be set
 as a C# project file is included. Just open up the .sln solution file
 in Visual Studio .NET 2003 or later, select Release Build, and do a
 Rebuild All from the Build menu. The accompanying C# and C++ project
 files are automatically used by the solution file.</p>
<h4><a name="Windows_java">3.2.1.2 Java</a></h4>
<p><b> <tt>JAVA_INCLUDE</tt></b> : Set this to the directory containing
 jni.h
<br><b> <tt>JAVA_BIN</tt></b> : Set this to the bin directory containing
 javac.exe</p>
<p> Example using JDK1.3:
<br> <tt>JAVA_INCLUDE: D:\jdk1.3\include
<br> JAVA_BIN: D:\jdk1.3\bin
<br></tt></p>
<h4><a name="Windows_perl">3.2.1.3 Perl</a></h4>
<p><b> <tt>PERL5_INCLUDE</tt></b> : Set this to the directory containing
 perl.h
<br><b> <tt>PERL5_LIB</tt></b> : Set this to the Perl library including
 path for linking</p>
<p> Example using nsPerl 5.004_04:</p>
<p> <tt>PERL5_INCLUDE: D:\nsPerl5.004_04\lib\CORE
<br> PERL5_LIB: D:\nsPerl5.004_04\lib\CORE\perl.lib
<br></tt></p>
<h4><a name="Windows_python">3.2.1.4 Python</a></h4>
<p><b> <tt>PYTHON_INCLUDE</tt></b> : Set this to the directory that
 contains Python.h
<br><b> <tt>PYTHON_LIB</tt></b> : Set this to the Python library
 including path for linking</p>
<p> Example using Python 2.1.1:
<br> <tt>PYTHON_INCLUDE: D:\python21\include
<br> PYTHON_LIB: D:\python21\libs\python21.lib
<br></tt></p>
<h4><a name="Windows_tcl">3.2.1.5 TCL</a></h4>
<p><b> <tt>TCL_INCLUDE</tt></b> : Set this to the directory containing
 tcl.h
<br><b> <tt>TCL_LIB</tt></b> : Set this to the TCL library including
 path for linking</p>
<p> Example using ActiveTcl 8.3.3.3
<br> <tt>TCL_INCLUDE: D:\tcl\include
<br> TCL_LIB: D:\tcl\lib\tcl83.lib
<br></tt></p>
<h4><a name="Windows_r">3.2.1.6 R</a></h4>
<p><b> <tt>R_INCLUDE</tt></b> : Set this to the directory containing R.h
<br><b> <tt>R_LIB</tt></b> : Set this to the R library (Rdll.lib)
 including path for linking. The library needs to be built as described
 in the R README.packages file (the pexports.exe approach is the
 easiest).</p>
<p> Example using R 2.5.1:
<br> <tt>R_INCLUDE: C:\Program Files\R\R-2.5.1\include
<br> R_LIB: C:\Program Files\R\R-2.5.1\bin\Rdll.lib
<br></tt></p>
<h4><a name="Windows_ruby">3.2.1.7 Ruby</a></h4>
<p><b> <tt>RUBY_INCLUDE</tt></b> : Set this to the directory containing
 ruby.h
<br><b> <tt>RUBY_LIB</tt></b> : Set this to the ruby library including
 path for linking</p>
<p> Example using Ruby 1.6.4:
<br> <tt>RUBY_INCLUDE: D:\ruby\lib\ruby\1.6\i586-mswin32
<br> RUBY_LIB: D:\ruby\lib\mswin32-ruby16.lib
<br></tt></p>
<h3><a name="Windows_other_compilers">3.2.2 Instructions for using the
 Examples with other compilers</a></h3>
<p> If you do not have access to Visual C++ you will have to set up
 project files / Makefiles for your chosen compiler. There is a section
 in each of the language modules detailing what needs setting up using
 Visual C++ which may be of some guidance. Alternatively you may want to
 use Cygwin as described in the following section.</p>
<h2><a name="Windows_cygwin_mingw">3.3 SWIG on Cygwin and MinGW</a></h2>
<p> SWIG can also be compiled and run using <a href="http://www.cygwin.com">
Cygwin</a> or <a href="http://www.mingw.org">MinGW</a> which provides a
 Unix like front end to Windows and comes free with gcc, an ISO C/C++
 compiler. However, this is not a recommended approach as the prebuilt
 executable is supplied.</p>
<h3><a name="Windows_swig_exe">3.3.1 Building swig.exe on Windows</a></h3>
<p> If you want to replicate the build of swig.exe that comes with the
 download, follow the MinGW instructions below. This is not necessary to
 use the supplied swig.exe. This information is provided for those that
 want to modify the SWIG source code in a Windows environment. Normally
 this is not needed, so most people will want to ignore this section.</p>
<h4><a name="Windows_mingw_msys">3.3.1.1 Building swig.exe using MinGW
 and MSYS</a></h4>
<p> The short abbreviated instructions follow...</p>
<ul>
<li>Install MinGW and MSYS from the <a href="http://www.mingw.org">MinGW</a>
 site. This provides a Unix environment on Windows.</li>
<li>Follow the usual Unix instructions in the README file in the SWIG
 root directory to build swig.exe from the MinGW command prompt.</li>
</ul>
<p> The step by step instructions to download and install MinGW and
 MSYS, then download and build the latest version of SWIG from Github
 follow... Note that the instructions for obtaining SWIG from Github are
 also online at <a href="http://www.swig.org/svn.html">SWIG Bleeding
 Edge</a>.</p>
<p><b> Pitfall note:</b> Execute the steps in the order shown and don't
 use spaces in path names. In fact it is best to use the default
 installation directories.</p>
<ol>
<li> Download the following packages from the <a href="http://www.mingw.org/download.shtml">
MinGW download page</a> or <a href="https://sourceforge.net/projects/mingw/files/">
MinGW SourceForge download page</a>. Note that at the time of writing,
 the majority of these are in the Current release list and some are in
 the Snapshot or Previous release list.
<ul>
<li>MinGW-3.1.0-1.exe</li>
<li>MSYS-1.0.11-2004.04.30-1.exe</li>
<li>msysDTK-1.0.1.exe</li>
<li>bison-2.0-MSYS.tar.gz</li>
<li>msys-autoconf-2.59.tar.bz2</li>
<li>msys-automake-1.8.2.tar.bz2</li>
</ul>
</li>
<li> Install MinGW-3.1.0-1.exe (C:\MinGW is default location.)</li>
<li> Install MSYS-1.0.11-2004.04.30-1.exe. Make sure you install it on
 the same windows drive letter as MinGW (C:\msys\1.0 is default). In the
 post install script,
<ul>
<li>Answer y to the &quot;do you wish to continue with the post install?&quot;</li>
<li>Answer y to the &quot;do you have MinGW installed?&quot;</li>
<li>Type in the folder in which you installed MinGW (C:/MinGW is
 default)</li>
</ul>
</li>
<li> Install msysDTK-1.0.1.exe to the same folder that you installed
 MSYS (C:\msys\1.0 is default).</li>
<li> Copy the following to the MSYS install folder (C:\msys\1.0 is
 default):
<ul>
<li>msys-automake-1.8.2.tar.bz2</li>
<li>msys-autoconf-2.59.tar.bz2</li>
<li>bison-2.0-MSYS.tar.gz</li>
</ul>
</li>
<li> Start the MSYS command prompt and execute:<div class="shell">
<pre>
cd /
tar -jxf msys-automake-1.8.2.tar.bz2
tar -jxf msys-autoconf-2.59.tar.bz2
tar -zxf bison-2.0-MSYS.tar.gz
</pre>
</div></li>
<li> The very latest development version of SWIG is available from <a href="https://github.com/swig/swig">
SWIG on Github</a> and can be downloaded as a zip file or if you have
 Git installed, via Git. Either download the latest <a href="https://github.com/swig/swig/archive/master.zip">
Zip file</a> snapshot and unzip and rename the top level folder to
 /usr/src/swig. Otherwise if using Git, type in the following:<div class="shell">
<pre>
mkdir /usr/src
cd /usr/src
git clone https://github.com/swig/swig.git
</pre>
</div><b> Pitfall note:</b> If you want to place SWIG in a different
 folder to the proposed /usr/src/swig, do not use MSYS emulated windows
 drive letters, because the autotools will fail miserably on those.</li>
<li> The PCRE third party library needs to be built next. Download the
 latest PCRE source tarball, such as <tt>pcre-8.10.tar.bz2</tt>, from <a href="http://www.pcre.org">
PCRE</a> and place in the <tt>/usr/src/swig</tt> directory. Build PCRE
 as a static library using the Tools/pcre-build.sh script as follows:<div
class="shell">
<pre>
cd /usr/src/swig
Tools/pcre-build.sh
</pre>
</div></li>
<li> You are now ready to build SWIG. Execute the following commands to
 build swig.exe:<div class="shell">
<pre>
cd /usr/src/swig
./autogen.sh
./configure
make
</pre>
</div></li>
</ol>
<h4><a name="Windows_cygwin">3.3.1.2 Building swig.exe using Cygwin</a></h4>
<p> Note that SWIG can also be built using Cygwin. However, SWIG will
 then require the Cygwin DLL when executing. Follow the Unix
 instructions in the README file in the SWIG root directory. Note that
 the Cygwin environment will also allow one to regenerate the autotool
 generated files which are supplied with the release distribution. These
 files are generated using the <tt>autogen.sh</tt> script and will only
 need regenerating in circumstances such as changing the build system.</p>
<h4><a name="Windows_building_alternatives">3.3.1.3 Building swig.exe
 alternatives</a></h4>
<p> If you don't want to install Cygwin or MinGW, use a different
 compiler to build SWIG. For example, all the source code files can be
 added to a Visual C++ project file in order to build swig.exe from the
 Visual C++ IDE.</p>
<h3><a name="Windows_examples_cygwin">3.3.2 Running the examples on
 Windows using Cygwin</a></h3>
<p> The examples and test-suite work as successfully on Cygwin as on any
 other Unix operating system. The modules which are known to work are
 Python, Tcl, Perl, Ruby, Java and C#. Follow the Unix instructions in
 the README file in the SWIG root directory to build the examples.</p>
<h2><a name="Windows_interface_file">3.4 Microsoft extensions and other
 Windows quirks</a></h2>
<p> A common problem when using SWIG on Windows are the Microsoft
 function calling conventions which are not in the C++ standard. SWIG
 parses ISO C/C++ so cannot deal with proprietary conventions such as <tt>
__declspec(dllimport)</tt>, <tt>__stdcall</tt> etc. There is a Windows
 interface file, <tt>windows.i</tt>, to deal with these calling
 conventions though. The file also contains typemaps for handling
 commonly used Windows specific types such as <tt>__int64</tt>, <tt>BOOL</tt>
, <tt>DWORD</tt> etc. Include it like you would any other interface
 file, for example:</p>
<div class="code">
<pre>
%include &lt;windows.i&gt;

__declspec(dllexport) ULONG __stdcall foo(DWORD, __int32);
</pre>
</div>
<p>Note that if you follow Microsoft's recommendation of wrapping the <tt>
__declspec</tt> calls in a preprocessor definition, you will need to
 make sure that the definition is included by SWIG as well, by either
 defining it manually or via a header. For example, if you have
 specified the preprocessor definition in a header named <tt>
export_lib.h</tt> and include other headers which depend on it, you
 should use the <tt>%include</tt> directive to include the definition
 explicitly. For example, if you had a header file, <tt>bar.h</tt>,
 which depended on <tt>export_lib.h</tt>, your SWIG definition file
 might look like:</p>
<div class="code">
<pre>
// bar.i
%module bar
%include &lt;windows.i&gt;
%include &quot;export_lib.h&quot;
%include &quot;bar.h&quot;
</pre>
</div>
<p> where export_lib.h may contain:</p>
<div class="code">
<pre>
// export_lib.h
#define BAR_API __declspec(dllexport)
</pre>
</div>
<p> and bar.h may look like:</p>
<div class="code">
<pre>
// bar.h
#include &quot;export_lib.h&quot;
BAR_API void bar_function(int, double);
</pre>
</div>
<p> Using the preprocessor to remove BAR_API is a popular simpler
 solution:</p>
<div class="code">
<pre>
// bar.i
%module bar
#define BAR_API
%include &quot;bar.h&quot;
</pre>
</div><HR NOSHADE>
<h1><a name="Scripting">4 Scripting Languages</a></h1>

<!-- INDEX -->
<div class="sectiontoc">
<ul>
<li><a href="#Scripting_nn2">The two language view of the world</a></li>
<li><a href="#Scripting_nn3">How does a scripting language talk to C?</a>
<ul>
<li><a href="#Scripting_nn4">Wrapper functions</a></li>
<li><a href="#Scripting_nn5">Variable linking</a></li>
<li><a href="#Scripting_nn6">Constants</a></li>
<li><a href="#Scripting_nn7">Structures and classes</a></li>
<li><a href="#Scripting_nn8">Proxy classes</a></li>
</ul>
</li>
<li><a href="#Scripting_nn9">Building scripting language extensions</a>
<ul>
<li><a href="#Scripting_nn10">Shared libraries and dynamic loading</a></li>
<li><a href="#Scripting_nn11">Linking with shared libraries</a></li>
<li><a href="#Scripting_nn12">Static linking</a></li>
</ul>
</li>
</ul>
</div>
<!-- INDEX -->
<p> This chapter provides a brief overview of scripting language
 extension programming and the mechanisms by which scripting language
 interpreters access C and C++ code.</p>
<h2><a name="Scripting_nn2">4.1 The two language view of the world</a></h2>
<p> When a scripting language is used to control a C program, the
 resulting system tends to look as follows:</p>
<center><img alt="Scripting language input - C/C++ functions output" HEIGHT="149"
src="ch2.1.png" WIDTH="377"></center>
<p> In this programming model, the scripting language interpreter is
 used for high level control whereas the underlying functionality of the
 C/C++ program is accessed through special scripting language
 &quot;commands.&quot; If you have ever tried to write your own simple command
 interpreter, you might view the scripting language approach to be a
 highly advanced implementation of that. Likewise, If you have ever used
 a package such as MATLAB or IDL, it is a very similar model--the
 interpreter executes user commands and scripts. However, most of the
 underlying functionality is written in a low-level language like C or
 Fortran.</p>
<p> The two-language model of computing is extremely powerful because it
 exploits the strengths of each language. C/C++ can be used for maximal
 performance and complicated systems programming tasks. Scripting
 languages can be used for rapid prototyping, interactive debugging,
 scripting, and access to high-level data structures such associative
 arrays.</p>
<h2><a name="Scripting_nn3">4.2 How does a scripting language talk to C?</a>
</h2>
<p> Scripting languages are built around a parser that knows how to
 execute commands and scripts. Within this parser, there is a mechanism
 for executing commands and accessing variables. Normally, this is used
 to implement the builtin features of the language. However, by
 extending the interpreter, it is usually possible to add new commands
 and variables. To do this, most languages define a special API for
 adding new commands. Furthermore, a special foreign function interface
 defines how these new commands are supposed to hook into the
 interpreter.</p>
<p> Typically, when you add a new command to a scripting interpreter you
 need to do two things; first you need to write a special &quot;wrapper&quot;
 function that serves as the glue between the interpreter and the
 underlying C function. Then you need to give the interpreter
 information about the wrapper by providing details about the name of
 the function, arguments, and so forth. The next few sections illustrate
 the process.</p>
<h3><a name="Scripting_nn4">4.2.1 Wrapper functions</a></h3>
<p> Suppose you have an ordinary C function like this :</p>
<div class="code">
<pre>
int fact(int n) {
  if (n &lt;= 1)
    return 1;
  else
    return n*fact(n-1);
}
</pre>
</div>
<p> In order to access this function from a scripting language, it is
 necessary to write a special &quot;wrapper&quot; function that serves as the glue
 between the scripting language and the underlying C function. A wrapper
 function must do three things :</p>
<ul>
<li>Gather function arguments and make sure they are valid.</li>
<li>Call the C function.</li>
<li>Convert the return value into a form recognized by the scripting
 language.</li>
</ul>
<p> As an example, the Tcl wrapper function for the <tt>fact()</tt>
 function above example might look like the following :</p>
<div class="code">
<pre>
int wrap_fact(ClientData clientData, Tcl_Interp *interp, int argc, char *argv[]) {
  int result;
  int arg0;
  if (argc != 2) {
    interp-&gt;result = &quot;wrong # args&quot;;
    return TCL_ERROR;
  }
  arg0 = atoi(argv[1]);
  result = fact(arg0);
  sprintf(interp-&gt;result, &quot;%d&quot;, result);
  return TCL_OK;
}

</pre>
</div>
<p> Once you have created a wrapper function, the final step is to tell
 the scripting language about the new function. This is usually done in
 an initialization function called by the language when the module is
 loaded. For example, adding the above function to the Tcl interpreter
 requires code like the following :</p>
<div class="code">
<pre>
int Wrap_Init(Tcl_Interp *interp) {
  Tcl_CreateCommand(interp, &quot;fact&quot;, wrap_fact, (ClientData) NULL,
                    (Tcl_CmdDeleteProc *) NULL);
  return TCL_OK;
}
</pre>
</div>
<p> When executed, Tcl will now have a new command called &quot;<tt>fact</tt>
&quot; that you can use like any other Tcl command.</p>
<p> Although the process of adding a new function to Tcl has been
 illustrated, the procedure is almost identical for Perl and Python.
 Both require special wrappers to be written and both need additional
 initialization code. Only the specific details are different.</p>
<h3><a name="Scripting_nn5">4.2.2 Variable linking</a></h3>
<p> Variable linking refers to the problem of mapping a C/C++ global
 variable to a variable in the scripting language interpreter. For
 example, suppose you had the following variable:</p>
<div class="code">
<pre>
double Foo = 3.5;
</pre>
</div>
<p> It might be nice to access it from a script as follows (shown for
 Perl):</p>
<div class="targetlang">
<pre>
$a = $Foo * 2.3;   # Evaluation
$Foo = $a + 2.0;   # Assignment
</pre>
</div>
<p> To provide such access, variables are commonly manipulated using a
 pair of get/set functions. For example, whenever the value of a
 variable is read, a &quot;get&quot; function is invoked. Similarly, whenever the
 value of a variable is changed, a &quot;set&quot; function is called.</p>
<p> In many languages, calls to the get/set functions can be attached to
 evaluation and assignment operators. Therefore, evaluating a variable
 such as <tt>$Foo</tt> might implicitly call the get function.
 Similarly, typing <tt>$Foo = 4</tt> would call the underlying set
 function to change the value.</p>
<h3><a name="Scripting_nn6">4.2.3 Constants</a></h3>
<p> In many cases, a C program or library may define a large collection
 of constants. For example:</p>
<div class="code">
<pre>
#define RED   0xff0000
#define BLUE  0x0000ff
#define GREEN 0x00ff00
</pre>
</div>
<p> To make constants available, their values can be stored in scripting
 language variables such as <tt>$RED</tt>, <tt>$BLUE</tt>, and <tt>
$GREEN</tt>. Virtually all scripting languages provide C functions for
 creating variables so installing constants is usually a trivial
 exercise.</p>
<h3><a name="Scripting_nn7">4.2.4 Structures and classes</a></h3>
<p> Although scripting languages have no trouble accessing simple
 functions and variables, accessing C/C++ structures and classes present
 a different problem. This is because the implementation of structures
 is largely related to the problem of data representation and layout.
 Furthermore, certain language features are difficult to map to an
 interpreter. For instance, what does C++ inheritance mean in a Perl
 interface?</p>
<p> The most straightforward technique for handling structures is to
 implement a collection of accessor functions that hide the underlying
 representation of a structure. For example,</p>
<div class="code">
<pre>
struct Vector {
  Vector();
  ~Vector();
  double x, y, z;
};

</pre>
</div>
<p> can be transformed into the following set of functions :</p>
<div class="code">
<pre>
Vector *new_Vector();
void delete_Vector(Vector *v);
double Vector_x_get(Vector *v);
double Vector_y_get(Vector *v);
double Vector_z_get(Vector *v);
void Vector_x_set(Vector *v, double x);
void Vector_y_set(Vector *v, double y);
void Vector_z_set(Vector *v, double z);

</pre>
</div>
<p> Now, from an interpreter these function might be used as follows:</p>
<div class="targetlang">
<pre>
% set v [new_Vector]
% Vector_x_set $v 3.5
% Vector_y_get $v
% delete_Vector $v
% ...
</pre>
</div>
<p> Since accessor functions provide a mechanism for accessing the
 internals of an object, the interpreter does not need to know anything
 about the actual representation of a <tt>Vector</tt>.</p>
<h3><a name="Scripting_nn8">4.2.5 Proxy classes</a></h3>
<p> In certain cases, it is possible to use the low-level accessor
 functions to create a proxy class, also known as a shadow class. A
 proxy class is a special kind of object that gets created in a
 scripting language to access a C/C++ class (or struct) in a way that
 looks like the original structure (that is, it proxies the real C++
 class). For example, if you have the following C++ definition :</p>
<div class="code">
<pre>
class Vector {
public:
  Vector();
  ~Vector();
  double x, y, z;
};
</pre>
</div>
<p> A proxy classing mechanism would allow you to access the structure
 in a more natural manner from the interpreter. For example, in Python,
 you might want to do this:</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; v = Vector()
&gt;&gt;&gt; v.x = 3
&gt;&gt;&gt; v.y = 4
&gt;&gt;&gt; v.z = -13
&gt;&gt;&gt; ...
&gt;&gt;&gt; del v
</pre>
</div>
<p> Similarly, in Perl5 you may want the interface to work like this:</p>
<div class="targetlang">
<pre>
$v = new Vector;
$v-&gt;{x} = 3;
$v-&gt;{y} = 4;
$v-&gt;{z} = -13;

</pre>
</div>
<p> Finally, in Tcl :</p>
<div class="targetlang">
<pre>
Vector v
v configure -x 3 -y 4 -z -13

</pre>
</div>
<p> When proxy classes are used, two objects are really at work--one in
 the scripting language, and an underlying C/C++ object. Operations
 affect both objects equally and for all practical purposes, it appears
 as if you are simply manipulating a C/C++ object.</p>
<h2><a name="Scripting_nn9">4.3 Building scripting language extensions</a>
</h2>
<p> The final step in using a scripting language with your C/C++
 application is adding your extensions to the scripting language itself.
 There are two primary approaches for doing this. The preferred
 technique is to build a dynamically loadable extension in the form of a
 shared library. Alternatively, you can recompile the scripting language
 interpreter with your extensions added to it.</p>
<h3><a name="Scripting_nn10">4.3.1 Shared libraries and dynamic loading</a>
</h3>
<p> To create a shared library or DLL, you often need to look at the
 manual pages for your compiler and linker. However, the procedure for a
 few common platforms is shown below:</p>
<div class="shell">
<pre>
# Build a shared library for Solaris
gcc -fpic -c example.c example_wrap.c -I/usr/local/include
ld -G example.o example_wrap.o -o example.so

# Build a shared library for Linux
gcc -fpic -c example.c example_wrap.c -I/usr/local/include
gcc -shared example.o example_wrap.o -o example.so
</pre>
</div>
<p> To use your shared library, you simply use the corresponding command
 in the scripting language (load, import, use, etc...). This will import
 your module and allow you to start using it. For example:</p>
<div class="targetlang">
<pre>
% load ./example.so
% fact 4
24
%
</pre>
</div>
<p> When working with C++ codes, the process of building shared
 libraries may be more complicated--primarily due to the fact that C++
 modules may need additional code in order to operate correctly. On many
 machines, you can build a shared C++ module by following the above
 procedures, but changing the link line to the following :</p>
<div class="shell">
<pre>
c++ -shared example.o example_wrap.o -o example.so
</pre>
</div>
<h3><a name="Scripting_nn11">4.3.2 Linking with shared libraries</a></h3>
<p> When building extensions as shared libraries, it is not uncommon for
 your extension to rely upon other shared libraries on your machine. In
 order for the extension to work, it needs to be able to find all of
 these libraries at run-time. Otherwise, you may get an error such as
 the following :</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; import graph
Traceback (innermost last):
  File &quot;&lt;stdin&gt;&quot;, line 1, in ?
  File &quot;/home/sci/data1/beazley/graph/graph.py&quot;, line 2, in ?
    import graphc
ImportError:  1101:/home/sci/data1/beazley/bin/python: rld: Fatal Error: cannot 
successfully map soname 'libgraph.so' under any of the filenames /usr/lib/libgraph.so:/
lib/libgraph.so:/lib/cmplrs/cc/libgraph.so:/usr/lib/cmplrs/cc/libgraph.so:
&gt;&gt;&gt;
</pre>
</div>
<p> What this error means is that the extension module created by SWIG
 depends upon a shared library called &quot;<tt>libgraph.so</tt>&quot; that the
 system was unable to locate. To fix this problem, there are a few
 approaches you can take.</p>
<ul>
<li>Link your extension and explicitly tell the linker where the
 required libraries are located. Often times, this can be done with a
 special linker flag such as <tt>-R</tt>, <tt>-rpath</tt>, etc. This is
 not implemented in a standard manner so read the man pages for your
 linker to find out more about how to set the search path for shared
 libraries.</li>
<li>Put shared libraries in the same directory as the executable. This
 technique is sometimes required for correct operation on non-Unix
 platforms.</li>
<li>Set the UNIX environment variable <tt>LD_LIBRARY_PATH</tt> to the
 directory where shared libraries are located before running Python.
 Although this is an easy solution, it is not recommended. Consider
 setting the path using linker options instead.</li>
</ul>
<h3><a name="Scripting_nn12">4.3.3 Static linking</a></h3>
<p> With static linking, you rebuild the scripting language interpreter
 with extensions. The process usually involves compiling a short main
 program that adds your customized commands to the language and starts
 the interpreter. You then link your program with a library to produce a
 new scripting language executable.</p>
<p> Although static linking is supported on all platforms, this is not
 the preferred technique for building scripting language extensions. In
 fact, there are very few practical reasons for doing this--consider
 using shared libraries instead.</p>
<HR NOSHADE>
<h1><a name="SWIG">5 SWIG Basics</a></h1>

<!-- INDEX -->
<div class="sectiontoc">
<ul>
<li><a href="#SWIG_nn2">Running SWIG</a>
<ul>
<li><a href="#SWIG_nn3">Input format</a></li>
<li><a href="#SWIG_output">SWIG Output</a></li>
<li><a href="#SWIG_nn5">Comments</a></li>
<li><a href="#SWIG_nn6">C Preprocessor</a></li>
<li><a href="#SWIG_nn7">SWIG Directives</a></li>
<li><a href="#SWIG_nn8">Parser Limitations</a></li>
</ul>
</li>
<li><a href="#SWIG_nn9">Wrapping Simple C Declarations</a>
<ul>
<li><a href="#SWIG_nn10">Basic Type Handling</a></li>
<li><a href="#SWIG_nn11">Global Variables</a></li>
<li><a href="#SWIG_nn12">Constants</a></li>
<li><a href="#SWIG_nn13">A brief word about const</a></li>
<li><a href="#SWIG_nn14">A cautionary tale of char *</a></li>
</ul>
</li>
<li><a href="#SWIG_nn15">Pointers and complex objects</a>
<ul>
<li><a href="#SWIG_nn16">Simple pointers</a></li>
<li><a href="#SWIG_nn17">Run time pointer type checking</a></li>
<li><a href="#SWIG_nn18">Derived types, structs, and classes</a></li>
<li><a href="#SWIG_nn19">Undefined datatypes</a></li>
<li><a href="#SWIG_nn20">Typedef</a></li>
</ul>
</li>
<li><a href="#SWIG_nn21">Other Practicalities</a>
<ul>
<li><a href="#SWIG_nn22">Passing structures by value</a></li>
<li><a href="#SWIG_nn23">Return by value</a></li>
<li><a href="#SWIG_nn24">Linking to structure variables</a></li>
<li><a href="#SWIG_nn25">Linking to char *</a></li>
<li><a href="#SWIG_nn26">Arrays</a></li>
<li><a href="#SWIG_readonly_variables">Creating read-only variables</a></li>
<li><a href="#SWIG_rename_ignore">Renaming and ignoring declarations</a>
<ul>
<li><a href="#SWIG_nn29">Simple renaming of specific identifiers</a></li>
<li><a href="#SWIG_advanced_renaming">Advanced renaming support</a></li>
<li><a href="#SWIG_limiting_renaming">Limiting global renaming rules</a></li>
<li><a href="#SWIG_chosen_unignore">Ignoring everything then wrapping a
 few selected symbols</a></li>
</ul>
</li>
<li><a href="#SWIG_default_args">Default/optional arguments</a></li>
<li><a href="#SWIG_nn30">Pointers to functions and callbacks</a></li>
</ul>
</li>
<li><a href="#SWIG_nn31">Structures and unions</a>
<ul>
<li><a href="#SWIG_nn32">Typedef and structures</a></li>
<li><a href="#SWIG_nn33">Character strings and structures</a></li>
<li><a href="#SWIG_nn34">Array members</a></li>
<li><a href="#SWIG_structure_data_members">Structure data members</a></li>
<li><a href="#SWIG_nn36">C constructors and destructors</a></li>
<li><a href="#SWIG_adding_member_functions">Adding member functions to C
 structures</a></li>
<li><a href="#SWIG_nested_structs">Nested structures</a></li>
<li><a href="#SWIG_nn39">Other things to note about structure wrapping</a>
</li>
</ul>
</li>
<li><a href="#SWIG_nn40">Code Insertion</a>
<ul>
<li><a href="#SWIG_nn41">The output of SWIG</a></li>
<li><a href="#SWIG_nn42">Code insertion blocks</a></li>
<li><a href="#SWIG_nn43">Inlined code blocks</a></li>
<li><a href="#SWIG_nn44">Initialization blocks</a></li>
</ul>
</li>
<li><a href="#SWIG_nn45">An Interface Building Strategy</a>
<ul>
<li><a href="#SWIG_nn46">Preparing a C program for SWIG</a></li>
<li><a href="#SWIG_nn47">The SWIG interface file</a></li>
<li><a href="#SWIG_nn48">Why use separate interface files?</a></li>
<li><a href="#SWIG_nn49">Getting the right header files</a></li>
<li><a href="#SWIG_nn50">What to do with main()</a></li>
</ul>
</li>
</ul>
</div>
<!-- INDEX -->
<p> This chapter describes the basic operation of SWIG, the structure of
 its input files, and how it handles standard ISO C declarations. C++
 support is described in the next chapter. However, C++ programmers
 should still read this chapter to understand the basics. Specific
 details about each target language are described in later chapters.</p>
<h2><a name="SWIG_nn2">5.1 Running SWIG</a></h2>
<p> To run SWIG, use the <tt>swig</tt> command with options and a
 filename like this:</p>
<div class="shell">
<pre>
swig [ options ] filename
</pre>
</div>
<p> where <tt>filename</tt> is a SWIG interface file or a C/C++ header
 file. Full help can be seen by running <tt>swig -help</tt>. Below is
 the common set of options that can be used. Additional options are also
 defined for each target language. A full list can be obtained by
 running <tt>swig<em> -&lt;lang&gt;</em> -help</tt> for language<em> &lt;lang&gt;</em>
 specific options, for example, <tt>swig -ruby -help</tt> for Ruby.</p>
<div class="shell">
<pre>
Supported Target Language Options
     -csharp         - Generate C# wrappers
     -d              - Generate D wrappers
     -go             - Generate Go wrappers
     -guile          - Generate Guile wrappers
     -java           - Generate Java wrappers
     -javascript     - Generate Javascript wrappers
     -lua            - Generate Lua wrappers
     -octave         - Generate Octave wrappers
     -perl5          - Generate Perl 5 wrappers
     -php7           - Generate PHP 7 wrappers
     -python         - Generate Python wrappers
     -r              - Generate R (aka GNU S) wrappers
     -ruby           - Generate Ruby wrappers
     -scilab         - Generate Scilab wrappers
     -tcl8           - Generate Tcl 8 wrappers
     -xml            - Generate XML wrappers

Experimental Target Language Options
     -mzscheme       - Generate MzScheme/Racket wrappers
     -ocaml          - Generate OCaml wrappers

General Options
     -addextern      - Add extra extern declarations
     -c++            - Enable C++ processing
     -co &lt;file&gt;      - Check &lt;file&gt; out of the SWIG library
     -copyctor       - Automatically generate copy constructors wherever possible
     -cpperraswarn   - Treat the preprocessor #error statement as #warning (default)
     -cppext &lt;ext&gt;   - Change file extension of generated C++ files to &lt;ext&gt;
                       (default is cxx)
     -copyright      - Display copyright notices
     -debug-classes  - Display information about the classes found in the interface
     -debug-module &lt;n&gt;- Display module parse tree at stages 1-4, &lt;n&gt; is a csv list of stages
     -debug-symtabs  - Display symbol tables information
     -debug-symbols  - Display target language symbols in the symbol tables
     -debug-csymbols - Display C symbols in the symbol tables
     -debug-lsymbols - Display target language layer symbols
     -debug-tags     - Display information about the tags found in the interface
     -debug-template - Display information for debugging templates
     -debug-top &lt;n&gt;  - Display entire parse tree at stages 1-4, &lt;n&gt; is a csv list of stages
     -debug-typedef  - Display information about the types and typedefs in the interface
     -debug-typemap  - Display typemap debugging information
     -debug-tmsearch - Display typemap search debugging information
     -debug-tmused   - Display typemaps used debugging information
     -directors      - Turn on director mode for all the classes, mainly for testing
     -dirprot        - Turn on wrapping of protected members for director classes (default)
     -D&lt;symbol&gt;      - Define a symbol &lt;symbol&gt; (for conditional compilation)
     -E              - Preprocess only, does not generate wrapper code
     -external-runtime [file] - Export the SWIG runtime stack
     -fakeversion &lt;v&gt;- Make SWIG fake the program version number to &lt;v&gt;
     -fcompact       - Compile in compact mode
     -features &lt;list&gt;- Set global features, where &lt;list&gt; is a comma separated list of
                       features, eg -features directors,autodoc=1
                       If no explicit value is given to the feature, a default of 1 is used
     -fastdispatch   - Enable fast dispatch mode to produce faster overload dispatcher code
     -Fmicrosoft     - Display error/warning messages in Microsoft format
     -Fstandard      - Display error/warning messages in commonly used format
     -fvirtual       - Compile in virtual elimination mode
     -help           - Display help
     -I-             - Don't search the current directory
     -I&lt;dir&gt;         - Look for SWIG files in directory &lt;dir&gt;
     -ignoremissing  - Ignore missing include files
     -importall      - Follow all #include statements as imports
     -includeall     - Follow all #include statements
     -l&lt;ifile&gt;       - Include SWIG library file &lt;ifile&gt;
     -macroerrors    - Report errors inside macros
     -makedefault    - Create default constructors/destructors (the default)
     -M              - List all dependencies
     -MD             - Is equivalent to `-M -MF &lt;file&gt;', except `-E' is not implied
     -MF &lt;file&gt;      - Generate dependencies into &lt;file&gt; and continue generating wrappers
     -MM             - List dependencies, but omit files in SWIG library
     -MMD            - Like `-MD', but omit files in SWIG library
     -module &lt;name&gt;  - Set module name to &lt;name&gt;
     -MP             - Generate phony targets for all dependencies
     -MT &lt;target&gt;    - Set the target of the rule emitted by dependency generation
     -nocontract     - Turn off contract checking
     -nocpperraswarn - Do not treat the preprocessor #error statement as #warning
     -nodefault      - Do not generate default constructors nor default destructors
     -nodefaultctor  - Do not generate implicit default constructors
     -nodefaultdtor  - Do not generate implicit default destructors
     -nodirprot      - Do not wrap director protected members
     -noexcept       - Do not wrap exception specifiers
     -nofastdispatch - Disable fast dispatch mode (default)
     -nopreprocess   - Skip the preprocessor step
     -notemplatereduce - Disable reduction of the typedefs in templates
     -O              - Enable the optimization options:
                        -fastdispatch -fvirtual
     -o &lt;outfile&gt;    - Set name of C/C++ output file to &lt;outfile&gt;
     -oh &lt;headfile&gt;  - Set name of C++ output header file for directors to &lt;headfile&gt;
     -outcurrentdir  - Set default output dir to current dir instead of input file's path
     -outdir &lt;dir&gt;   - Set language specific files output directory to &lt;dir&gt;
     -pcreversion    - Display PCRE version information
     -small          - Compile in virtual elimination and compact mode
     -swiglib        - Report location of SWIG library and exit
     -templatereduce - Reduce all the typedefs in templates
     -v              - Run in verbose mode
     -version        - Display SWIG version number
     -Wall           - Remove all warning suppression, also implies -Wextra
     -Wallkw         - Enable keyword warnings for all the supported languages
     -Werror         - Treat warnings as errors
     -Wextra         - Adds the following additional warnings: 202,309,403,405,512,321,322
     -w&lt;list&gt;        - Suppress/add warning messages, eg -w401,+321 - see Warnings.html
     -xmlout &lt;file&gt;  - Write XML version of the parse tree to &lt;file&gt; after normal processing
</pre>
</div>
<p> Arguments may also be passed in a command-line options file (also
 known as a response file) which is useful if they exceed the system
 command line length limit. To do this, put the arguments in a file,
 then provide the file name prefixed with <tt>@</tt> like so:</p>
<div class="shell">
<pre>
swig @<em>file</em>
</pre>
</div>
<p> The options read from the file are inserted in place of the file
 option. If the file does not exist, or cannot be read, then the option
 will be treated literally and not removed.</p>
<p> Options in the file are separated by whitespace. A whitespace
 character may be included in an option by surrounding the entire option
 in either single or double quotes. Any character (including a
 backslash) may be included by prefixing the character to be included
 with a backslash. The file may itself contain additional <tt>@file</tt>
 options; any such options will be processed recursively.</p>
<h3><a name="SWIG_nn3">5.1.1 Input format</a></h3>
<p> As input, SWIG expects a file containing ISO C/C++ declarations and
 special SWIG directives. More often than not, this is a special SWIG
 interface file which is usually denoted with a special <tt>.i</tt> or <tt>
.swg</tt> suffix. In certain cases, SWIG can be used directly on raw
 header files or source files. However, this is not the most typical
 case and there are several reasons why you might not want to do this
 (described later).</p>
<p> The most common format of a SWIG interface is as follows:</p>
<div class="code">
<pre>
%module mymodule 
%{
#include &quot;myheader.h&quot;
%}
// Now list ISO C/C++ declarations
int foo;
int bar(int x);
...
</pre>
</div>
<p> The module name is supplied using the special <tt>%module</tt>
 directive. Modules are described further in the <a href="#Modules_introduction">
Modules Introduction</a> section.</p>
<p> Everything in the <tt>%{ ... %}</tt> block is simply copied verbatim
 to the resulting wrapper file created by SWIG. This section is almost
 always used to include header files and other declarations that are
 required to make the generated wrapper code compile. It is important to
 emphasize that just because you include a declaration in a SWIG input
 file, that declaration does<em> not</em> automatically appear in the
 generated wrapper code---therefore you need to make sure you include
 the proper header files in the <tt>%{ ... %}</tt> section. It should be
 noted that the text enclosed in <tt>%{ ... %}</tt> is not parsed or
 interpreted by SWIG. The <tt>%{...%}</tt> syntax and semantics in SWIG
 is analogous to that of the declarations section used in input files to
 parser generation tools such as yacc or bison.</p>
<h3><a name="SWIG_output">5.1.2 SWIG Output</a></h3>
<p> The output of SWIG is a C/C++ file that contains all of the wrapper
 code needed to build an extension module. SWIG may generate some
 additional files depending on the target language. By default, an input
 file with the name <tt>file.i</tt> is transformed into a file <tt>
file_wrap.c</tt> or <tt>file_wrap.cxx</tt> (depending on whether or not
 the <tt>-c++</tt> option has been used). The name of the output C/C++
 file can be changed using the <tt>-o</tt> option. In certain cases,
 file suffixes are used by the compiler to determine the source language
 (C, C++, etc.). Therefore, you have to use the <tt>-o</tt> option to
 change the suffix of the SWIG-generated wrapper file if you want
 something different than the default. For example:</p>
<div class="shell">
<pre>
$ swig -c++ -python -o example_wrap.cpp example.i
</pre>
</div>
<p> The C/C++ output file created by SWIG often contains everything that
 is needed to construct an extension module for the target scripting
 language. SWIG is not a stub compiler nor is it usually necessary to
 edit the output file (and if you look at the output, you probably won't
 want to). To build the final extension module, the SWIG output file is
 compiled and linked with the rest of your C/C++ program to create a
 shared library.</p>
<p> For many target languages SWIG will also generate proxy class files
 in the target language. The default output directory for these language
 specific files is the same directory as the generated C/C++ file. This
 can be modified using the <tt>-outdir</tt> option. For example:</p>
<div class="shell">
<pre>
$ swig -c++ -python -outdir pyfiles -o cppfiles/example_wrap.cpp example.i
</pre>
</div>
<p> If the directories <tt>cppfiles</tt> and <tt>pyfiles</tt> exist, the
 following will be generated:</p>
<div class="shell">
<pre>
cppfiles/example_wrap.cpp
pyfiles/example.py
</pre>
</div>
<p> If the <tt>-outcurrentdir</tt> option is used (without <tt>-o</tt>)
 then SWIG behaves like a typical C/C++ compiler and the default output
 directory is then the current directory. Without this option the
 default output directory is the path to the input file. If <tt>-o</tt>
 and <tt>-outcurrentdir</tt> are used together, <tt>-outcurrentdir</tt>
 is effectively ignored as the output directory for the language files
 is the same directory as the generated C/C++ file if not overridden
 with <tt>-outdir</tt>.</p>
<h3><a name="SWIG_nn5">5.1.3 Comments</a></h3>
<p> C and C++ style comments may appear anywhere in interface files. In
 previous versions of SWIG, comments were used to generate documentation
 files. However, this feature is currently under repair and will
 reappear in a later SWIG release.</p>
<h3><a name="SWIG_nn6">5.1.4 C Preprocessor</a></h3>
<p> Like C, SWIG preprocesses all input files through an enhanced
 version of the C preprocessor. All standard preprocessor features are
 supported including file inclusion, conditional compilation and macros.
 However, <tt>#include</tt> statements are ignored unless the <tt>
-includeall</tt> command line option has been supplied. The reason for
 disabling includes is that SWIG is sometimes used to process raw C
 header files. In this case, you usually only want the extension module
 to include functions in the supplied header file rather than everything
 that might be included by that header file (i.e., system headers, C
 library functions, etc.).</p>
<p> It should also be noted that the SWIG preprocessor skips all text
 enclosed inside a <tt>%{...%}</tt> block. In addition, the preprocessor
 includes a number of macro handling enhancements that make it more
 powerful than the normal C preprocessor. These extensions are described
 in the &quot;<a href="#Preprocessor">Preprocessor</a>&quot; chapter.</p>
<h3><a name="SWIG_nn7">5.1.5 SWIG Directives</a></h3>
<p> Most of SWIG's operation is controlled by special directives that
 are always preceded by a &quot;<tt>%</tt>&quot; to distinguish them from normal C
 declarations. These directives are used to give SWIG hints or to alter
 SWIG's parsing behavior in some manner.</p>
<p> Since SWIG directives are not legal C syntax, it is generally not
 possible to include them in header files. However, SWIG directives can
 be included in C header files using conditional compilation like this:</p>
<div class="code">
<pre>
/* header.h  --- Some header file */

/* SWIG directives -- only seen if SWIG is running */ 
#ifdef SWIG
%module foo
#endif
</pre>
</div>
<p> <tt>SWIG</tt> is a special preprocessing symbol defined by SWIG when
 it is parsing an input file.</p>
<h3><a name="SWIG_nn8">5.1.6 Parser Limitations</a></h3>
<p> Although SWIG can parse most C/C++ declarations, it does not provide
 a complete C/C++ parser implementation. Most of these limitations
 pertain to very complicated type declarations and certain advanced C++
 features. Specifically, the following features are not currently
 supported:</p>
<ul>
<li>
<p> Non-conventional type declarations. For example, SWIG does not
 support declarations such as the following (even though this is legal
 C):</p>
<div class="code">
<pre>
/* Non-conventional placement of storage specifier (extern) */
const int extern Number;

/* Extra declarator grouping */
Matrix (foo);    // A global variable

/* Extra declarator grouping in parameters */
void bar(Spam (Grok)(Doh));

</pre>
</div>
<p> In practice, few (if any) C programmers actually write code like
 this since this style is never featured in programming books. However,
 if you're feeling particularly obfuscated, you can certainly break SWIG
 (although why would you want to?).</p>
</li>
<li>
<p> Running SWIG on C++ source files (the code in a .C, .cpp or .cxx
 file) is not recommended. The usual approach is to feed SWIG header
 files for parsing C++ definitions and declarations. The main reason is
 if SWIG parses a scoped definition or declaration (as is normal for C++
 source files), it is ignored, unless a declaration for the symbol was
 parsed earlier. For example</p>
<div class="code">
<pre>
/* bar not wrapped unless foo has been defined and 
   the declaration of bar within foo has already been parsed */
int foo::bar(int) {
  ... whatever ...
}
</pre>
</div></li>
<li>
<p> Certain advanced features of C++ such as nested classes are not yet
 fully supported. Please see the C++ <a href="#SWIGPlus_nested_classes">
Nested classes</a> section for more information.</p>
</li>
</ul>
<p> In the event of a parsing error, conditional compilation can be used
 to skip offending code. For example:</p>
<div class="code">
<pre>
#ifndef SWIG
... some bad declarations ...
#endif
</pre>
</div>
<p> Alternatively, you can just delete the offending code from the
 interface file.</p>
<p> One of the reasons why SWIG does not provide a full C++ parser
 implementation is that it has been designed to work with incomplete
 specifications and to be very permissive in its handling of C/C++
 datatypes (e.g., SWIG can generate interfaces even when there are
 missing class declarations or opaque datatypes). Unfortunately, this
 approach makes it extremely difficult to implement certain parts of a
 C/C++ parser as most compilers use type information to assist in the
 parsing of more complex declarations (for the truly curious, the
 primary complication in the implementation is that the SWIG parser does
 not utilize a separate<em> typedef-name</em> terminal symbol as
 described on p. 234 of K&amp;R).</p>
<h2><a name="SWIG_nn9">5.2 Wrapping Simple C Declarations</a></h2>
<p> SWIG wraps simple C declarations by creating an interface that
 closely matches the way in which the declarations would be used in a C
 program. For example, consider the following interface file:</p>
<div class="code">
<pre>
%module example

%inline %{
extern double sin(double x);
extern int strcmp(const char *, const char *);
extern int Foo;
%}
#define STATUS 50
#define VERSION &quot;1.1&quot;
</pre>
</div>
<p> In this file, there are two functions <tt>sin()</tt> and <tt>
strcmp()</tt>, a global variable <tt>Foo</tt>, and two constants <tt>
STATUS</tt> and <tt>VERSION</tt>. When SWIG creates an extension module,
 these declarations are accessible as scripting language functions,
 variables, and constants respectively. For example, in Tcl:</p>
<div class="targetlang">
<pre>
% sin 3
5.2335956
% strcmp Dave Mike
-1
% puts $Foo
42
% puts $STATUS
50
% puts $VERSION
1.1
</pre>
</div>
<p> Or in Python:</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; example.sin(3)
5.2335956
&gt;&gt;&gt; example.strcmp('Dave', 'Mike')
-1
&gt;&gt;&gt; print example.cvar.Foo
42
&gt;&gt;&gt; print example.STATUS
50
&gt;&gt;&gt; print example.VERSION
1.1
</pre>
</div>
<p> Whenever possible, SWIG creates an interface that closely matches
 the underlying C/C++ code. However, due to subtle differences between
 languages, run-time environments, and semantics, it is not always
 possible to do so. The next few sections describe various aspects of
 this mapping.</p>
<h3><a name="SWIG_nn10">5.2.1 Basic Type Handling</a></h3>
<p> In order to build an interface, SWIG has to convert C/C++ datatypes
 to equivalent types in the target language. Generally, scripting
 languages provide a more limited set of primitive types than C.
 Therefore, this conversion process involves a certain amount of type
 coercion.</p>
<p> Most scripting languages provide a single integer type that is
 implemented using the <tt>int</tt> or <tt>long</tt> datatype in C. The
 following list shows all of the C datatypes that SWIG will convert to
 and from integers in the target language:</p>
<div class="code">
<pre>
int
short
long
unsigned
signed
unsigned short
unsigned long
unsigned char
signed char
bool
</pre>
</div>
<p> When an integral value is converted from C, a cast is used to
 convert it to the representation in the target language. Thus, a 16 bit
 short in C may be promoted to a 32 bit integer. When integers are
 converted in the other direction, the value is cast back into the
 original C type. If the value is too large to fit, it is silently
 truncated.
<!-- Dave: Maybe we should fix this -->
</p>
<p> <tt>unsigned char</tt> and <tt>signed char</tt> are special cases
 that are handled as small 8-bit integers. Normally, the <tt>char</tt>
 datatype is mapped as a one-character ASCII string.</p>
<p> The <tt>bool</tt> datatype is cast to and from an integer value of 0
 and 1 unless the target language provides a special boolean type.</p>
<p> Some care is required when working with large integer values. Most
 scripting languages use 32-bit integers so mapping a 64-bit long
 integer may lead to truncation errors. Similar problems may arise with
 32 bit unsigned integers (which may appear as large negative numbers).
 As a rule of thumb, the <tt>int</tt> datatype and all variations of <tt>
char</tt> and <tt>short</tt> datatypes are safe to use. For <tt>unsigned
 int</tt> and <tt>long</tt> datatypes, you will need to carefully check
 the correct operation of your program after it has been wrapped with
 SWIG.</p>
<p> Although the SWIG parser supports the <tt>long long</tt> datatype,
 not all language modules support it. This is because <tt>long long</tt>
 usually exceeds the integer precision available in the target language.
 In certain modules such as Tcl and Perl5, <tt>long long</tt> integers
 are encoded as strings. This allows the full range of these numbers to
 be represented. However, it does not allow <tt>long long</tt> values to
 be used in arithmetic expressions. It should also be noted that
 although <tt>long long</tt> is part of the ISO C99 standard, it is not
 universally supported by all C compilers. Make sure you are using a
 compiler that supports <tt>long long</tt> before trying to use this
 type with SWIG.</p>
<p> SWIG recognizes the following floating point types :</p>
<div class="code">
<pre>
float
double
</pre>
</div>
<p> Floating point numbers are mapped to and from the natural
 representation of floats in the target language. This is almost always
 a C <tt>double</tt>. The rarely used datatype of <tt>long double</tt>
 is not supported by SWIG.</p>
<p> The <tt>char</tt> datatype is mapped into a NULL terminated ASCII
 string with a single character. When used in a scripting language it
 shows up as a tiny string containing the character value. When
 converting the value back into C, SWIG takes a character string from
 the scripting language and strips off the first character as the char
 value. Thus if the value &quot;foo&quot; is assigned to a <tt>char</tt> datatype,
 it gets the value `f'.</p>
<p> The <tt>char *</tt> datatype is handled as a NULL-terminated ASCII
 string. SWIG maps this into a 8-bit character string in the target
 scripting language. SWIG converts character strings in the target
 language to NULL terminated strings before passing them into C/C++. The
 default handling of these strings does not allow them to have embedded
 NULL bytes. Therefore, the <tt>char *</tt> datatype is not generally
 suitable for passing binary data. However, it is possible to change
 this behavior by defining a SWIG typemap. See the chapter on <a href="#Typemaps">
Typemaps</a> for details about this.</p>
<p> At this time, SWIG provides limited support for Unicode and
 wide-character strings (the C <tt>wchar_t</tt> type). Some languages
 provide typemaps for wchar_t, but bear in mind these might not be
 portable across different operating systems. This is a delicate topic
 that is poorly understood by many programmers and not implemented in a
 consistent manner across languages. For those scripting languages that
 provide Unicode support, Unicode strings are often available in an
 8-bit representation such as UTF-8 that can be mapped to the <tt>char *</tt>
 type (in which case the SWIG interface will probably work). If the
 program you are wrapping uses Unicode, there is no guarantee that
 Unicode characters in the target language will use the same internal
 representation (e.g., UCS-2 vs. UCS-4). You may need to write some
 special conversion functions.</p>
<h3><a name="SWIG_nn11">5.2.2 Global Variables</a></h3>
<p> Whenever possible, SWIG maps C/C++ global variables into scripting
 language variables. For example,</p>
<div class="code">
<pre>
%module example
double foo;

</pre>
</div>
<p> results in a scripting language variable like this:</p>
<div class="code">
<pre>
# Tcl
set foo [3.5]                   ;# Set foo to 3.5
puts $foo                       ;# Print the value of foo

# Python
cvar.foo = 3.5                  # Set foo to 3.5
print cvar.foo                  # Print value of foo

# Perl
$foo = 3.5;                     # Set foo to 3.5
print $foo, &quot;\n&quot;;               # Print value of foo

# Ruby
Module.foo = 3.5               # Set foo to 3.5
print Module.foo, &quot;\n&quot;         # Print value of foo
</pre>
</div>
<p> Whenever the scripting language variable is used, the underlying C
 global variable is accessed. Although SWIG makes every attempt to make
 global variables work like scripting language variables, it is not
 always possible to do so. For instance, in Python, all global variables
 must be accessed through a special variable object known as <tt>cvar</tt>
 (shown above). In Ruby, variables are accessed as attributes of the
 module. Other languages may convert variables to a pair of accessor
 functions. For example, the Java module generates a pair of functions <tt>
double get_foo()</tt> and <tt>set_foo(double val)</tt> that are used to
 manipulate the value.</p>
<p> Finally, if a global variable has been declared as <tt>const</tt>,
 it only supports read-only access. Note: this behavior is new to
 SWIG-1.3. Earlier versions of SWIG incorrectly handled <tt>const</tt>
 and created constants instead.</p>
<h3><a name="SWIG_nn12">5.2.3 Constants</a></h3>
<p> Constants can be created using <tt>#define</tt>, enumerations, or a
 special <tt>%constant</tt> directive. The following interface file
 shows a few valid constant declarations :</p>
<div class="code">
<pre>
#define I_CONST       5               // An integer constant
#define PI            3.14159         // A Floating point constant
#define S_CONST       &quot;hello world&quot;   // A string constant
#define NEWLINE       '\n'            // Character constant

enum boolean {NO=0, YES=1};
enum months {JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG,
             SEP, OCT, NOV, DEC};
%constant double BLAH = 42.37;
#define PI_4 PI/4
#define FLAGS 0x04 | 0x08 | 0x40

</pre>
</div>
<p> In <tt>#define</tt> declarations, the type of a constant is inferred
 by syntax. For example, a number with a decimal point is assumed to be
 floating point. In addition, SWIG must be able to fully resolve all of
 the symbols used in a <tt>#define</tt> in order for a constant to
 actually be created. This restriction is necessary because <tt>#define</tt>
 is also used to define preprocessor macros that are definitely not
 meant to be part of the scripting language interface. For example:</p>
<div class="code">
<pre>
#define EXTERN extern

EXTERN void foo();
</pre>
</div>
<p> In this case, you probably don't want to create a constant called <tt>
EXTERN</tt> (what would the value be?). In general, SWIG will not create
 constants for macros unless the value can be completely determined by
 the preprocessor. For instance, in the above example, the declaration</p>
<div class="code">
<pre>
#define PI_4  PI/4
</pre>
</div>
<p> defines a constant because <tt>PI</tt> was already defined as a
 constant and the value is known. However, for the same conservative
 reasons even a constant with a simple cast will be ignored, such as</p>
<div class="code">
<pre>
#define F_CONST (double) 5            // A floating point constant with cast
</pre>
</div>
<p> This logic can lead to false attempts at converting <tt>#define</tt>
 into <tt>%constant</tt> though. For example the following case does not
 have any undefined symbols within the macro:</p>
<div class="code">
<pre>
// For indicating pure virtual functions such as: virtual void f() PURE;
#define PURE = 0
</pre>
</div>
<p> A warning is issued:</p>
<div class="shell">
<pre>
pure.h:1: Warning 305: Bad constant value (ignored).
</pre>
</div>
<p> In such cases simply ignore the warning or suppress it using the
 normal warning suppression techniques.</p>
<p> The use of constant expressions is allowed, but SWIG does not
 evaluate them. Rather, it passes them through to the output file and
 lets the C compiler perform the final evaluation (SWIG does perform a
 limited form of type-checking however).</p>
<p> For enumerations, it is critical that the original enum definition
 be included somewhere in the interface file (either in a header file or
 in the <tt>%{ %}</tt> block). SWIG only translates the enumeration into
 code needed to add the constants to a scripting language. It needs the
 original enumeration declaration in order to get the correct enum
 values as assigned by the C compiler.</p>
<p> The <tt>%constant</tt> directive is used to more precisely create
 constants corresponding to different C datatypes. Although it is not
 usually needed for simple values, it is more useful when working with
 pointers and other more complex datatypes. Typically, <tt>%constant</tt>
 is only used when you want to add constants to the scripting language
 interface that are not defined in the original header file.</p>
<h3><a name="SWIG_nn13">5.2.4 A brief word about const</a></h3>
<p> A common confusion with C programming is the semantic meaning of the
 <tt>const</tt> qualifier in declarations--especially when it is mixed
 with pointers and other type modifiers. In fact, previous versions of
 SWIG handled <tt>const</tt> incorrectly--a situation that SWIG-1.3.7
 and newer releases have fixed.</p>
<p> Starting with SWIG-1.3, all variable declarations, regardless of any
 use of <tt>const</tt>, are wrapped as global variables. If a
 declaration happens to be declared as <tt>const</tt>, it is wrapped as
 a read-only variable. To tell if a variable is <tt>const</tt> or not,
 you need to look at the right-most occurrence of the <tt>const</tt>
 qualifier (that appears before the variable name). If the right-most <tt>
const</tt> occurs after all other type modifiers (such as pointers),
 then the variable is <tt>const</tt>. Otherwise, it is not.</p>
<p> Here are some examples of <tt>const</tt> declarations.</p>
<div class="code">
<pre>
const char a;           // A constant character
char const b;           // A constant character (the same)
char *const c;          // A constant pointer to a character
const char *const d;    // A constant pointer to a constant character
</pre>
</div>
<p> Here is an example of a declaration that is not <tt>const</tt>:</p>
<div class="code">
<pre>
const char *e;          // A pointer to a constant character.  The pointer
                        // may be modified.
</pre>
</div>
<p> In this case, the pointer <tt>e</tt> can change---it's only the
 value being pointed to that is read-only.</p>
<p> Please note that for const parameters or return types used in a
 function, SWIG pretty much ignores the fact that these are const, see
 the section on <a href="#SWIGPlus_const">const-correctness</a> for more
 information.</p>
<p><b> Compatibility Note:</b> One reason for changing SWIG to handle <tt>
const</tt> declarations as read-only variables is that there are many
 situations where the value of a <tt>const</tt> variable might change.
 For example, a library might export a symbol as <tt>const</tt> in its
 public API to discourage modification, but still allow the value to
 change through some other kind of internal mechanism. Furthermore,
 programmers often overlook the fact that with a constant declaration
 like <tt>char *const</tt>, the underlying data being pointed to can be
 modified--it's only the pointer itself that is constant. In an embedded
 system, a <tt>const</tt> declaration might refer to a read-only memory
 address such as the location of a memory-mapped I/O device port (where
 the value changes, but writing to the port is not supported by the
 hardware). Rather than trying to build a bunch of special cases into
 the <tt>const</tt> qualifier, the new interpretation of <tt>const</tt>
 as &quot;read-only&quot; is simple and exactly matches the actual semantics of <tt>
const</tt> in C/C++. If you really want to create a constant as in older
 versions of SWIG, use the <tt>%constant</tt> directive instead. For
 example:</p>
<div class="code">
<pre>
%constant double PI = 3.14159;
</pre>
</div>
<p> or</p>
<div class="code">
<pre>
#ifdef SWIG
#define const %constant
#endif
const double foo = 3.4;
const double bar = 23.4;
const int    spam = 42;
#ifdef SWIG
#undef const
#endif
...

</pre>
</div>
<h3><a name="SWIG_nn14">5.2.5 A cautionary tale of char *</a></h3>
<p> Before going any further, there is one bit of caution involving <tt>
char *</tt> that must now be mentioned. When strings are passed from a
 scripting language to a C <tt>char *</tt>, the pointer usually points
 to string data stored inside the interpreter. It is almost always a
 really bad idea to modify this data. Furthermore, some languages may
 explicitly disallow it. For instance, in Python, strings are supposed
 to be immutable. If you violate this, you will probably receive a vast
 amount of wrath when you unleash your module on the world.</p>
<p> The primary source of problems are functions that might modify
 string data in place. A classic example would be a function like this:</p>
<div class="code">
<pre>
char *strcat(char *s, const char *t)
</pre>
</div>
<p> Although SWIG will certainly generate a wrapper for this, its
 behavior will be undefined. In fact, it will probably cause your
 application to crash with a segmentation fault or other memory related
 problem. This is because <tt>s</tt> refers to some internal data in the
 target language---data that you shouldn't be touching.</p>
<p> The bottom line: don't rely on <tt>char *</tt> for anything other
 than read-only input values. However, it must be noted that you could
 change the behavior of SWIG using <a href="#Typemaps">typemaps</a>.</p>
<h2><a name="SWIG_nn15">5.3 Pointers and complex objects</a></h2>
<p> Most C programs manipulate arrays, structures, and other types of
 objects. This section discusses the handling of these datatypes.</p>
<h3><a name="SWIG_nn16">5.3.1 Simple pointers</a></h3>
<p> Pointers to primitive C datatypes such as</p>
<div class="code">
<pre>
int *
double ***
char **
</pre>
</div>
<p> are fully supported by SWIG. Rather than trying to convert the data
 being pointed to into a scripting representation, SWIG simply encodes
 the pointer itself into a representation that contains the actual value
 of the pointer and a type-tag. Thus, the SWIG representation of the
 above pointers (in Tcl), might look like this:</p>
<div class="targetlang">
<pre>
_10081012_p_int
_1008e124_ppp_double
_f8ac_pp_char
</pre>
</div>
<p> A NULL pointer is represented by the string &quot;NULL&quot; or the value 0
 encoded with type information.</p>
<p> All pointers are treated as opaque objects by SWIG. Thus, a pointer
 may be returned by a function and passed around to other C functions as
 needed. For all practical purposes, the scripting language interface
 works in exactly the same way as you would use the pointer in a C
 program. The only difference is that there is no mechanism for
 dereferencing the pointer since this would require the target language
 to understand the memory layout of the underlying object.</p>
<p> The scripting language representation of a pointer value should
 never be manipulated directly. Even though the values shown look like
 hexadecimal addresses, the numbers used may differ from the actual
 machine address (e.g., on little-endian machines, the digits may appear
 in reverse order). Furthermore, SWIG does not normally map pointers
 into high-level objects such as associative arrays or lists (for
 example, converting an <tt>int *</tt> into an list of integers). There
 are several reasons why SWIG does not do this:</p>
<ul>
<li>There is not enough information in a C declaration to properly map
 pointers into higher level constructs. For example, an <tt>int *</tt>
 may indeed be an array of integers, but if it contains ten million
 elements, converting it into a list object is probably a bad idea.</li>
<li>The underlying semantics associated with a pointer is not known by
 SWIG. For instance, an <tt>int *</tt> might not be an array at
 all--perhaps it is an output value!</li>
<li>By handling all pointers in a consistent manner, the implementation
 of SWIG is greatly simplified and less prone to error.</li>
</ul>
<h3><a name="SWIG_nn17">5.3.2 Run time pointer type checking</a></h3>
<p> By allowing pointers to be manipulated from a scripting language,
 extension modules effectively bypass compile-time type checking in the
 C/C++ compiler. To prevent errors, a type signature is encoded into all
 pointer values and is used to perform run-time type checking. This
 type-checking process is an integral part of SWIG and can not be
 disabled or modified without using typemaps (described in later
 chapters).</p>
<p> Like C, <tt>void *</tt> matches any kind of pointer. Furthermore, <tt>
NULL</tt> pointers can be passed to any function that expects to receive
 a pointer. Although this has the potential to cause a crash, <tt>NULL</tt>
 pointers are also sometimes used as sentinel values or to denote a
 missing/empty value. Therefore, SWIG leaves NULL pointer checking up to
 the application.</p>
<h3><a name="SWIG_nn18">5.3.3 Derived types, structs, and classes</a></h3>
<p> For everything else (structs, classes, arrays, etc...) SWIG applies
 a very simple rule :</p>
<center><b> Everything else is a pointer</b></center>
<p> In other words, SWIG manipulates everything else by reference. This
 model makes sense because most C/C++ programs make heavy use of
 pointers and SWIG can use the type-checked pointer mechanism already
 present for handling pointers to basic datatypes.</p>
<p> Although this probably sounds complicated, it's really quite simple.
 Suppose you have an interface file like this :</p>
<div class="code">
<pre>
%module fileio
FILE *fopen(char *, char *);
int fclose(FILE *);
unsigned fread(void *ptr, unsigned size, unsigned nobj, FILE *);
unsigned fwrite(void *ptr, unsigned size, unsigned nobj, FILE *);
void *malloc(int nbytes);
void free(void *);

</pre>
</div>
<p> In this file, SWIG doesn't know what a <tt>FILE</tt> is, but since
 it's used as a pointer, so it doesn't really matter what it is. If you
 wrapped this module into Python, you can use the functions just like
 you expect :</p>
<div class="targetlang">
<pre>
# Copy a file 
def filecopy(source, target):
    f1 = fopen(source, &quot;r&quot;)
    f2 = fopen(target, &quot;w&quot;)
    buffer = malloc(8192)
    nbytes = fread(buffer, 8192, 1, f1)
    while (nbytes &gt; 0):
        fwrite(buffer, 8192, 1, f2)
            nbytes = fread(buffer, 8192, 1, f1)
    free(buffer)
</pre>
</div>
<p> In this case <tt>f1</tt>, <tt>f2</tt>, and <tt>buffer</tt> are all
 opaque objects containing C pointers. It doesn't matter what value they
 contain--our program works just fine without this knowledge.</p>
<h3><a name="SWIG_nn19">5.3.4 Undefined datatypes</a></h3>
<p> When SWIG encounters an undeclared datatype, it automatically
 assumes that it is a structure or class. For example, suppose the
 following function appeared in a SWIG input file:</p>
<div class="code">
<pre>
void matrix_multiply(Matrix *a, Matrix *b, Matrix *c);
</pre>
</div>
<p> SWIG has no idea what a &quot;<tt>Matrix</tt>&quot; is. However, it is
 obviously a pointer to something so SWIG generates a wrapper using its
 generic pointer handling code.</p>
<p> Unlike C or C++, SWIG does not actually care whether <tt>Matrix</tt>
 has been previously defined in the interface file or not. This allows
 SWIG to generate interfaces from only partial or limited information.
 In some cases, you may not care what a <tt>Matrix</tt> really is as
 long as you can pass an opaque reference to one around in the scripting
 language interface.</p>
<p> An important detail to mention is that SWIG will gladly generate
 wrappers for an interface when there are unspecified type names.
 However,<b> all unspecified types are internally handled as pointers to
 structures or classes!</b> For example, consider the following
 declaration:</p>
<div class="code">
<pre>
void foo(size_t num);
</pre>
</div>
<p> If <tt>size_t</tt> is undeclared, SWIG generates wrappers that
 expect to receive a type of <tt>size_t *</tt> (this mapping is
 described shortly). As a result, the scripting interface might behave
 strangely. For example:</p>
<div class="code">
<pre>
foo(40);
TypeError: expected a _p_size_t.
</pre>
</div>
<p> The only way to fix this problem is to make sure you properly
 declare type names using <tt>typedef</tt>.</p>

<!-- We might want to add an error reporting flag to swig -->
<h3><a name="SWIG_nn20">5.3.5 Typedef</a></h3>
<p> Like C, <tt>typedef</tt> can be used to define new type names in
 SWIG. For example:</p>
<div class="code">
<pre>
typedef unsigned int size_t;
</pre>
</div>
<p> <tt>typedef</tt> definitions appearing in a SWIG interface are not
 propagated to the generated wrapper code. Therefore, they either need
 to be defined in an included header file or placed in the declarations
 section like this:</p>
<div class="code">
<pre>
%{
/* Include in the generated wrapper file */
typedef unsigned int size_t;
%}
/* Tell SWIG about it */
typedef unsigned int size_t;
</pre>
</div>
<p> or</p>
<div class="code">
<pre>
%inline %{
typedef unsigned int size_t;
%}
</pre>
</div>
<p> In certain cases, you might be able to include other header files to
 collect type information. For example:</p>
<div class="code">
<pre>
%module example
%import &quot;sys/types.h&quot;
</pre>
</div>
<p> In this case, you might run SWIG as follows:</p>
<div class="shell">
<pre>
$ swig -I/usr/include -includeall example.i
</pre>
</div>
<p> It should be noted that your mileage will vary greatly here. System
 headers are notoriously complicated and may rely upon a variety of
 non-standard C coding extensions (e.g., such as special directives to
 GCC). Unless you exactly specify the right include directories and
 preprocessor symbols, this may not work correctly (you will have to
 experiment).</p>
<p> SWIG tracks <tt>typedef</tt> declarations and uses this information
 for run-time type checking. For instance, if you use the above <tt>
typedef</tt> and had the following function declaration:</p>
<div class="code">
<pre>
void foo(unsigned int *ptr);
</pre>
</div>
<p> The corresponding wrapper function will accept arguments of type <tt>
unsigned int *</tt> or <tt>size_t *</tt>.</p>
<h2><a name="SWIG_nn21">5.4 Other Practicalities</a></h2>
<p> So far, this chapter has presented almost everything you need to
 know to use SWIG for simple interfaces. However, some C programs use
 idioms that are somewhat more difficult to map to a scripting language
 interface. This section describes some of these issues.</p>
<h3><a name="SWIG_nn22">5.4.1 Passing structures by value</a></h3>
<p> Sometimes a C function takes structure parameters that are passed by
 value. For example, consider the following function:</p>
<div class="code">
<pre>
double dot_product(Vector a, Vector b);
</pre>
</div>
<p> To deal with this, SWIG transforms the function to use pointers by
 creating a wrapper equivalent to the following:</p>
<div class="code">
<pre>
double wrap_dot_product(Vector *a, Vector *b) {
  Vector x = *a;
  Vector y = *b;
  return dot_product(x, y);
}
</pre>
</div>
<p> In the target language, the <tt>dot_product()</tt> function now
 accepts pointers to Vectors instead of Vectors. For the most part, this
 transformation is transparent so you might not notice.</p>
<h3><a name="SWIG_nn23">5.4.2 Return by value</a></h3>
<p> C functions that return structures or classes datatypes by value are
 more difficult to handle. Consider the following function:</p>
<div class="code">
<pre>
Vector cross_product(Vector v1, Vector v2);
</pre>
</div>
<p> This function wants to return <tt>Vector</tt>, but SWIG only really
 supports pointers. As a result, SWIG creates a wrapper like this:</p>
<div class="code">
<pre>
Vector *wrap_cross_product(Vector *v1, Vector *v2) {
  Vector x = *v1;
  Vector y = *v2;
  Vector *result;
  result = (Vector *) malloc(sizeof(Vector));
  *(result) = cross(x, y);
  return result;
}
</pre>
</div>
<p> or if SWIG was run with the <tt>-c++</tt> option:</p>
<div class="code">
<pre>
Vector *wrap_cross(Vector *v1, Vector *v2) {
  Vector x = *v1;
  Vector y = *v2;
  Vector *result = new Vector(cross(x, y)); // Uses default copy constructor
  return result;
}
</pre>
</div>
<p> In both cases, SWIG allocates a new object and returns a reference
 to it. It is up to the user to delete the returned object when it is no
 longer in use. Clearly, this will leak memory if you are unaware of the
 implicit memory allocation and don't take steps to free the result.
 That said, it should be noted that some language modules can now
 automatically track newly created objects and reclaim memory for you.
 Consult the documentation for each language module for more details.</p>
<p> It should also be noted that the handling of pass/return by value in
 C++ has some special cases. For example, the above code fragments don't
 work correctly if <tt>Vector</tt> doesn't define a default constructor.
 The section on SWIG and C++ has more information about this case.</p>
<h3><a name="SWIG_nn24">5.4.3 Linking to structure variables</a></h3>
<p> When global variables or class members involving structures are
 encountered, SWIG handles them as pointers. For example, a global
 variable like this</p>
<div class="code">
<pre>
Vector unit_i;
</pre>
</div>
<p> gets mapped to an underlying pair of set/get functions like this :</p>
<div class="code">
<pre>
Vector *unit_i_get() {
  return &amp;unit_i;
}
void unit_i_set(Vector *value) {
  unit_i = *value;
}
</pre>
</div>
<p> Again some caution is in order. A global variable created in this
 manner will show up as a pointer in the target scripting language. It
 would be an extremely bad idea to free or destroy such a pointer. Also,
 C++ classes must supply a properly defined copy constructor in order
 for assignment to work correctly.</p>
<h3><a name="SWIG_nn25">5.4.4 Linking to char *</a></h3>
<p> When a global variable of type <tt>char *</tt> appears, SWIG uses <tt>
malloc()</tt> or <tt>new</tt> to allocate memory for the new value.
 Specifically, if you have a variable like this</p>
<div class="code">
<pre>
char *foo;
</pre>
</div>
<p> SWIG generates the following code:</p>
<div class="code">
<pre>
/* C mode */
void foo_set(char *value) {
  if (foo) free(foo);
  foo = (char *) malloc(strlen(value)+1);
  strcpy(foo, value);
}

/* C++ mode.  When -c++ option is used */
void foo_set(char *value) {
  if (foo) delete [] foo;
  foo = new char[strlen(value)+1];
  strcpy(foo, value);
}
</pre>
</div>
<p> If this is not the behavior that you want, consider making the
 variable read-only using the <tt>%immutable</tt> directive.
 Alternatively, you might write a short assist-function to set the value
 exactly like you want. For example:</p>
<div class="code">
<pre>
%inline %{
  void set_foo(char *value) {
    strncpy(foo, value, 50);
  }
%}
</pre>
</div>
<p> Note: If you write an assist function like this, you will have to
 call it as a function from the target scripting language (it does not
 work like a variable). For example, in Python you will have to write:</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; set_foo(&quot;Hello World&quot;)
</pre>
</div>
<p> A common mistake with <tt>char *</tt> variables is to link to a
 variable declared like this:</p>
<div class="code">
<pre>
char *VERSION = &quot;1.0&quot;;
</pre>
</div>
<p> In this case, the variable will be readable, but any attempt to
 change the value results in a segmentation or general protection fault.
 This is due to the fact that SWIG is trying to release the old value
 using <tt>free</tt> or <tt>delete</tt> when the string literal value
 currently assigned to the variable wasn't allocated using <tt>malloc()</tt>
 or <tt>new</tt>. To fix this behavior, you can either mark the variable
 as read-only, write a typemap (as described in Chapter 6), or write a
 special set function as shown. Another alternative is to declare the
 variable as an array:</p>
<div class="code">
<pre>
char VERSION[64] = &quot;1.0&quot;;
</pre>
</div>
<p> When variables of type <tt>const char *</tt> are declared, SWIG
 still generates functions for setting and getting the value. However,
 the default behavior does<em> not</em> release the previous contents
 (resulting in a possible memory leak). In fact, you may get a warning
 message such as this when wrapping such a variable:</p>
<div class="shell">
<pre>
example.i:20. Typemap warning. Setting const char * variable may leak memory
</pre>
</div>
<p> The reason for this behavior is that <tt>const char *</tt> variables
 are often used to point to string literals. For example:</p>
<div class="code">
<pre>
const char *foo = &quot;Hello World\n&quot;;
</pre>
</div>
<p> Therefore, it's a really bad idea to call <tt>free()</tt> on such a
 pointer. On the other hand, it<em> is</em> legal to change the pointer
 to point to some other value. When setting a variable of this type,
 SWIG allocates a new string (using malloc or new) and changes the
 pointer to point to the new value. However, repeated modifications of
 the value will result in a memory leak since the old value is not
 released.</p>
<h3><a name="SWIG_nn26">5.4.5 Arrays</a></h3>
<p> Arrays are fully supported by SWIG, but they are always handled as
 pointers instead of mapping them to a special array object or list in
 the target language. Thus, the following declarations :</p>
<div class="code">
<pre>
int foobar(int a[40]);
void grok(char *argv[]);
void transpose(double a[20][20]);
</pre>
</div>
<p> are processed as if they were really declared like this:</p>
<div class="code">
<pre>
int foobar(int *a);
void grok(char **argv);
void transpose(double (*a)[20]);
</pre>
</div>
<p> Like C, SWIG does not perform array bounds checking. It is up to the
 user to make sure the pointer points to a suitably allocated region of
 memory.</p>
<p> Multi-dimensional arrays are transformed into a pointer to an array
 of one less dimension. For example:</p>
<div class="code">
<pre>
int [10];         // Maps to int *
int [10][20];     // Maps to int (*)[20]
int [10][20][30]; // Maps to int (*)[20][30]
</pre>
</div>
<p> It is important to note that in the C type system, a
 multidimensional array <tt>a[][]</tt> is<b> NOT</b> equivalent to a
 single pointer <tt>*a</tt> or a double pointer such as <tt>**a</tt>.
 Instead, a pointer to an array is used (as shown above) where the
 actual value of the pointer is the starting memory location of the
 array. The reader is strongly advised to dust off their C book and
 re-read the section on arrays before using them with SWIG.</p>
<p> Array variables are supported, but are read-only by default. For
 example:</p>
<div class="code">
<pre>
int   a[100][200];
</pre>
</div>
<p> In this case, reading the variable 'a' returns a pointer of type <tt>
int (*)[200]</tt> that points to the first element of the array <tt>
&amp;a[0][0]</tt>. Trying to modify 'a' results in an error. This is because
 SWIG does not know how to copy data from the target language into the
 array. To work around this limitation, you may want to write a few
 simple assist functions like this:</p>
<div class="code">
<pre>
%inline %{
void a_set(int i, int j, int val) {
  a[i][j] = val;
}
int a_get(int i, int j) {
  return a[i][j];
}
%}
</pre>
</div>
<p> To dynamically create arrays of various sizes and shapes, it may be
 useful to write some helper functions in your interface. For example:</p>
<div class="code">
<pre>
// Some array helpers
%inline %{
  /* Create any sort of [size] array */
  int *int_array(int size) {
    return (int *) malloc(size*sizeof(int));
  }
  /* Create a two-dimension array [size][10] */
  int (*int_array_10(int size))[10] {
    return (int (*)[10]) malloc(size*10*sizeof(int));
  }
%}
</pre>
</div>
<p> Arrays of <tt>char</tt> are handled as a special case by SWIG. In
 this case, strings in the target language can be stored in the array.
 For example, if you have a declaration like this,</p>
<div class="code">
<pre>
char pathname[256];
</pre>
</div>
<p> SWIG generates functions for both getting and setting the value that
 are equivalent to the following code:</p>
<div class="code">
<pre>
char *pathname_get() {
  return pathname;
}
void pathname_set(char *value) {
  strncpy(pathname, value, 256);
}
</pre>
</div>
<p> In the target language, the value can be set like a normal variable.</p>
<h3><a name="SWIG_readonly_variables">5.4.6 Creating read-only variables</a>
</h3>
<p> A read-only variable can be created by using the <tt>%immutable</tt>
 directive as shown :</p>
<div class="code">
<pre>
// File : interface.i

int a;       // Can read/write
%immutable;
int b, c, d;   // Read only variables
%mutable;
double x, y;  // read/write
</pre>
</div>
<p> The <tt>%immutable</tt> directive enables read-only mode until it is
 explicitly disabled using the <tt>%mutable</tt> directive. As an
 alternative to turning read-only mode off and on like this, individual
 declarations can also be tagged as immutable. For example:</p>
<div class="code">
<pre>
%immutable x;                   // Make x read-only
...
double x;                       // Read-only (from earlier %immutable directive)
double y;                       // Read-write
...
</pre>
</div>
<p> The <tt>%mutable</tt> and <tt>%immutable</tt> directives are
 actually <a href="#Customization_features">%feature directives</a>
 defined like this:</p>
<div class="code">
<pre>
#define %immutable   %feature(&quot;immutable&quot;)
#define %mutable     %feature(&quot;immutable&quot;, &quot;&quot;)
</pre>
</div>
<p> If you wanted to make all wrapped variables read-only, barring one
 or two, it might be easier to take this approach:</p>
<div class="code">
<pre>
%immutable;                     // Make all variables read-only
%feature(&quot;immutable&quot;, &quot;0&quot;) x;   // except, make x read/write
...
double x;
double y;
double z;
...
</pre>
</div>
<p> Read-only variables are also created when declarations are declared
 as <tt>const</tt>. For example:</p>
<div class="code">
<pre>
const int foo;               /* Read only variable */
char * const version=&quot;1.0&quot;;  /* Read only variable */
</pre>
</div>
<p><b> Compatibility note:</b> Read-only access used to be controlled by
 a pair of directives <tt>%readonly</tt> and <tt>%readwrite</tt>.
 Although these directives still work, they generate a warning message.
 Simply change the directives to <tt>%immutable;</tt> and <tt>%mutable;</tt>
 to silence the warning. Don't forget the extra semicolon!</p>
<h3><a name="SWIG_rename_ignore">5.4.7 Renaming and ignoring
 declarations</a></h3>
<h4><a name="SWIG_nn29">5.4.7.1 Simple renaming of specific identifiers</a>
</h4>
<p> Normally, the name of a C declaration is used when that declaration
 is wrapped into the target language. However, this may generate a
 conflict with a keyword or already existing function in the scripting
 language. To resolve a name conflict, you can use the <tt>%rename</tt>
 directive as shown :</p>
<div class="code">
<pre>
// interface.i

%rename(my_print) print;
extern void print(const char *);

%rename(foo) a_really_long_and_annoying_name;
extern int a_really_long_and_annoying_name;

</pre>
</div>
<p> SWIG still calls the correct C function, but in this case the
 function <tt>print()</tt> will really be called &quot;<tt>my_print()</tt>&quot;
 in the target language.</p>
<p> The placement of the <tt>%rename</tt> directive is arbitrary as long
 as it appears before the declarations to be renamed. A common technique
 is to write code for wrapping a header file like this:</p>
<div class="code">
<pre>
// interface.i

%rename(my_print) print;
%rename(foo) a_really_long_and_annoying_name;

%include &quot;header.h&quot;
</pre>
</div>
<p> <tt>%rename</tt> applies a renaming operation to all future
 occurrences of a name. The renaming applies to functions, variables,
 class and structure names, member functions, and member data. For
 example, if you had two-dozen C++ classes, all with a member function
 named `print' (which is a keyword in Python), you could rename them all
 to `output' by specifying :</p>
<div class="code">
<pre>
%rename(output) print; // Rename all `print' functions to `output'
</pre>
</div>
<p> SWIG does not normally perform any checks to see if the functions it
 wraps are already defined in the target scripting language. However, if
 you are careful about namespaces and your use of modules, you can
 usually avoid these problems.</p>
<p> When wrapping C code, simple use of identifiers/symbols with <tt>
%rename</tt> usually suffices. When wrapping C++ code, simple use of
 simple identifiers/symbols with <tt>%rename</tt> might be too limiting
 when using C++ features such as function overloading, default
 arguments, namespaces, template specialization etc. If you are using
 the <tt>%rename</tt> directive and C++, make sure you read the <a href="#SWIGPlus">
SWIG and C++</a> chapter and in particular the section on <a href="#SWIGPlus_ambiguity_resolution_renaming">
Renaming and ambiguity resolution</a> for method overloading and default
 arguments.</p>
<p> Closely related to <tt>%rename</tt> is the <tt>%ignore</tt>
 directive. <tt>%ignore</tt> instructs SWIG to ignore declarations that
 match a given identifier. For example:</p>
<div class="code">
<pre>
%ignore print;         // Ignore all declarations named print
%ignore MYMACRO;       // Ignore a macro
...
#define MYMACRO 123
void print(const char *);
...
</pre>
</div>
<p> Any function, variable etc which matches <tt>%ignore</tt> will not
 be wrapped and therefore will not be available from the target
 language. A common usage of <tt>%ignore</tt> is to selectively remove
 certain declarations from a header file without having to add
 conditional compilation to the header. However, it should be stressed
 that this only works for simple declarations. If you need to remove a
 whole section of problematic code, the SWIG preprocessor should be used
 instead.</p>
<p><b> Compatibility note:</b> Older versions of SWIG provided a special
 <tt>%name</tt> directive for renaming declarations. For example:</p>
<div class="code">
<pre>
%name(output) extern void print(const char *);
</pre>
</div>
<p> This directive is still supported, but it is deprecated and should
 probably be avoided. The <tt>%rename</tt> directive is more powerful
 and better supports wrapping of raw header file information.</p>
<h4><a name="SWIG_advanced_renaming">5.4.7.2 Advanced renaming support</a>
</h4>
<p> While writing <tt>%rename</tt> for specific declarations is simple
 enough, sometimes the same renaming rule needs to be applied to many,
 maybe all, identifiers in the SWIG input. For example, it may be
 necessary to apply some transformation to all the names in the target
 language to better follow its naming conventions, like adding a
 specific prefix to all wrapped functions. Doing it individually for
 each function is impractical so SWIG supports applying a renaming rule
 to all declarations if the name of the identifier to be renamed is not
 specified:</p>
<div class="code">
<pre>
%rename(&quot;myprefix_%s&quot;) &quot;&quot;; // print&nbsp;-&gt;&nbsp;myprefix_print
</pre>
</div>
<p> This also shows that the argument of <tt>%rename</tt> doesn't have
 to be a literal string but can be a <tt>printf()</tt>-like format
 string. In the simplest form, <tt>&quot;%s&quot;</tt> is replaced with the name
 of the original declaration, as shown above. However this is not always
 enough and SWIG provides extensions to the usual format string syntax
 to allow applying a (SWIG-defined) function to the argument. For
 example, to wrap all C functions <tt>do_something_long()</tt> as more
 Java-like <tt>doSomethingLong()</tt> you can use the <tt>
&quot;lowercamelcase&quot;</tt> extended format specifier like this:</p>
<div class="code">
<pre>
%rename(&quot;%(lowercamelcase)s&quot;) &quot;&quot;; // foo_bar -&gt; fooBar; FooBar -&gt; fooBar
</pre>
</div>
<p> Some functions can be parametrized, for example the <tt>&quot;strip&quot;</tt>
 one strips the provided prefix from its argument. The prefix is
 specified as part of the format string, following a colon after the
 function name:</p>
<div class="code">
<pre>
%rename(&quot;%(strip:[wx])s&quot;) &quot;&quot;; // wxHello -&gt; Hello; FooBar -&gt; FooBar
</pre>
</div>
<p> Below is the table summarizing all currently defined functions with
 an example of applying each one. Note that some of them have two names,
 a shorter one and a more descriptive one, but the two functions are
 otherwise equivalent:</p>
<table border="1" cellpadding="5" summary="Format string functions">
<tr><th>Function</th><th>Returns</th><th colspan="2">Example (in/out)</th>
</tr>
<tr><td><tt>uppercase</tt> or <tt>upper</tt></td><td>Upper case version
 of the string.</td><td><tt>Print</tt></td><td><tt>PRINT</tt></td></tr>
<tr><td><tt>lowercase</tt> or <tt>lower</tt></td><td>Lower case version
 of the string.</td><td><tt>Print</tt></td><td><tt>print</tt></td></tr>
<tr><td><tt>title</tt></td><td>String with first letter capitalized and
 the rest in lower case.</td><td><tt>print</tt></td><td><tt>Print</tt></td>
</tr>
<tr><td><tt>firstuppercase</tt></td><td>String with the first letter
 capitalized and the rest unchanged.</td><td><tt>printIt</tt></td><td><tt>
PrintIt</tt></td></tr>
<tr><td><tt>firstlowercase</tt></td><td>String with the first letter in
 lower case and the rest unchanged.</td><td><tt>PrintIt</tt></td><td><tt>
printIt</tt></td></tr>
<tr><td><tt>camelcase</tt> or <tt>ctitle</tt></td><td>String with
 capitalized first letter and any letter following an underscore (which
 are removed in the process) and rest in lower case.</td><td><tt>
print_it</tt></td><td><tt>PrintIt</tt></td></tr>
<tr><td><tt>lowercamelcase</tt> or <tt>lctitle</tt></td><td>String with
 every letter following an underscore (which is removed in the process)
 capitalized and rest, including the first letter, in lower case.</td><td>
<tt>print_it</tt></td><td><tt>printIt</tt></td></tr>
<tr><td><tt>undercase</tt> or <tt>utitle</tt></td><td>Lower case string
 with underscores inserted before every upper case letter in the
 original string and any number not at the end of string. Logically,
 this is the reverse of <tt>camelcase</tt>.</td><td><tt>PrintIt</tt></td><td>
<tt>print_it</tt></td></tr>
<tr><td><tt>schemify</tt></td><td>String with all underscores replaced
 with dashes, resulting in more Lispers/Schemers-pleasing name.</td><td><tt>
print_it</tt></td><td><tt>print-it</tt></td></tr>
<tr><td><tt>strip:[prefix]</tt></td><td>String without the given prefix
 or the original string if it doesn't start with this prefix. Note that
 square brackets should be used literally, e.g. <tt>
%rename(&quot;strip:[wx]&quot;)</tt></td><td><tt>wxPrint</tt></td><td><tt>Print</tt>
</td></tr>
<tr><td><tt>rstrip:[suffix]</tt></td><td>String without the given suffix
 or the original string if it doesn't end with this suffix. Note that
 square brackets should be used literally, e.g. <tt>
%rename(&quot;rstrip:[Cls]&quot;)</tt></td><td><tt>PrintCls</tt></td><td><tt>Print</tt>
</td></tr>
<tr><td><span style="white-space: nowrap;"><tt>regex:/pattern/subst/</tt>
</span></td><td>String after (Perl-like) regex substitution operation.
 This function allows to apply arbitrary regular expressions to the
 identifier names. The<i> pattern</i> part is a regular expression in
 Perl syntax (as supported by the <a href="http://www.pcre.org/">Perl
 Compatible Regular Expressions (PCRE)</a>) library and the<i> subst</i>
 string can contain back-references of the form <tt>\N</tt> where <tt>N</tt>
 is a digit from 0 to 9, or one of the following escape sequences: <tt>
\l</tt>, <tt>\L</tt>, <tt>\u</tt>, <tt>\U</tt> or <tt>\E</tt>. The
 back-references are replaced with the contents of the corresponding
 capture group while the escape sequences perform the case conversion in
 the substitution string: <tt>\l</tt> and <tt>\L</tt> convert to the
 lower case, while <tt>\u</tt> and <tt>\U</tt> convert to the upper
 case. The difference between the elements of each pair is that <tt>\l</tt>
 and <tt>\u</tt> change the case of the next character only, while <tt>
\L</tt> and <tt>\U</tt> do it for all the remaining characters or until <tt>
\E</tt> is encountered. Finally please notice that backslashes need to
 be escaped in C strings, so in practice <tt>&quot;\\&quot;</tt> must be used in
 all these escape sequences. For example, to remove any alphabetic
 prefix before an underscore and capitalize the remaining part you could
 use the following directive: <tt>%rename(&quot;regex:/(\\w+)_(.*)/\\u\\2/&quot;)</tt>
</td><td><tt>prefix_print</tt></td><td><tt>Print</tt></td></tr>
<tr><td><tt>command:cmd</tt></td><td>Output of an external command <tt>
cmd</tt> with the string passed to it as input. Notice that this
 function is extremely slow compared to all the other ones as it
 involves spawning a separate process and using it for many declarations
 is not recommended. The<i> cmd</i> is not enclosed in square brackets
 but must be terminated with a triple <tt>'&lt;'</tt> sign, e.g. <tt>
%rename(&quot;command:tr&nbsp;-d&nbsp;aeiou &lt;&lt;&lt;&quot;)</tt> (nonsensical example removing
 all vowels)</td><td><tt>Print</tt></td><td><tt>Prnt</tt></td></tr>
</table>
<p> The most general function of all of the above ones (not counting <tt>
command</tt> which is even more powerful in principle but which should
 generally be avoided because of performance considerations) is the <tt>
regex</tt> one. Here are some more examples of its use:</p>
<div class="code">
<pre>
// Strip the wx prefix from all identifiers except those starting with wxEVT
%rename(&quot;%(regex:/wx(?!EVT)(.*)/\\1/)s&quot;) &quot;&quot;; // wxSomeWidget -&gt; SomeWidget
                                             // wxEVT_PAINT -&gt; wxEVT_PAINT

// Apply a rule for renaming the enum elements to avoid the common prefixes
// which are redundant in C#/Java
%rename(&quot;%(regex:/^([A-Z][a-z]+)+_(.*)/\\2/)s&quot;, %$isenumitem) &quot;&quot;; // Colour_Red -&gt; Red

// Remove all &quot;Set/Get&quot; prefixes.
%rename(&quot;%(regex:/^(Set|Get)(.*)/\\2/)s&quot;) &quot;&quot;; // SetValue -&gt; Value
                                              // GetValue -&gt; Value
</pre>
</div>
<p> As before, everything that was said above about <tt>%rename</tt>
 also applies to <tt>%ignore</tt>. In fact, the latter is just a special
 case of the former and ignoring an identifier is the same as renaming
 it to the special <tt>&quot;$ignore&quot;</tt> value. So the following snippets</p>
<div class="code">
<pre>
%ignore print;
</pre>
</div>
<p> and</p>
<div class="code">
<pre>
%rename(&quot;$ignore&quot;) print;
</pre>
</div>
<p> are exactly equivalent and <tt>%rename</tt> can be used to
 selectively ignore multiple declarations using the previously described
 matching possibilities.</p>
<h4><a name="SWIG_limiting_renaming">5.4.7.3 Limiting global renaming
 rules</a></h4>
<p> As explained in the previous sections, it is possible to either
 rename individual declarations or apply a rename rule to all of them at
 once. In practice, the latter is however rarely appropriate as there
 are always some exceptions to the general rules. To deal with them, the
 scope of an unnamed <tt>%rename</tt> can be limited using subsequent <tt>
match</tt> parameters. They can be applied to any of the attributes
 associated by SWIG with the declarations appearing in its input. For
 example:</p>
<div class="code">
<pre>
%rename(&quot;foo&quot;, match$name=&quot;bar&quot;) &quot;&quot;;
</pre>
</div>
<p> can be used to achieve the same effect as the simpler</p>
<div class="code">
<pre>
%rename(&quot;foo&quot;) bar;
</pre>
</div>
<p> and so is not very interesting on its own. However <tt>match</tt>
 can also be applied to the declaration type, for example <tt>
match=&quot;class&quot;</tt> restricts the match to class declarations only (in
 C++) and <tt>match=&quot;enumitem&quot;</tt> restricts it to the enum elements.
 SWIG also provides convenience macros for such match expressions, for
 example</p>
<div class="code">
<pre>
%rename(&quot;%(title)s&quot;, %$isenumitem) &quot;&quot;;
</pre>
</div>
<p> will capitalize the names of all the enum elements but not change
 the case of the other declarations. Similarly, <tt>%$isclass</tt>, <tt>
%$isfunction</tt>, <tt>%$isconstructor</tt>, <tt>%$isunion</tt>, <tt>
%$istemplate</tt>, and <tt>%$isvariable</tt> can be used. Many other
 checks are possible and this documentation is not exhaustive, see the
 &quot;%rename predicates&quot; section in <tt>swig.swg</tt> for the full list of
 supported match expressions.</p>
<p> In addition to literally matching some string with <tt>match</tt>
 you can also use <tt>regexmatch</tt> or <tt>notregexmatch</tt> to match
 a string against a regular expression. For example, to ignore all
 functions having &quot;Old&quot; as a suffix you could use</p>
<div class="code">
<pre>
%rename(&quot;$ignore&quot;, regexmatch$name=&quot;Old$&quot;) &quot;&quot;;
</pre>
</div>
<p> For simple cases like this, specifying the regular expression for
 the declaration name directly can be preferable and can also be done
 using <tt>regextarget</tt>:</p>
<div class="code">
<pre>
%rename(&quot;$ignore&quot;, regextarget=1) &quot;Old$&quot;;
</pre>
</div>
<p> Notice that the check is done only against the name of the
 declaration itself, if you need to match the full name of a C++
 declaration you must use <tt>fullname</tt> attribute:</p>
<div class="code">
<pre>
%rename(&quot;$ignore&quot;, regextarget=1, fullname=1) &quot;NameSpace::ClassName::.*Old$&quot;;
</pre>
</div>
<p> As for <tt>notregexmatch</tt>, it restricts the match only to the
 strings not matching the specified regular expression. So to rename all
 declarations to lower case except those consisting of capital letters
 only:</p>
<div class="code">
<pre>
%rename(&quot;$(lower)s&quot;, notregexmatch$name=&quot;^[A-Z]+$&quot;) &quot;&quot;;
</pre>
</div>
<p> Finally, variants of <tt>%rename</tt> and <tt>%ignore</tt>
 directives can be used to help wrap C++ overloaded functions and
 methods or C++ methods which use default arguments. This is described
 in the <a href="#SWIGPlus_ambiguity_resolution_renaming">Renaming and
 ambiguity resolution</a> section in the C++ chapter.</p>
<h4><a name="SWIG_chosen_unignore">5.4.7.4 Ignoring everything then
 wrapping a few selected symbols</a></h4>
<p> Using the techniques described above it is possible to ignore
 everything in a header and then selectively wrap a few chosen methods
 or classes. For example, consider a header, <tt>myheader.h</tt> which
 has many classes in it and just the one class called <tt>Star</tt> is
 wanted within this header, the following approach could be taken:</p>
<div class="code">
<pre>
%ignore &quot;&quot;; // Ignore everything

// Unignore chosen class 'Star'
%rename(&quot;%s&quot;) Star;

// As the ignore everything will include the constructor, destructor, methods etc
// in the class, these have to be explicitly unignored too:
%rename(&quot;%s&quot;) Star::Star;
%rename(&quot;%s&quot;) Star::~Star;
%rename(&quot;%s&quot;) Star::shine; // named method

%include &quot;myheader.h&quot;
</pre>
</div>
<p> Another approach which might be more suitable as it does not require
 naming all the methods in the chosen class is to begin by ignoring just
 the classes. This does not add an explicit ignore to any members of the
 class, so when the chosen class is unignored, all of its methods will
 be wrapped.</p>
<div class="code">
<pre>
%rename($ignore, %$isclass) &quot;&quot;; // Only ignore all classes
%rename(&quot;%s&quot;) Star; // Unignore 'Star'
%include &quot;myheader.h&quot;
</pre>
</div>
<h3><a name="SWIG_default_args">5.4.8 Default/optional arguments</a></h3>
<p> SWIG supports default arguments in both C and C++ code. For example:</p>
<div class="code">
<pre>
int plot(double x, double y, int color=WHITE);
</pre>
</div>
<p> In this case, SWIG generates wrapper code where the default
 arguments are optional in the target language. For example, this
 function could be used in Tcl as follows :</p>
<div class="targetlang">
<pre>
% plot -3.4 7.5    # Use default value
% plot -3.4 7.5 10 # set color to 10 instead

</pre>
</div>
<p> Although the ISO C standard does not allow default arguments,
 default arguments specified in a SWIG interface work with both C and
 C++.</p>
<p><b> Note:</b> There is a subtle semantic issue concerning the use of
 default arguments and the SWIG generated wrapper code. When default
 arguments are used in C code, the default values are emitted into the
 wrappers and the function is invoked with a full set of arguments. This
 is different to when wrapping C++ where an overloaded wrapper method is
 generated for each defaulted argument. Please refer to the section on <a
href="#SWIGPlus_default_args">default arguments</a> in the C++ chapter
 for further details.</p>
<h3><a name="SWIG_nn30">5.4.9 Pointers to functions and callbacks</a></h3>
<p> Occasionally, a C library may include functions that expect to
 receive pointers to functions--possibly to serve as callbacks. SWIG
 provides full support for function pointers when the callback functions
 are defined in C and not in the target language. For example, consider
 a function like this:</p>
<div class="code">
<pre>
int binary_op(int a, int b, int (*op)(int, int));
</pre>
</div>
<p> When you first wrap something like this into an extension module,
 you may find the function to be impossible to use. For instance, in
 Python:</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; def add(x, y):
...     return x+y
...
&gt;&gt;&gt; binary_op(3, 4, add)
Traceback (most recent call last):
  File &quot;&lt;stdin&gt;&quot;, line 1, in ?
TypeError: Type error. Expected _p_f_int_int__int
&gt;&gt;&gt;
</pre>
</div>
<p> The reason for this error is that SWIG doesn't know how to map a
 scripting language function into a C callback. However, existing C
 functions can be used as arguments provided you install them as
 constants. One way to do this is to use the <tt>%constant</tt>
 directive like this:</p>
<div class="code">
<pre>
/* Function with a callback */
int binary_op(int a, int b, int (*op)(int, int));

/* Some callback functions */
%constant int add(int, int);
%constant int sub(int, int);
%constant int mul(int, int);
</pre>
</div>
<p> In this case, <tt>add</tt>, <tt>sub</tt>, and <tt>mul</tt> become
 function pointer constants in the target scripting language. This
 allows you to use them as follows:</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; binary_op(3, 4, add)
7
&gt;&gt;&gt; binary_op(3, 4, mul)
12
&gt;&gt;&gt;
</pre>
</div>
<p> Unfortunately, by declaring the callback functions as constants,
 they are no longer accessible as functions. For example:</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; add(3, 4)
Traceback (most recent call last):
  File &quot;&lt;stdin&gt;&quot;, line 1, in ?
TypeError: object is not callable: '_ff020efc_p_f_int_int__int'
&gt;&gt;&gt;
</pre>
</div>
<p> If you want to make a function available as both a callback function
 and a function, you can use the <tt>%callback</tt> and <tt>%nocallback</tt>
 directives like this:</p>
<div class="code">
<pre>
/* Function with a callback */
int binary_op(int a, int b, int (*op)(int, int));

/* Some callback functions */
%callback(&quot;%s_cb&quot;);
int add(int, int);
int sub(int, int);
int mul(int, int);
%nocallback;
</pre>
</div>
<p> The argument to <tt>%callback</tt> is a printf-style format string
 that specifies the naming convention for the callback constants (<tt>%s</tt>
 gets replaced by the function name). The callback mode remains in
 effect until it is explicitly disabled using <tt>%nocallback</tt>. When
 you do this, the interface now works as follows:</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; binary_op(3, 4, add_cb)
7
&gt;&gt;&gt; binary_op(3, 4, mul_cb)
12
&gt;&gt;&gt; add(3, 4)
7
&gt;&gt;&gt; mul(3, 4)
12
</pre>
</div>
<p> Notice that when the function is used as a callback, special names
 such as <tt>add_cb</tt> are used instead. To call the function
 normally, just use the original function name such as <tt>add()</tt>.</p>
<p> SWIG provides a number of extensions to standard C printf formatting
 that may be useful in this context. For instance, the following
 variation installs the callbacks as all upper case constants such as <tt>
ADD</tt>, <tt>SUB</tt>, and <tt>MUL</tt>:</p>
<div class="code">
<pre>
/* Some callback functions */
%callback(&quot;%(uppercase)s&quot;);
int add(int, int);
int sub(int, int);
int mul(int, int);
%nocallback;
</pre>
</div>
<p> A format string of <tt>&quot;%(lowercase)s&quot;</tt> converts all characters
 to lower case. A string of <tt>&quot;%(title)s&quot;</tt> capitalizes the first
 character and converts the rest to lower case.</p>
<p> And now, a final note about function pointer support. Although SWIG
 does not normally allow callback functions to be written in the target
 language, this can be accomplished with the use of typemaps and other
 advanced SWIG features. See the <a href="#Typemaps">Typemaps chapter</a>
 for more about typemaps and individual target language chapters for
 more on callbacks. The 'director' feature can be used to make callbacks
 from C/C++ into the target language, see <a href="#SWIGPlus_target_language_callbacks">
Callbacks to the target language</a>.</p>
<h2><a name="SWIG_nn31">5.5 Structures and unions</a></h2>
<p> This section describes the behavior of SWIG when processing ISO C
 structures and union declarations. Extensions to handle C++ are
 described in the next section.</p>
<p> If SWIG encounters the definition of a structure or union, it
 creates a set of accessor functions. Although SWIG does not need
 structure definitions to build an interface, providing definitions
 makes it possible to access structure members. The accessor functions
 generated by SWIG simply take a pointer to an object and allow access
 to an individual member. For example, the declaration :</p>
<div class="code">
<pre>
struct Vector {
  double x, y, z;
}

</pre>
</div>
<p> gets transformed into the following set of accessor functions :</p>
<div class="code">
<pre>
double Vector_x_get(struct Vector *obj) {
  return obj-&gt;x;
}
double Vector_y_get(struct Vector *obj) { 
  return obj-&gt;y;
}
double Vector_z_get(struct Vector *obj) { 
  return obj-&gt;z;
}
void Vector_x_set(struct Vector *obj, double value) {
  obj-&gt;x = value;
}
void Vector_y_set(struct Vector *obj, double value) {
  obj-&gt;y = value;
}
void Vector_z_set(struct Vector *obj, double value) {
  obj-&gt;z = value;
}
</pre>
</div>
<p> In addition, SWIG creates default constructor and destructor
 functions if none are defined in the interface. For example:</p>
<div class="code">
<pre>
struct Vector *new_Vector() {
  return (Vector *) calloc(1, sizeof(struct Vector));
}
void delete_Vector(struct Vector *obj) {
  free(obj);
}
</pre>
</div>
<p> Using these low-level accessor functions, an object can be minimally
 manipulated from the target language using code like this:</p>
<div class="code">
<pre>
v = new_Vector()
Vector_x_set(v, 2)
Vector_y_set(v, 10)
Vector_z_set(v, -5)
...
delete_Vector(v)
</pre>
</div>
<p> However, most of SWIG's language modules also provide a high-level
 interface that is more convenient. Keep reading.</p>
<h3><a name="SWIG_nn32">5.5.1 Typedef and structures</a></h3>
<p> SWIG supports the following construct which is quite common in C
 programs :</p>
<div class="code">
<pre>
typedef struct {
  double x, y, z;
} Vector;

</pre>
</div>
<p> When encountered, SWIG assumes that the name of the object is
 `Vector' and creates accessor functions like before. The only
 difference is that the use of <tt>typedef</tt> allows SWIG to drop the <tt>
struct</tt> keyword on its generated code. For example:</p>
<div class="code">
<pre>
double Vector_x_get(Vector *obj) {
  return obj-&gt;x;
}
</pre>
</div>
<p> If two different names are used like this :</p>
<div class="code">
<pre>
typedef struct vector_struct {
  double x, y, z;
} Vector;

</pre>
</div>
<p> the name <tt>Vector</tt> is used instead of <tt>vector_struct</tt>
 since this is more typical C programming style. If declarations defined
 later in the interface use the type <tt>struct vector_struct</tt>, SWIG
 knows that this is the same as <tt>Vector</tt> and it generates the
 appropriate type-checking code.</p>
<h3><a name="SWIG_nn33">5.5.2 Character strings and structures</a></h3>
<p> Structures involving character strings require some care. SWIG
 assumes that all members of type <tt>char *</tt> have been dynamically
 allocated using <tt>malloc()</tt> and that they are NULL-terminated
 ASCII strings. When such a member is modified, the previous contents
 will be released, and the new contents allocated. For example :</p>
<div class="code">
<pre>
%module mymodule
...
struct Foo {
  char *name;
  ...
}

</pre>
</div>
<p> This results in the following accessor functions :</p>
<div class="code">
<pre>
char *Foo_name_get(Foo *obj) {
  return Foo-&gt;name;
}

char *Foo_name_set(Foo *obj, char *c) {
  if (obj-&gt;name)
    free(obj-&gt;name);
  obj-&gt;name = (char *) malloc(strlen(c)+1);
  strcpy(obj-&gt;name, c);
  return obj-&gt;name;
}
</pre>
</div>
<p> If this behavior differs from what you need in your applications,
 the SWIG &quot;memberin&quot; typemap can be used to change it. See the typemaps
 chapter for further details.</p>
<p> Note: If the <tt>-c++</tt> option is used, <tt>new</tt> and <tt>
delete</tt> are used to perform memory allocation.</p>
<h3><a name="SWIG_nn34">5.5.3 Array members</a></h3>
<p> Arrays may appear as the members of structures, but they will be
 read-only. SWIG will write an accessor function that returns the
 pointer to the first element of the array, but will not write a
 function to change the contents of the array itself. When this
 situation is detected, SWIG may generate a warning message such as the
 following :</p>
<div class="shell">
<pre>
interface.i:116. Warning. Array member will be read-only
</pre>
</div>
<p> To eliminate the warning message, typemaps can be used, but this is
 discussed in a later chapter. In many cases, the warning message is
 harmless.</p>
<h3><a name="SWIG_structure_data_members">5.5.4 Structure data members</a>
</h3>
<p> Occasionally, a structure will contain data members that are
 themselves structures. For example:</p>
<div class="code">
<pre>
typedef struct Foo {
  int x;
} Foo;

typedef struct Bar {
  int y;
  Foo f;           /* struct member */
} Bar;
</pre>
</div>
<p> When a structure member is wrapped, it is handled as a pointer,
 unless the <tt>%naturalvar</tt> directive is used where it is handled
 more like a C++ reference (see <a href="#SWIGPlus_member_data">C++
 Member data</a>). The accessors to the member variable as a pointer are
 effectively wrapped as follows:</p>
<div class="code">
<pre>
Foo *Bar_f_get(Bar *b) {
  return &amp;b-&gt;f;
}
void Bar_f_set(Bar *b, Foo *value) {
  b-&gt;f = *value;
}
</pre>
</div>
<p> The reasons for this are somewhat subtle but have to do with the
 problem of modifying and accessing data inside the data member. For
 example, suppose you wanted to modify the value of <tt>f.x</tt> of a <tt>
Bar</tt> object like this:</p>
<div class="code">
<pre>
Bar *b;
b-&gt;f.x = 37;
</pre>
</div>
<p> Translating this assignment to function calls (as would be used
 inside the scripting language interface) results in the following code:</p>
<div class="code">
<pre>
Bar *b;
Foo_x_set(Bar_f_get(b), 37);
</pre>
</div>
<p> In this code, if the <tt>Bar_f_get()</tt> function were to return a <tt>
Foo</tt> instead of a <tt>Foo *</tt>, then the resulting modification
 would be applied to a<em> copy</em> of <tt>f</tt> and not the data
 member <tt>f</tt> itself. Clearly that's not what you want!</p>
<p> It should be noted that this transformation to pointers only occurs
 if SWIG knows that a data member is a structure or class. For instance,
 if you had a structure like this,</p>
<div class="code">
<pre>
struct Foo {
  WORD   w;
};
</pre>
</div>
<p> and nothing was known about <tt>WORD</tt>, then SWIG will generate
 more normal accessor functions like this:</p>
<div class="code">
<pre>
WORD Foo_w_get(Foo *f) {
  return f-&gt;w;
}
void Foo_w_set(FOO *f, WORD value) {
  f-&gt;w = value;
}
</pre>
</div>
<p><b> Compatibility Note:</b> SWIG-1.3.11 and earlier releases
 transformed all non-primitive member datatypes to pointers. Starting in
 SWIG-1.3.12, this transformation<em> only</em> occurs if a datatype is
 known to be a structure, class, or union. This is unlikely to break
 existing code. However, if you need to tell SWIG that an undeclared
 datatype is really a struct, simply use a forward struct declaration
 such as <tt>&quot;struct Foo;&quot;</tt>.</p>
<h3><a name="SWIG_nn36">5.5.5 C constructors and destructors</a></h3>
<p> When wrapping structures, it is generally useful to have a mechanism
 for creating and destroying objects. If you don't do anything, SWIG
 will automatically generate functions for creating and destroying
 objects using <tt>malloc()</tt> and <tt>free()</tt>. Note: the use of <tt>
malloc()</tt> only applies when SWIG is used on C code (i.e., when the <tt>
-c++</tt> option is<em> not</em> supplied on the command line). C++ is
 handled differently.</p>
<p> If you don't want SWIG to generate default constructors for your
 interfaces, you can use the <tt>%nodefaultctor</tt> directive or the <tt>
-nodefaultctor</tt> command line option. For example:</p>
<div class="shell">
<pre>
swig -nodefaultctor example.i 
</pre>
</div>
<p> or</p>
<div class="code">
<pre>
%module foo
...
%nodefaultctor;        // Don't create default constructors
... declarations ...
%clearnodefaultctor;   // Re-enable default constructors
</pre>
</div>
<p> If you need more precise control, <tt>%nodefaultctor</tt> can
 selectively target individual structure definitions. For example:</p>
<div class="code">
<pre>
%nodefaultctor Foo;      // No default constructor for Foo
...
struct Foo {             // No default constructor generated.
};

struct Bar {             // Default constructor generated.
};
</pre>
</div>
<p> Since ignoring the implicit or default destructors most of the time
 produces memory leaks, SWIG will always try to generate them. If
 needed, however, you can selectively disable the generation of the
 default/implicit destructor by using <tt>%nodefaultdtor</tt></p>
<div class="code">
<pre>
%nodefaultdtor Foo; // No default/implicit destructor for Foo
...
struct Foo {              // No default destructor is generated.
};

struct Bar {              // Default destructor generated.
};
</pre>
</div>
<p><b> Compatibility note:</b> Prior to SWIG-1.3.7, SWIG did not
 generate default constructors or destructors unless you explicitly
 turned them on using <tt>-make_default</tt>. However, it appears that
 most users want to have constructor and destructor functions so it has
 now been enabled as the default behavior.</p>
<p><b> Note:</b> There are also the <tt>-nodefault</tt> option and <tt>
%nodefault</tt> directive, which disable both the default or implicit
 destructor generation. This could lead to memory leaks across the
 target languages, and it is highly recommended you don't use them.</p>
<h3><a name="SWIG_adding_member_functions">5.5.6 Adding member functions
 to C structures</a></h3>
<p> Most languages provide a mechanism for creating classes and
 supporting object oriented programming. From a C standpoint, object
 oriented programming really just boils down to the process of attaching
 functions to structures. These functions normally operate on an
 instance of the structure (or object). Although there is a natural
 mapping of C++ to such a scheme, there is no direct mechanism for
 utilizing it with C code. However, SWIG provides a special <tt>%extend</tt>
 directive that makes it possible to attach methods to C structures for
 purposes of building an object oriented interface. Suppose you have a C
 header file with the following declaration :</p>
<div class="code">
<pre>
/* file : vector.h */
...
typedef struct Vector {
  double x, y, z;
} Vector;

</pre>
</div>
<p> You can make a <tt>Vector</tt> look a lot like a class by writing a
 SWIG interface like this:</p>
<div class="code">
<pre>
// file : vector.i
%module mymodule
%{
#include &quot;vector.h&quot;
%}

%include &quot;vector.h&quot;          // Just grab original C header file
%extend Vector {             // Attach these functions to struct Vector
  Vector(double x, double y, double z) {
    Vector *v;
    v = (Vector *) malloc(sizeof(Vector));
    v-&gt;x = x;
    v-&gt;y = y;
    v-&gt;z = z;
    return v;
  }
  ~Vector() {
    free($self);
  }
  double magnitude() {
    return sqrt($self-&gt;x*$self-&gt;x+$self-&gt;y*$self-&gt;y+$self-&gt;z*$self-&gt;z);
  }
  void print() {
    printf(&quot;Vector [%g, %g, %g]\n&quot;, $self-&gt;x, $self-&gt;y, $self-&gt;z);
  }
};

</pre>
</div>
<p> Note the usage of the <tt>$self</tt> special variable. Its usage is
 identical to a C++ 'this' pointer and should be used whenever access to
 the struct instance is required. Also note that C++ constructor and
 destructor syntax has been used to simulate a constructor and
 destructor, even for C code. There is one subtle difference to a normal
 C++ constructor implementation though and that is although the
 constructor declaration is as per a normal C++ constructor, the newly
 constructed object must be returned<b> as if</b> the constructor
 declaration had a return value, a <tt>Vector *</tt> in this case.</p>
<p> Now, when used with proxy classes in Python, you can do things like
 this :</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; v = Vector(3, 4, 0)                 # Create a new vector
&gt;&gt;&gt; print v.magnitude()                # Print magnitude
5.0
&gt;&gt;&gt; v.print()                  # Print it out
[ 3, 4, 0 ]
&gt;&gt;&gt; del v                      # Destroy it
</pre>
</div>
<p> The <tt>%extend</tt> directive can also be used inside the
 definition of the Vector structure. For example:</p>
<div class="code">
<pre>
// file : vector.i
%module mymodule
%{
#include &quot;vector.h&quot;
%}

typedef struct Vector {
  double x, y, z;
  %extend {
    Vector(double x, double y, double z) { ... }
    ~Vector() { ... }
    ...
  }
} Vector;
</pre>
</div>
<p> Note that <tt>%extend</tt> can be used to access externally written
 functions provided they follow the naming convention used in this
 example :</p>
<div class="code">
<pre>
/* File : vector.c */
/* Vector methods */
#include &quot;vector.h&quot;
Vector *new_Vector(double x, double y, double z) {
  Vector *v;
  v = (Vector *) malloc(sizeof(Vector));
  v-&gt;x = x;
  v-&gt;y = y;
  v-&gt;z = z;
  return v;
}
void delete_Vector(Vector *v) {
  free(v);
}

double Vector_magnitude(Vector *v) {
  return sqrt(v-&gt;x*v-&gt;x+v-&gt;y*v-&gt;y+v-&gt;z*v-&gt;z);
}

// File : vector.i
// Interface file
%module mymodule
%{
#include &quot;vector.h&quot;
%}

typedef struct Vector {
  double x, y, z;
  %extend {
    Vector(int, int, int); // This calls new_Vector()
    ~Vector();           // This calls delete_Vector()
    double magnitude();  // This will call Vector_magnitude()
    ...
  }
} Vector;
</pre>
</div>
<p> The name used for %extend should be the name of the struct and not
 the name of any typedef to the struct. For example:</p>
<div class="code">
<pre>
typedef struct Integer {
  int value;
} Int;
%extend Integer { ...  } /* Correct name */
%extend Int { ...  } /* Incorrect name */

struct Float {
  float value;
};
typedef struct Float FloatValue;
%extend Float { ...  } /* Correct name */
%extend FloatValue { ...  } /* Incorrect name */
</pre>
</div>
<p> There is one exception to this rule and that is when the struct is
 anonymously named such as:</p>
<div class="code">
<pre>
typedef struct {
  double value;
} Double;
%extend Double { ...  } /* Okay */
</pre>
</div>
<p> A little known feature of the <tt>%extend</tt> directive is that it
 can also be used to add synthesized attributes or to modify the
 behavior of existing data attributes. For example, suppose you wanted
 to make <tt>magnitude</tt> a read-only attribute of <tt>Vector</tt>
 instead of a method. To do this, you might write some code like this:</p>
<div class="code">
<pre>
// Add a new attribute to Vector
%extend Vector {
  const double magnitude;
}
// Now supply the implementation of the Vector_magnitude_get function
%{
const double Vector_magnitude_get(Vector *v) {
  return (const double) sqrt(v-&gt;x*v-&gt;x+v-&gt;y*v-&gt;y+v-&gt;z*v-&gt;z);
}
%}

</pre>
</div>
<p> Now, for all practical purposes, <tt>magnitude</tt> will appear like
 an attribute of the object.</p>
<p> A similar technique can also be used to work with data members that
 you want to process. For example, consider this interface:</p>
<div class="code">
<pre>
typedef struct Person {
  char name[50];
  ...
} Person;
</pre>
</div>
<p> Say you wanted to ensure <tt>name</tt> was always upper case, you
 can rewrite the interface as follows to ensure this occurs whenever a
 name is read or written to:</p>
<div class="code">
<pre>
typedef struct Person {
  %extend {
    char name[50];
  }
  ...
} Person;

%{
#include &lt;string.h&gt;
#include &lt;ctype.h&gt;

void make_upper(char *name) {
  char *c;
  for (c = name; *c; ++c)
    *c = (char)toupper((int)*c);
}

/* Specific implementation of set/get functions forcing capitalization */

char *Person_name_get(Person *p) {
  make_upper(p-&gt;name);
  return p-&gt;name;
}

void Person_name_set(Person *p, char *val) {
  strncpy(p-&gt;name, val, 50);
  make_upper(p-&gt;name);
}
%}
</pre>
</div>
<p> Finally, it should be stressed that even though <tt>%extend</tt> can
 be used to add new data members, these new members can not require the
 allocation of additional storage in the object (e.g., their values must
 be entirely synthesized from existing attributes of the structure or
 obtained elsewhere).</p>
<p><b> Compatibility note:</b> The <tt>%extend</tt> directive is a new
 name for the <tt>%addmethods</tt> directive. Since <tt>%addmethods</tt>
 could be used to extend a structure with more than just methods, a more
 suitable directive name has been chosen.</p>
<h3><a name="SWIG_nested_structs">5.5.7 Nested structures</a></h3>
<p> Occasionally, a C program will involve structures like this :</p>
<div class="code">
<pre>
typedef struct Object {
  int objtype;
  union {
    int ivalue;
    double dvalue;
    char *strvalue;
    void *ptrvalue;
  } intRep;
} Object;

</pre>
</div>
<p> When SWIG encounters this, it performs a structure splitting
 operation that transforms the declaration into the equivalent of the
 following:</p>
<div class="code">
<pre>
typedef union {
  int ivalue;
  double dvalue;
  char *strvalue;
  void *ptrvalue;
} Object_intRep;

typedef struct Object {
  int objType;
  Object_intRep intRep;
} Object;

</pre>
</div>
<p> SWIG will then create an <tt>Object_intRep</tt> structure for use
 inside the interface file. Accessor functions will be created for both
 structures. In this case, functions like this would be created :</p>
<div class="code">
<pre>
Object_intRep *Object_intRep_get(Object *o) {
  return (Object_intRep *) &amp;o-&gt;intRep;
}
int Object_intRep_ivalue_get(Object_intRep *o) {
  return o-&gt;ivalue;
}
int Object_intRep_ivalue_set(Object_intRep *o, int value) {
  return (o-&gt;ivalue = value);
}
double Object_intRep_dvalue_get(Object_intRep *o) {
  return o-&gt;dvalue;
}
... etc ...

</pre>
</div>
<p> Although this process is a little hairy, it works like you would
 expect in the target scripting language--especially when proxy classes
 are used. For instance, in Perl:</p>
<div class="targetlang">
<pre>
# Perl5 script for accessing nested member
$o = CreateObject();                    # Create an object somehow
$o-&gt;{intRep}-&gt;{ivalue} = 7              # Change value of o.intRep.ivalue
</pre>
</div>
<p> If you have a lot of nested structure declarations, it is advisable
 to double-check them after running SWIG. Although, there is a good
 chance that they will work, you may have to modify the interface file
 in certain cases.</p>
<p> Finally, note that nesting is handled differently in C++ mode, see <a
href="#SWIGPlus_nested_classes">Nested classes</a>.</p>
<h3><a name="SWIG_nn39">5.5.8 Other things to note about structure
 wrapping</a></h3>
<p> SWIG doesn't care if the declaration of a structure in a <tt>.i</tt>
 file exactly matches that used in the underlying C code (except in the
 case of nested structures). For this reason, there are no problems
 omitting problematic members or simply omitting the structure
 definition altogether. If you are happy passing pointers around, this
 can be done without ever giving SWIG a structure definition.</p>
<p> Starting with SWIG1.3, a number of improvements have been made to
 SWIG's code generator. Specifically, even though structure access has
 been described in terms of high-level accessor functions such as this,</p>
<div class="code">
<pre>
double Vector_x_get(Vector *v) {
  return v-&gt;x;
}
</pre>
</div>
<p> most of the generated code is actually inlined directly into wrapper
 functions. Therefore, no function <tt>Vector_x_get()</tt> actually
 exists in the generated wrapper file. For example, when creating a Tcl
 module, the following function is generated instead:</p>
<div class="code">
<pre>
static int
_wrap_Vector_x_get(ClientData clientData, Tcl_Interp *interp, 
                   int objc, Tcl_Obj *CONST objv[]) {
  struct Vector *arg1 ;
  double result ;

  if (SWIG_GetArgs(interp, objc, objv, &quot;p:Vector_x_get self &quot;, &amp;arg0,
                   SWIGTYPE_p_Vector) == TCL_ERROR)
    return TCL_ERROR;
  result = (double ) (arg1-&gt;x);
  Tcl_SetObjResult(interp, Tcl_NewDoubleObj((double) result));
  return TCL_OK;
}
</pre>
</div>
<p> The only exception to this rule are methods defined with <tt>%extend</tt>
. In this case, the added code is contained in a separate function.</p>
<p> Finally, it is important to note that most language modules may
 choose to build a more advanced interface. Although you may never use
 the low-level interface described here, most of SWIG's language modules
 use it in some way or another.</p>
<h2><a name="SWIG_nn40">5.6 Code Insertion</a></h2>
<p> Sometimes it is necessary to insert special code into the resulting
 wrapper file generated by SWIG. For example, you may want to include
 additional C code to perform initialization or other operations. There
 are four common ways to insert code, but it's useful to know how the
 output of SWIG is structured first.</p>
<h3><a name="SWIG_nn41">5.6.1 The output of SWIG</a></h3>
<p> When SWIG creates its output C/C++ file, it is broken up into five
 sections corresponding to runtime code, headers, wrapper functions, and
 module initialization code (in that order).</p>
<ul>
<li><b>Begin section</b>.
<br> A placeholder for users to put code at the beginning of the C/C++
 wrapper file. This is most often used to define preprocessor macros
 that are used in later sections.</li>
<li><b>Runtime code</b>.
<br> This code is internal to SWIG and is used to include type-checking
 and other support functions that are used by the rest of the module.</li>
<li><b>Header section</b>.
<br> This is user-defined support code that has been included by the <tt>
%{ ... %}</tt> directive. Usually this consists of header files and
 other helper functions.</li>
<li><b>Wrapper code</b>.
<br> These are the wrappers generated automatically by SWIG.</li>
<li><b>Module initialization</b>.
<br> The function generated by SWIG to initialize the module upon
 loading.</li>
</ul>
<h3><a name="SWIG_nn42">5.6.2 Code insertion blocks</a></h3>
<p> The <tt>%insert</tt> directive enables inserting blocks of code into
 a given section of the generated code. It can be used in one of two
 ways:</p>
<div class="code">
<pre>
%insert(&quot;section&quot;) &quot;filename&quot;
%insert(&quot;section&quot;) %{ ... %}
</pre>
</div>
<p> The first will dump the contents of the file in the given <tt>
filename</tt> into the named <tt>section</tt>. The second inserts the
 code between the braces into the named <tt>section</tt>. For example,
 the following adds code into the runtime section:</p>
<div class="code">
<pre>
%insert(&quot;runtime&quot;) %{
  ... code in runtime section ...
%}
</pre>
</div>
<p> There are the 5 sections, however, some target languages add in
 additional sections and some of these result in code being generated
 into a target language file instead of the C/C++ wrapper file. These
 are documented when available in the target language chapters. Macros
 named after the code sections are available as additional directives
 and these macro directives are normally used instead of <tt>%insert</tt>
. For example, <tt>%runtime</tt> is used instead of <tt>
%insert(&quot;runtime&quot;)</tt>. The valid sections and order of the sections in
 the generated C/C++ wrapper file is as shown:</p>
<div class="code">
<pre>
%begin %{
  ... code in begin section ...
%}

%runtime %{
  ... code in runtime section ...
%}

%header %{
  ... code in header section ...
%}

%wrapper %{
  ... code in wrapper section ...
%}

%init %{
  ... code in init section ...
%}
</pre>
</div>
<p> The bare <tt>%{ ... %}</tt> directive is a shortcut that is the same
 as <tt>%header %{ ... %}</tt>.</p>
<p> The <tt>%begin</tt> section is effectively empty as it just contains
 the SWIG banner by default. This section is provided as a way for users
 to insert code at the top of the wrapper file before any other code is
 generated. Everything in a code insertion block is copied verbatim into
 the output file and is not parsed by SWIG. Most SWIG input files have
 at least one such block to include header files and support C code.
 Additional code blocks may be placed anywhere in a SWIG file as needed.</p>
<div class="code">
<pre>
%module mymodule
%{
#include &quot;my_header.h&quot;
%}
... Declare functions here
%{

void some_extra_function() {
  ...
}
%}
</pre>
</div>
<p> A common use for code blocks is to write &quot;helper&quot; functions. These
 are functions that are used specifically for the purpose of building an
 interface, but which are generally not visible to the normal C program.
 For example :</p>
<div class="code">
<pre>
%{
/* Create a new vector */
static Vector *new_Vector() {
  return (Vector *) malloc(sizeof(Vector));
}

%}
// Now wrap it 
Vector *new_Vector();
</pre>
</div>
<h3><a name="SWIG_nn43">5.6.3 Inlined code blocks</a></h3>
<p> Since the process of writing helper functions is fairly common,
 there is a special inlined form of code block that is used as follows :</p>
<div class="code">
<pre>
%inline %{
/* Create a new vector */
Vector *new_Vector() {
  return (Vector *) malloc(sizeof(Vector));
}
%}
</pre>
</div>
<p> This is the same as writing:</p>
<div class="code">
<pre>
%{
/* Create a new vector */
Vector *new_Vector() {
  return (Vector *) malloc(sizeof(Vector));
}
%}

/* Create a new vector */
Vector *new_Vector() {
  return (Vector *) malloc(sizeof(Vector));
}
</pre>
</div>
<p> In other words, the <tt>%inline</tt> directive inserts all of the
 code that follows verbatim into the header portion of an interface
 file. The code is then parsed by both the SWIG preprocessor and parser.
 Thus, the above example creates a new command <tt>new_Vector</tt> using
 only one declaration. Since the code inside an <tt>%inline %{ ... %}</tt>
 block is given to both the C compiler and SWIG, it is illegal to
 include any SWIG directives inside a <tt>%{ ... %}</tt> block.</p>
<p><b> Note:</b> The usual SWIG C preprocessor rules apply to code in <tt>
%apply</tt> blocks when SWIG parses this code. For example, as mentioned
 earlier, <a href="#SWIG_nn6">SWIG's C Preprocessor</a> does not follow <tt>
#include</tt> directives by default.</p>
<h3><a name="SWIG_nn44">5.6.4 Initialization blocks</a></h3>
<p> When code is included in the <tt>%init</tt> section, it is copied
 directly into the module initialization function. For example, if you
 needed to perform some extra initialization on module loading, you
 could write this:</p>
<div class="code">
<pre>
%init %{
  init_variables();
%}
</pre>
</div>
<p> Please note that some language backends (e.g. C# or Java) don't have
 any initialization function, hence you should define a global object
 performing the necessary initialization for them instead:</p>
<div class="code">
<pre>
%init %{
  static struct MyInit { MyInit() { init_variables(); } } myInit;
%}
</pre>
</div>
<h2><a name="SWIG_nn45">5.7 An Interface Building Strategy</a></h2>
<p> This section describes the general approach for building interfaces
 with SWIG. The specifics related to a particular scripting language are
 found in later chapters.</p>
<h3><a name="SWIG_nn46">5.7.1 Preparing a C program for SWIG</a></h3>
<p> SWIG doesn't require modifications to your C code, but if you feed
 it a collection of raw C header files or source code, the results might
 not be what you expect---in fact, they might be awful. Here's a series
 of steps you can follow to make an interface for a C program :</p>
<ul>
<li>Identify the functions that you want to wrap. It's probably not
 necessary to access every single function of a C program--thus, a
 little forethought can dramatically simplify the resulting scripting
 language interface. C header files are a particularly good source for
 finding things to wrap.</li>
<li>Create a new interface file to describe the scripting language
 interface to your program.</li>
<li>Copy the appropriate declarations into the interface file or use
 SWIG's <tt>%include</tt> directive to process an entire C source/header
 file.</li>
<li>Make sure everything in the interface file uses ISO C/C++ syntax.</li>
<li>Make sure all necessary `<tt>typedef</tt>' declarations and
 type-information is available in the interface file. In particular,
 ensure that the type information is specified in the correct order as
 required by a C/C++ compiler. Most importantly, define a type before it
 is used! A C compiler will tell you if the full type information is not
 available if it is needed, whereas SWIG will usually not warn or error
 out as it is designed to work without full type information. However,
 if type information is not specified correctly, the wrappers can be
 sub-optimal and even result in uncompilable C/C++ code.</li>
<li>If your program has a main() function, you may need to rename it
 (read on).</li>
<li>Run SWIG and compile.</li>
</ul>
<p> Although this may sound complicated, the process turns out to be
 fairly easy once you get the hang of it.</p>
<p> In the process of building an interface, SWIG may encounter syntax
 errors or other problems. The best way to deal with this is to simply
 copy the offending code into a separate interface file and edit it.
 However, the SWIG developers have worked very hard to improve the SWIG
 parser--you should report parsing errors to the <a href="http://www.swig.org/mail.html">
swig-devel mailing list</a> or to the <a href="http://www.swig.org/bugs.html">
SWIG bug tracker</a>.</p>
<h3><a name="SWIG_nn47">5.7.2 The SWIG interface file</a></h3>
<p> The preferred method of using SWIG is to generate a separate
 interface file. Suppose you have the following C header file :</p>
<div class="code">
<pre>
/* File : header.h */

#include &lt;stdio.h&gt;
#include &lt;math.h&gt;

extern int foo(double);
extern double bar(int, int);
extern void dump(FILE *f);

</pre>
</div>
<p> A typical SWIG interface file for this header file would look like
 the following :</p>
<div class="code">
<pre>
/* File : interface.i */
%module mymodule
%{
#include &quot;header.h&quot;
%}
extern int foo(double);
extern double bar(int, int);
extern void dump(FILE *f);

</pre>
</div>
<p> Of course, in this case, our header file is pretty simple so we
 could use a simpler approach and use an interface file like this:</p>
<div class="code">
<pre>
/* File : interface.i */
%module mymodule
%{
#include &quot;header.h&quot;
%}
%include &quot;header.h&quot;
</pre>
</div>
<p> The main advantage of this approach is minimal maintenance of an
 interface file for when the header file changes in the future. In more
 complex projects, an interface file containing numerous <tt>%include</tt>
 and <tt>#include</tt> statements like this is one of the most common
 approaches to interface file design due to lower maintenance overhead.</p>
<h3><a name="SWIG_nn48">5.7.3 Why use separate interface files?</a></h3>
<p> Although SWIG can parse many header files, it is more common to
 write a special <tt>.i</tt> file defining the interface to a package.
 There are several reasons why you might want to do this:</p>
<ul>
<li>It is rarely necessary to access every single function in a large
 package. Many C functions might have little or no use in a scripted
 environment. Therefore, why wrap them?</li>
<li>Separate interface files provide an opportunity to provide more
 precise rules about how an interface is to be constructed.</li>
<li>Interface files can provide more structure and organization.</li>
<li>SWIG can't parse certain definitions that appear in header files.
 Having a separate file allows you to eliminate or work around these
 problems.</li>
<li>Interface files provide a more precise definition of what the
 interface is. Users wanting to extend the system can go to the
 interface file and immediately see what is available without having to
 dig it out of header files.</li>
</ul>
<h3><a name="SWIG_nn49">5.7.4 Getting the right header files</a></h3>
<p> Sometimes, it is necessary to use certain header files in order for
 the code generated by SWIG to compile properly. Make sure you include
 certain header files by using a <tt>%{ %}</tt> block like this:</p>
<div class="code">
<pre>
%module graphics
%{
#include &lt;GL/gl.h&gt;
#include &lt;GL/glu.h&gt;
%}

// Put the rest of the declarations here
...
</pre>
</div>
<h3><a name="SWIG_nn50">5.7.5 What to do with main()</a></h3>
<p> If your program defines a <tt>main()</tt> function, you may need to
 get rid of it or rename it in order to use a scripting language. Most
 scripting languages define their own <tt>main()</tt> procedure that is
 called instead. <tt>main()</tt> also makes no sense when working with
 dynamic loading. There are a few approaches to solving the <tt>main()</tt>
 conflict :</p>
<ul>
<li>Get rid of <tt>main()</tt> entirely.</li>
<li>Rename <tt>main()</tt> to something else. You can do this by
 compiling your C program with an option like <tt>-Dmain=oldmain</tt>.</li>
<li>Use conditional compilation to only include <tt>main()</tt> when not
 using a scripting language.</li>
</ul>
<p> Getting rid of <tt>main()</tt> may cause potential initialization
 problems of a program. To handle this problem, you may consider writing
 a special function called <tt>program_init()</tt> that initializes your
 program upon startup. This function could then be called either from
 the scripting language as the first operation, or when the SWIG
 generated module is loaded.</p>
<p> As a general note, many C programs only use the <tt>main()</tt>
 function to parse command line options and to set parameters. However,
 by using a scripting language, you are probably trying to create a
 program that is more interactive. In many cases, the old <tt>main()</tt>
 program can be completely replaced by a Perl, Python, or Tcl script.</p>
<p><b> Note:</b> In some cases, you might be inclined to create a
 scripting language wrapper for <tt>main()</tt>. If you do this, the
 compilation will probably work and your module might even load
 correctly. The only trouble is that when you call your <tt>main()</tt>
 wrapper, you will find that it actually invokes the <tt>main()</tt> of
 the scripting language interpreter itself! This behavior is a side
 effect of the symbol binding mechanism used in the dynamic linker. The
 bottom line: don't do this.</p>
<HR NOSHADE>
<h1><a name="SWIGPlus">6 SWIG and C++</a></h1>

<!-- INDEX -->
<div class="sectiontoc">
<ul>
<li><a href="#SWIGPlus_nn2">Comments on C++ Wrapping</a></li>
<li><a href="#SWIGPlus_nn3">Approach</a></li>
<li><a href="#SWIGPlus_nn4">Supported C++ features</a></li>
<li><a href="#SWIGPlus_nn5">Command line options and compilation</a></li>
<li><a href="#SWIGPlus_nn38">Proxy classes</a>
<ul>
<li><a href="#SWIGPlus_nn39">Construction of proxy classes</a></li>
<li><a href="#SWIGPlus_nn40">Resource management in proxies</a></li>
<li><a href="#SWIGPlus_nn41">Language specific details</a></li>
</ul>
</li>
<li><a href="#SWIGPlus_nn6">Simple C++ wrapping</a>
<ul>
<li><a href="#SWIGPlus_nn7">Constructors and destructors</a></li>
<li><a href="#SWIGPlus_nn8">Default constructors, copy constructors and
 implicit destructors</a></li>
<li><a href="#SWIGPlus_nn9">When constructor wrappers aren't created</a></li>
<li><a href="#SWIGPlus_nn10">Copy constructors</a></li>
<li><a href="#SWIGPlus_nn11">Member functions</a></li>
<li><a href="#SWIGPlus_nn12">Static members</a></li>
<li><a href="#SWIGPlus_member_data">Member data</a></li>
</ul>
</li>
<li><a href="#SWIGPlus_nn15">Protection</a></li>
<li><a href="#SWIGPlus_nn16">Enums and constants</a></li>
<li><a href="#SWIGPlus_nn17">Friends</a></li>
<li><a href="#SWIGPlus_nn18">References and pointers</a></li>
<li><a href="#SWIGPlus_nn19">Pass and return by value</a></li>
<li><a href="#SWIGPlus_nn20">Inheritance</a></li>
<li><a href="#SWIGPlus_nn21">A brief discussion of multiple inheritance,
 pointers, and type checking</a></li>
<li><a href="#SWIGPlus_default_args">Default arguments</a></li>
<li><a href="#SWIGPlus_overloaded_methods">Overloaded functions and
 methods</a>
<ul>
<li><a href="#SWIGPlus_nn24">Dispatch function generation</a></li>
<li><a href="#SWIGPlus_nn25">Ambiguity in overloading</a></li>
<li><a href="#SWIGPlus_ambiguity_resolution_renaming">Renaming and
 ambiguity resolution</a></li>
<li><a href="#SWIGPlus_nn27">Comments on overloading</a></li>
</ul>
</li>
<li><a href="#SWIGPlus_nn28">Overloaded operators</a></li>
<li><a href="#SWIGPlus_class_extension">Class extension</a></li>
<li><a href="#SWIGPlus_nn30">Templates</a>
<ul>
<li><a href="#SWIGPlus_template_directive">The %template directive</a></li>
<li><a href="#SWIGPlus_template_functions">Function templates</a></li>
<li><a href="#SWIGPlus_template_classes">Default template arguments</a></li>
<li><a href="#SWIGPlus_template_class_inheritance">Template base classes</a>
</li>
<li><a href="#SWIGPlus_template_specialization">Template specialization</a>
</li>
<li><a href="#SWIGPlus_template_member">Member templates</a></li>
<li><a href="#SWIGPlus_template_scoping">Scoping and templates</a></li>
<li><a href="#SWIGPlus_template_more">More on templates</a></li>
</ul>
</li>
<li><a href="#SWIGPlus_namespaces">Namespaces</a>
<ul>
<li><a href="#SWIGPlus_nspace">The nspace feature for namespaces</a></li>
</ul>
</li>
<li><a href="#SWIGPlus_renaming_templated_types_namespaces">Renaming
 templated types in namespaces</a></li>
<li><a href="#SWIGPlus_exception_specifications">Exception
 specifications</a></li>
<li><a href="#SWIGPlus_catches">Exception handling with %catches</a></li>
<li><a href="#SWIGPlus_nn33">Pointers to Members</a></li>
<li><a href="#SWIGPlus_smart_pointers">Smart pointers and operator-&gt;()</a>
</li>
<li><a href="#SWIGPlus_ref_unref">C++ reference counted objects -
 ref/unref feature</a></li>
<li><a href="#SWIGPlus_nn35">Using declarations and inheritance</a></li>
<li><a href="#SWIGPlus_nested_classes">Nested classes</a></li>
<li><a href="#SWIGPlus_const">A brief rant about const-correctness</a></li>
<li><a href="#SWIGPlus_target_language_callbacks">Callbacks to the
 target language</a>
<ul>
<li><a href="#SWIGPlus_director_classes_introduction">Introduction to
 director classes</a></li>
<li><a href="#SWIGPlus_directors_for_function_pointers">Using directors
 and target language callbacks</a></li>
</ul>
</li>
<li><a href="#SWIGPlus_nn42">Where to go for more information</a></li>
</ul>
</div>
<!-- INDEX -->
<p> This chapter describes SWIG's support for wrapping C++. It is mostly
 concerned about C++ as defined by the C++ 98 and 03 standards. For
 additions to the original C++ standard, please read the <a href="#CPlusPlus11">
SWIG and C++11</a>, <a href="#CPlusPlus14">SWIG and C++14</a> and <a href="#CPlusPlus17">
SWIG and C++17</a> chapters. As a prerequisite, you should first read
 the chapter <a href="#SWIG">SWIG Basics</a> to see how SWIG wraps ISO
 C. Support for C++ builds upon ISO C wrapping and that material will be
 useful in understanding this chapter.</p>
<h2><a name="SWIGPlus_nn2">6.1 Comments on C++ Wrapping</a></h2>
<p> Because of its complexity and the fact that C++ can be difficult to
 integrate with itself let alone other languages, SWIG only provides
 support for a subset of C++ features. Fortunately, this is now a rather
 large subset.</p>
<p> In part, the problem with C++ wrapping is that there is no
 semantically obvious (or automatic ) way to map many of its advanced
 features into other languages. As a simple example, consider the
 problem of wrapping C++ multiple inheritance to a target language with
 no such support. Similarly, the use of overloaded operators and
 overloaded functions can be problematic when no such capability exists
 in a target language.</p>
<p> A more subtle issue with C++ has to do with the way that some C++
 programmers think about programming libraries. In the world of SWIG,
 you are really trying to create binary-level software components for
 use in other languages. In order for this to work, a &quot;component&quot; has to
 contain real executable instructions and there has to be some kind of
 binary linking mechanism for accessing its functionality. In contrast,
 C++ has increasingly relied upon generic programming and templates for
 much of its functionality. Although templates are a powerful feature,
 they are largely orthogonal to the whole notion of binary components
 and libraries. For example, an STL <tt>vector</tt> does not define any
 kind of binary object for which SWIG can just create a wrapper. To
 further complicate matters, these libraries often utilize a lot of
 behind the scenes magic in which the semantics of seemingly basic
 operations (e.g., pointer dereferencing, procedure call, etc.) can be
 changed in dramatic and sometimes non-obvious ways. Although this
 &quot;magic&quot; may present few problems in a C++-only universe, it greatly
 complicates the problem of crossing language boundaries and provides
 many opportunities to shoot yourself in the foot. You will just have to
 be careful.</p>
<h2><a name="SWIGPlus_nn3">6.2 Approach</a></h2>
<p> To wrap C++, SWIG uses a layered approach to code generation. At the
 lowest level, SWIG generates a collection of procedural ISO C style
 wrappers. These wrappers take care of basic type conversion, type
 checking, error handling, and other low-level details of the C++
 binding. These wrappers are also sufficient to bind C++ into any target
 language that supports built-in procedures. In some sense, you might
 view this layer of wrapping as providing a C library interface to C++.
 On top of the low-level procedural (flattened) interface, SWIG
 generates proxy classes that provide a natural object-oriented (OO)
 interface to the underlying code. The proxy classes are typically
 written in the target language itself. For instance, in Python, a real
 Python class is used to provide a wrapper around the underlying C++
 object.</p>
<p> It is important to emphasize that SWIG takes a deliberately
 conservative and non-intrusive approach to C++ wrapping. SWIG does not
 encapsulate C++ classes inside a special C++ adaptor, it does not rely
 upon templates, nor does it add in additional C++ inheritance when
 generating wrappers. The last thing that most C++ programs need is even
 more compiler magic. Therefore, SWIG tries to maintain a very strict
 and clean separation between the implementation of your C++ application
 and the resulting wrapper code. You might say that SWIG has been
 written to follow the principle of least surprise--it does not play
 sneaky tricks with the C++ type system, it doesn't mess with your class
 hierarchies, and it doesn't introduce new semantics. Although this
 approach might not provide the most seamless integration with C++, it
 is safe, simple, portable, and debuggable.</p>
<p> Some of this chapter focuses on the low-level procedural interface
 to C++ that is used as the foundation for all language modules. Keep in
 mind that the target languages also provide the high-level OO interface
 via proxy classes. More detailed coverage can be found in the
 documentation for each target language.</p>
<h2><a name="SWIGPlus_nn4">6.3 Supported C++ features</a></h2>
<p> SWIG currently supports most C++ features including the following:</p>
<ul>
<li>Classes</li>
<li>Constructors and destructors</li>
<li>Virtual functions</li>
<li>Public inheritance (including multiple inheritance)</li>
<li>Static functions</li>
<li>Function and method overloading</li>
<li>Operator overloading for many standard operators</li>
<li>References</li>
<li>Templates (including specialization and member templates)</li>
<li>Pointers to members</li>
<li>Namespaces</li>
<li>Default parameters</li>
<li>Smart pointers</li>
</ul>
<p> The following C++ features are not currently supported:</p>
<ul>
<li>Overloaded versions of certain operators (new, delete, etc.)</li>
</ul>
<p> As a rule of thumb, SWIG should not be used on raw C++ source files,
 use header files only.</p>
<p> SWIG's C++ support is an ongoing project so some of these
 limitations may be lifted in future releases. However, we make no
 promises. Also, submitting a bug report is a very good way to get
 problems fixed (wink).</p>
<h2><a name="SWIGPlus_nn5">6.4 Command line options and compilation</a></h2>
<p> When wrapping C++ code, it is critical that SWIG be called with the
 `<tt>-c++</tt>' option. This changes the way a number of critical
 features such as memory management are handled. It also enables the
 recognition of C++ keywords. Without the <tt>-c++</tt> flag, SWIG will
 either issue a warning or a large number of syntax errors if it
 encounters C++ code in an interface file.</p>
<p> When compiling and linking the resulting wrapper file, it is normal
 to use the C++ compiler. For example:</p>
<div class="shell">
<pre>
$ swig -c++ -tcl example.i
$ c++ -fPIC -c example_wrap.cxx 
$ c++ example_wrap.o $(OBJS) -o example.so
</pre>
</div>
<p> Unfortunately, the process varies slightly on each platform. Make
 sure you refer to the documentation on each target language for further
 details. The SWIG Wiki also has further details.</p>
<b> Compatibility Note:</b> Early versions of SWIG generated just a
 flattened low-level C style API to C++ classes by default. The <tt>
-noproxy</tt> commandline option is recognised by many target languages
 and will generate just this interface as in earlier versions.
<h2><a name="SWIGPlus_nn38">6.5 Proxy classes</a></h2>
<p> In order to provide a natural mapping from C++ classes to the target
 language classes, SWIG's target languages mostly wrap C++ classes with
 special proxy classes. These proxy classes are typically implemented in
 the target language itself. For example, if you're building a Python
 module, each C++ class is wrapped by a Python proxy class. Or if you're
 building a Java module, each C++ class is wrapped by a Java proxy
 class.</p>
<h3><a name="SWIGPlus_nn39">6.5.1 Construction of proxy classes</a></h3>
<p> Proxy classes are always constructed as an extra layer of wrapping
 that uses low-level accessor functions. To illustrate, suppose you had
 a C++ class like this:</p>
<div class="code">
<pre>
class Foo {
  public:
    Foo();
    ~Foo();
    int  bar(int x);
    int  x;
};
</pre>
</div>
<p> Using C++ as pseudocode, a proxy class looks something like this:</p>
<div class="code">
<pre>
class FooProxy {
  private:
    Foo    *self;
  public:
    FooProxy() {
      self = new_Foo();
    }
    ~FooProxy() {
      delete_Foo(self);
    }
    int bar(int x) {
      return Foo_bar(self, x);
    }
    int x_get() {
      return Foo_x_get(self);
    }
    void x_set(int x) {
      Foo_x_set(self, x);
    }
};
</pre>
</div>
<p> Of course, always keep in mind that the real proxy class is written
 in the target language. For example, in Python, the proxy might look
 roughly like this:</p>
<div class="targetlang">
<pre>
class Foo:
    def __init__(self):
        self.this = new_Foo()
    def __del__(self):
        delete_Foo(self.this)
    def bar(self, x):
        return Foo_bar(self.this, x)
    def __getattr__(self, name):
        if name == 'x':
            return Foo_x_get(self.this)
        ...
    def __setattr__(self, name, value):
        if name == 'x':
            Foo_x_set(self.this, value)
        ...
</pre>
</div>
<p> Again, it's important to emphasize that the low-level accessor
 functions are always used by the proxy classes. Whenever possible,
 proxies try to take advantage of language features that are similar to
 C++. This might include operator overloading, exception handling, and
 other features.</p>
<h3><a name="SWIGPlus_nn40">6.5.2 Resource management in proxies</a></h3>
<p> A major issue with proxies concerns the memory management of wrapped
 objects. Consider the following C++ code:</p>
<div class="code">
<pre>
class Foo {
public:
  Foo();
  ~Foo();
  int bar(int x);
  int x;
};

class Spam {
public:
  Foo *value;
  ...
};
</pre>
</div>
<p> Consider some script code that uses these classes:</p>
<div class="targetlang">
<pre>
f = Foo()               # Creates a new Foo
s = Spam()              # Creates a new Spam
s.value = f             # Stores a reference to f inside s
g = s.value             # Returns stored reference
g = 4                   # Reassign g to some other value
del f                   # Destroy f 
</pre>
</div>
<p> Now, ponder the resulting memory management issues. When objects are
 created in the script, the objects are wrapped by newly created proxy
 classes. That is, there is both a new proxy class instance and a new
 instance of the underlying C++ class. In this example, both <tt>f</tt>
 and <tt>s</tt> are created in this way. However, the statement <tt>
s.value</tt> is rather curious---when executed, a pointer to <tt>f</tt>
 is stored inside another object. This means that the scripting proxy
 class<em> AND</em> another C++ class share a reference to the same
 object. To make matters even more interesting, consider the statement <tt>
g = s.value</tt>. When executed, this creates a new proxy class <tt>g</tt>
 that provides a wrapper around the C++ object stored in <tt>s.value</tt>
. In general, there is no way to know where this object came from---it
 could have been created by the script, but it could also have been
 generated internally. In this particular example, the assignment of <tt>
g</tt> results in a second proxy class for <tt>f</tt>. In other words, a
 reference to <tt>f</tt> is now shared by two proxy classes<em> and</em>
 a C++ class.</p>
<p> Finally, consider what happens when objects are destroyed. In the
 statement, <tt>g=4</tt>, the variable <tt>g</tt> is reassigned. In many
 languages, this makes the old value of <tt>g</tt> available for garbage
 collection. Therefore, this causes one of the proxy classes to be
 destroyed. Later on, the statement <tt>del f</tt> destroys the other
 proxy class. Of course, there is still a reference to the original
 object stored inside another C++ object. What happens to it? Is the
 object still valid?</p>
<p> To deal with memory management problems, proxy classes provide an
 API for controlling ownership. In C++ pseudocode, ownership control
 might look roughly like this:</p>
<div class="code">
<pre>
class FooProxy {
  public:
    Foo    *self;
    int     thisown;

    FooProxy() {
      self = new_Foo();
      thisown = 1;       // Newly created object
    }
    ~FooProxy() {
      if (thisown) delete_Foo(self);
    }
    ...
    // Ownership control API
    void disown() {
      thisown = 0;
    }
    void acquire() {
      thisown = 1;
    }
};

class FooPtrProxy: public FooProxy {
public:
  FooPtrProxy(Foo *s) {
    self = s;
    thisown = 0;
  }
};

class SpamProxy {
  ...
  FooProxy *value_get() {
    return FooPtrProxy(Spam_value_get(self));
  }
  void value_set(FooProxy *v) {
    Spam_value_set(self, v-&gt;self);
    v-&gt;disown();
  }
  ...
};
</pre>
</div>
<p> Looking at this code, there are a few central features:</p>
<ul>
<li>Each proxy class keeps an extra flag to indicate ownership. C++
 objects are only destroyed if the ownership flag is set.</li>
<li>When new objects are created in the target language, the ownership
 flag is set.</li>
<li>When a reference to an internal C++ object is returned, it is
 wrapped by a proxy class, but the proxy class does not have ownership.</li>
<li>In certain cases, ownership is adjusted. For instance, when a value
 is assigned to the member of a class, ownership is lost.</li>
<li>Manual ownership control is provided by special <tt>disown()</tt>
 and <tt>acquire()</tt> methods.</li>
</ul>
<p> Given the tricky nature of C++ memory management, it is impossible
 for proxy classes to automatically handle every possible memory
 management problem. However, proxies do provide a mechanism for manual
 control that can be used (if necessary) to address some of the more
 tricky memory management problems.</p>
<h3><a name="SWIGPlus_nn41">6.5.3 Language specific details</a></h3>
<p> Language specific details on proxy classes are contained in the
 chapters describing each target language. This chapter has merely
 introduced the topic in a very general way.</p>
<h2><a name="SWIGPlus_nn6">6.6 Simple C++ wrapping</a></h2>
<p> The following code shows a SWIG interface file for a simple C++
 class.</p>
<div class="code">
<pre>
%module list
%{
#include &quot;list.h&quot;
%}

// Very simple C++ example for linked list

class List {
public:
  List();
  ~List();
  int  search(char *value);
  void insert(char *);
  void remove(char *);
  char *get(int n);
  int  length;
static void print(List *l);
};
</pre>
</div>
<p> To generate wrappers for this class, SWIG first reduces the class to
 a collection of low-level C-style accessor functions which are then
 used by the proxy classes.</p>
<h3><a name="SWIGPlus_nn7">6.6.1 Constructors and destructors</a></h3>
<p> C++ constructors and destructors are translated into accessor
 functions such as the following :</p>
<div class="code">
<pre>
List * new_List(void) {
  return new List;
}
void delete_List(List *l) {
  delete l;
}

</pre>
</div>
<h3><a name="SWIGPlus_nn8">6.6.2 Default constructors, copy constructors
 and implicit destructors</a></h3>
<p> Following the C++ rules for implicit constructor and destructors,
 SWIG will automatically assume there is one even when they are not
 explicitly declared in the class interface.</p>
<p> In general then:</p>
<ul>
<li> If a C++ class does not declare any explicit constructor, SWIG will
 automatically generate a wrapper for one.</li>
<li> If a C++ class does not declare an explicit copy constructor, SWIG
 will automatically generate a wrapper for one if the <tt>%copyctor</tt>
 is used.</li>
<li> If a C++ class does not declare an explicit destructor, SWIG will
 automatically generate a wrapper for one.</li>
</ul>
<p> And as in C++, a few rules that alters the previous behavior:</p>
<ul>
<li>A default constructor is not created if a class already defines a
 constructor with arguments.</li>
<li>Default constructors are not generated for classes with pure virtual
 methods or for classes that inherit from an abstract class, but don't
 provide definitions for all of the pure methods.</li>
<li>A default constructor is not created unless all base classes support
 a default constructor.</li>
<li>Default constructors and implicit destructors are not created if a
 class defines them in a <tt>private</tt> or <tt>protected</tt> section.</li>
<li>Default constructors and implicit destructors are not created if any
 base class defines a non-public default constructor or destructor.</li>
</ul>
<p> SWIG should never generate a default constructor, copy constructor
 or default destructor wrapper for a class in which it is illegal to do
 so. In some cases, however, it could be necessary (if the complete
 class declaration is not visible from SWIG, and one of the above rules
 is violated) or desired (to reduce the size of the final interface) by
 manually disabling the implicit constructor/destructor generation.</p>
<p> To manually disable these, the <tt>%nodefaultctor</tt> and <tt>
%nodefaultdtor</tt> <a href="#Customization_feature_flags">feature flag</a>
 directives can be used. Note that these directives only affects the
 implicit generation, and they have no effect if the default/copy
 constructors or destructor are explicitly declared in the class
 interface.</p>
<p> For example:</p>
<div class="code">
<pre>
%nodefaultctor Foo;  // Disable the default constructor for class Foo.
class Foo {          // No default constructor is generated, unless one is declared
...
};
class Bar {          // A default constructor is generated, if possible
...
};
</pre>
</div>
<p> The directive <tt>%nodefaultctor</tt> can also be applied
 &quot;globally&quot;, as in:</p>
<div class="code">
<pre>
%nodefaultctor; // Disable creation of default constructors
class Foo {     // No default constructor is generated, unless one is declared
...
};
class Bar {   
public:
  Bar();        // The default constructor is generated, since one is declared
};
%clearnodefaultctor; // Enable the creation of default constructors again
</pre>
</div>
<p> The corresponding <tt>%nodefaultdtor</tt> directive can be used to
 disable the generation of the default or implicit destructor, if
 needed. Be aware, however, that this could lead to memory leaks in the
 target language. Hence, it is recommended to use this directive only in
 well known cases. For example:</p>
<div class="code">
<pre>
%nodefaultdtor Foo;   // Disable the implicit/default destructor for class Foo.
class Foo {           // No destructor is generated, unless one is declared
...
};
</pre>
</div>
<p><b> Compatibility Note:</b> The generation of default
 constructors/implicit destructors was made the default behavior in SWIG
 1.3.7. This may break certain older modules, but the old behavior can
 be easily restored using <tt>%nodefault</tt> or the <tt>-nodefault</tt>
 command line option. Furthermore, in order for SWIG to properly
 generate (or not generate) default constructors, it must be able to
 gather information from both the <tt>private</tt> and <tt>protected</tt>
 sections (specifically, it needs to know if a private or protected
 constructor/destructor is defined). In older versions of SWIG, it was
 fairly common to simply remove or comment out the private and protected
 sections of a class due to parser limitations. However, this removal
 may now cause SWIG to erroneously generate constructors for classes
 that define a constructor in those sections. Consider restoring those
 sections in the interface or using <tt>%nodefault</tt> to fix the
 problem.</p>
<p><b> Note:</b> The <tt>%nodefault</tt> directive/<tt>-nodefault</tt>
 options described above, which disable both the default constructor and
 the implicit destructors, could lead to memory leaks, and so it is
 strongly recommended to not use them.</p>
<h3><a name="SWIGPlus_nn9">6.6.3 When constructor wrappers aren't
 created</a></h3>
<p> If a class defines a constructor, SWIG normally tries to generate a
 wrapper for it. However, SWIG will not generate a constructor wrapper
 if it thinks that it will result in illegal wrapper code. There are
 really two cases where this might show up.</p>
<p> First, SWIG won't generate wrappers for protected or private
 constructors. For example:</p>
<div class="code">
<pre>
class Foo {
protected:
  Foo();         // Not wrapped.
public:
  ...
};
</pre>
</div>
<p> Next, SWIG won't generate wrappers for a class if it appears to be
 abstract--that is, it has undefined pure virtual methods. Here are some
 examples:</p>
<div class="code">
<pre>
class Bar {
public:
  Bar();               // Not wrapped.  Bar is abstract.
  virtual void spam(void) = 0;
};

class Grok : public Bar {
public:
  Grok();              // Not wrapped. No implementation of abstract spam().
};
</pre>
</div>
<p> Some users are surprised (or confused) to find missing constructor
 wrappers in their interfaces. In almost all cases, this is caused when
 classes are determined to be abstract. To see if this is the case, run
 SWIG with all of its warnings turned on:</p>
<div class="shell">
<pre>
% swig -Wall -python module.i
</pre>
</div>
<p> In this mode, SWIG will issue a warning for all abstract classes. It
 is possible to force a class to be non-abstract using this:</p>
<div class="code">
<pre>
%feature(&quot;notabstract&quot;) Foo;

class Foo : public Bar {
public:
  Foo();    // Generated no matter what---not abstract.
  ...
};
</pre>
</div>
<p> More information about <tt>%feature</tt> can be found in the <a href="#Customization">
Customization features</a> chapter.</p>
<h3><a name="SWIGPlus_nn10">6.6.4 Copy constructors</a></h3>
<p> If a class defines more than one constructor, its behavior depends
 on the capabilities of the target language. If overloading is
 supported, the copy constructor is accessible using the normal
 constructor function. For example, if you have this:</p>
<div class="code">
<pre>
class List {
public:
  List();    
  List(const List &amp;);      // Copy constructor
  ...
};
</pre>
</div>
<p> then the copy constructor can be used as follows:</p>
<div class="targetlang">
<pre>
x = List()               # Create a list
y = List(x)              # Copy list x
</pre>
</div>
<p> If the target language does not support overloading, then the copy
 constructor is available through a special function like this:</p>
<div class="code">
<pre>
List *copy_List(List *f) {
  return new List(*f);
}
</pre>
</div>
<p><b> Note:</b> For a class <tt>X</tt>, SWIG only treats a constructor
 as a copy constructor if it can be applied to an object of type <tt>X</tt>
 or <tt>X *</tt>. If more than one copy constructor is defined, only the
 first definition that appears is used as the copy constructor--other
 definitions will result in a name-clash. Constructors such as <tt>
X(const X &amp;)</tt>, <tt>X(X &amp;)</tt>, and <tt>X(X *)</tt> are handled as
 copy constructors in SWIG.</p>
<p><b> Note:</b> SWIG does<em> not</em> generate a copy constructor
 wrapper unless one is explicitly declared in the class. This differs
 from the treatment of default constructors and destructors. However,
 copy constructor wrappers can be generated if using the <tt>copyctor</tt>
 <a href="#Customization_feature_flags">feature flag</a>. For example:</p>
<div class="code">
<pre>
%copyctor List;

class List {
public:
  List();    
};
</pre>
</div>
<p> Will generate a copy constructor wrapper for <tt>List</tt>.</p>
<p><b> Compatibility note:</b> Special support for copy constructors was
 not added until SWIG-1.3.12. In previous versions, copy constructors
 could be wrapped, but they had to be renamed. For example:</p>
<div class="code">
<pre>
class Foo {
public:
  Foo();
  %name(CopyFoo) Foo(const Foo &amp;);
  ...
};
</pre>
</div>
<p> For backwards compatibility, SWIG does not perform any special
 copy-constructor handling if the constructor has been manually renamed.
 For instance, in the above example, the name of the constructor is set
 to <tt>new_CopyFoo()</tt>. This is the same as in older versions.</p>
<h3><a name="SWIGPlus_nn11">6.6.5 Member functions</a></h3>
<p> All member functions are roughly translated into accessor functions
 like this :</p>
<div class="code">
<pre>
int List_search(List *obj, char *value) {
  return obj-&gt;search(value);
}

</pre>
</div>
<p> This translation is the same even if the member function has been
 declared as <tt>virtual</tt>.</p>
<p> It should be noted that SWIG does not<em> actually</em> create a C
 accessor function in the code it generates. Instead, member access such
 as <tt>obj-&gt;search(value)</tt> is directly inlined into the generated
 wrapper functions. However, the name and calling convention of the
 low-level procedural wrappers match the accessor function prototype
 described above.</p>
<h3><a name="SWIGPlus_nn12">6.6.6 Static members</a></h3>
<p> Static member functions are called directly without making any
 special transformations. For example, the static member function <tt>
print(List *l)</tt> directly invokes <tt>List::print(List *l)</tt> in
 the generated wrapper code.</p>
<h3><a name="SWIGPlus_member_data">6.6.7 Member data</a></h3>
<p> Member data is handled in exactly the same manner as for C
 structures. A pair of accessor functions are effectively created. For
 example :</p>
<div class="code">
<pre>
int List_length_get(List *obj) {
  return obj-&gt;length;
}
int List_length_set(List *obj, int value) {
  obj-&gt;length = value;
  return value;
}

</pre>
</div>
<p> A read-only member can be created using the <tt>%immutable</tt> and <tt>
%mutable</tt> <a href="#Customization_feature_flags">feature flag</a>
 directive. For example, we probably wouldn't want the user to change
 the length of a list so we could do the following to make the value
 available, but read-only.</p>
<div class="code">
<pre>
class List {
public:
...
%immutable;
  int length;
%mutable;
...
};
</pre>
</div>
<p> Alternatively, you can specify an immutable member in advance like
 this:</p>
<div class="code">
<pre>
%immutable List::length;
...
class List {
  ...
  int length;         // Immutable by above directive
  ...
};
</pre>
</div>
<p> Similarly, all data attributes declared as <tt>const</tt> are
 wrapped as read-only members.</p>
<p> By default, SWIG uses the const reference typemaps for members that
 are primitive types. There are some subtle issues when wrapping data
 members that are not primitive types, such as classes. For instance, if
 you had another class like this,</p>
<div class="code">
<pre>
class Foo {
public:
  List items;
  ...
</pre>
</div>
<p> then the low-level accessor to the <tt>items</tt> member actually
 uses pointers. For example:</p>
<div class="code">
<pre>
List *Foo_items_get(Foo *self) {
  return &amp;self-&gt;items;
}
void Foo_items_set(Foo *self, List *value) {
  self-&gt;items = *value;
}
</pre>
</div>
<p> More information about this can be found in the SWIG Basics chapter,
 <a href="#SWIG_structure_data_members">Structure data members</a>
 section.</p>
<p> The wrapper code to generate the accessors for classes comes from
 the pointer typemaps. This can be somewhat unnatural for some types.
 For example, a user would expect the STL std::string class member
 variables to be wrapped as a string in the target language, rather than
 a pointer to this class. The const reference typemaps offer this type
 of marshalling, so there is a feature to tell SWIG to use the const
 reference typemaps rather than the pointer typemaps. It is the
 naturalvar feature and can be used to effectively change the way
 accessors are generated to the following:</p>
<div class="code">
<pre>
const List &amp;Foo_items_get(Foo *self) {
  return self-&gt;items;
}
void Foo_items_set(Foo *self, const List &amp;value) {
  self-&gt;items = value;
}
</pre>
</div>
<p> The <tt>%naturalvar</tt> directive is a macro for, and hence
 equivalent to, <tt>%feature(&quot;naturalvar&quot;)</tt>. It can be used as
 follows:</p>
<div class="code">
<pre>
// All List variables will use const List&amp; typemaps
%naturalvar List;

// Only Foo::myList will use const List&amp; typemaps
%naturalvar Foo::myList;
struct Foo {
  List myList;
};

// All non-primitive types will use const reference typemaps
%naturalvar;
</pre>
</div>
<p> The observant reader will notice that <tt>%naturalvar</tt> works
 like any other <a href="#Customization_feature_flags">feature flag</a>
 directive but with some extra flexibility. The first of the example
 usages above shows <tt>%naturalvar</tt> attaching to the <tt>myList</tt>
's variable type, that is the <tt>List</tt> class. The second usage
 shows <tt>%naturalvar</tt> attaching to the variable name. Hence the
 naturalvar feature can be used on either the variable's name or type.
 Note that using the naturalvar feature on a variable's name overrides
 any naturalvar feature attached to the variable's type.</p>
<p> It is generally a good idea to use this feature globally as the
 reference typemaps have extra NULL checking compared to the pointer
 typemaps. A pointer can be NULL, whereas a reference cannot, so the
 extra checking ensures that the target language user does not pass in a
 value that translates to a NULL pointer and thereby preventing any
 potential NULL pointer dereferences. The <tt>%naturalvar</tt> feature
 will apply to global variables in addition to member variables in some
 language modules, eg C# and Java.</p>
<p> The naturalvar behavior can also be turned on as a global setting
 via the <tt>-naturalvar</tt> commandline option or the module mode
 option, <tt>%module(naturalvar=1)</tt>. However, any use of <tt>
%feature(&quot;naturalvar&quot;)</tt> will override the global setting.</p>
<p><b> Compatibility note:</b> The <tt>%naturalvar</tt> feature was
 introduced in SWIG-1.3.28, prior to which it was necessary to manually
 apply the const reference typemaps, eg <tt>%apply const std::string &amp; {
 std::string * }</tt>, but this example would also apply the typemaps to
 methods taking a <tt>std::string</tt> pointer.</p>
<p><b> Compatibility note:</b> Read-only access used to be controlled by
 a pair of directives <tt>%readonly</tt> and <tt>%readwrite</tt>.
 Although these directives still work, they generate a warning message.
 Simply change the directives to <tt>%immutable;</tt> and <tt>%mutable;</tt>
 to silence the warning. Don't forget the extra semicolon!</p>
<p><b> Compatibility note:</b> Prior to SWIG-1.3.12, all members of
 unknown type were wrapped into accessor functions using pointers. For
 example, if you had a structure like this</p>
<div class="code">
<pre>
struct Foo {
  size_t  len;
};
</pre>
</div>
<p> and nothing was known about <tt>size_t</tt>, then accessors would be
 written to work with <tt>size_t *</tt>. Starting in SWIG-1.3.12, this
 behavior has been modified. Specifically, pointers will<em> only</em>
 be used if SWIG knows that a datatype corresponds to a structure or
 class. Therefore, the above code would be wrapped into accessors
 involving <tt>size_t</tt>. This change is subtle, but it smooths over a
 few problems related to structure wrapping and some of SWIG's
 customization features.</p>
<h2><a name="SWIGPlus_nn15">6.7 Protection</a></h2>
<p> SWIG wraps class members that are public following the C++
 conventions, i.e., by explicit public declaration or by the use of the <tt>
using</tt> directive. In general, anything specified in a private or
 protected section will be ignored, although the internal code generator
 sometimes looks at the contents of the private and protected sections
 so that it can properly generate code for default constructors and
 destructors. Directors could also modify the way non-public virtual
 protected members are treated.</p>
<p> By default, members of a class definition are assumed to be private
 until you explicitly give a `<tt>public:</tt>' declaration (This is the
 same convention used by C++).</p>
<h2><a name="SWIGPlus_nn16">6.8 Enums and constants</a></h2>
<p> Enumerations and constants are handled differently by the different
 language modules and are described in detail in the appropriate
 language chapter. However, many languages map enums and constants in a
 class definition into constants with the classname as a prefix. For
 example :</p>
<div class="code">
<pre>
class Swig {
public:
  enum {ALE, LAGER, PORTER, STOUT};
};

</pre>
</div>
<p> Generates the following set of constants in the target scripting
 language :</p>
<div class="targetlang">
<pre>
Swig_ALE = Swig::ALE
Swig_LAGER = Swig::LAGER
Swig_PORTER = Swig::PORTER
Swig_STOUT = Swig::STOUT

</pre>
</div>
<p> Members declared as <tt>const</tt> are wrapped as read-only members
 and do not create constants.</p>
<h2><a name="SWIGPlus_nn17">6.9 Friends</a></h2>
<p> Friend declarations are recognised by SWIG. For example, if you have
 this code:</p>
<div class="code">
<pre>
class Foo {
public:
  ...
  friend void blah(Foo *f);
  ...
};
</pre>
</div>
<p> then the <tt>friend</tt> declaration does result in a wrapper code
 equivalent to one generated for the following declaration</p>
<div class="code">
<pre>
class Foo {
public:
  ...
};

void blah(Foo *f);    
</pre>
</div>
<p> A friend declaration, as in C++, is understood to be in the same
 scope where the class is declared, hence, you can have</p>
<div class="code">
<pre>

%ignore bar::blah(Foo *f);

namespace bar {

  class Foo {
  public:
    ...
    friend void blah(Foo *f);
    ...
  };
}
</pre>
</div>
<p> and a wrapper for the method 'blah' will not be generated.</p>
<h2><a name="SWIGPlus_nn18">6.10 References and pointers</a></h2>
<p> C++ references are supported, but SWIG transforms them back into
 pointers. For example, a declaration like this :</p>
<div class="code">
<pre>
class Foo {
public:
  double bar(double &amp;a);
}
</pre>
</div>
<p> has a low-level accessor</p>
<div class="code">
<pre>
double Foo_bar(Foo *obj, double *a) {
  obj-&gt;bar(*a);
}
</pre>
</div>
<p> As a special case, most language modules pass <tt>const</tt>
 references to primitive datatypes (<tt>int</tt>, <tt>short</tt>, <tt>
float</tt>, etc.) by value instead of pointers. For example, if you have
 a function like this,</p>
<div class="code">
<pre>
void foo(const int &amp;x);
</pre>
</div>
<p> it is called from a script as follows:</p>
<div class="targetlang">
<pre>
foo(3)              # Notice pass by value
</pre>
</div>
<p> Functions that return a reference are remapped to return a pointer
 instead. For example:</p>
<div class="code">
<pre>
class Bar {
public:
  Foo &amp;spam();
};
</pre>
</div>
<p> Generates an accessor like this:</p>
<div class="code">
<pre>
Foo *Bar_spam(Bar *obj) {
  Foo &amp;result = obj-&gt;spam();
  return &amp;result;
}
</pre>
</div>
<p> However, functions that return <tt>const</tt> references to
 primitive datatypes (<tt>int</tt>, <tt>short</tt>, etc.) normally
 return the result as a value rather than a pointer. For example, a
 function like this,</p>
<div class="code">
<pre>
const int &amp;bar();
</pre>
</div>
<p> will return integers such as 37 or 42 in the target scripting
 language rather than a pointer to an integer.</p>
<p> Don't return references to objects allocated as local variables on
 the stack. SWIG doesn't make a copy of the objects so this will
 probably cause your program to crash.</p>
<p><b> Note:</b> The special treatment for references to primitive
 datatypes is necessary to provide more seamless integration with more
 advanced C++ wrapping applications---especially related to templates
 and the STL. This was first added in SWIG-1.3.12.</p>
<h2><a name="SWIGPlus_nn19">6.11 Pass and return by value</a></h2>
<p> Occasionally, a C++ program will pass and return class objects by
 value. For example, a function like this might appear:</p>
<div class="code">
<pre>
Vector cross_product(Vector a, Vector b);
</pre>
</div>
<p> If no information is supplied about <tt>Vector</tt>, SWIG creates a
 wrapper function similar to the following:</p>
<div class="code">
<pre>
Vector *wrap_cross_product(Vector *a, Vector *b) {
  Vector x = *a;
  Vector y = *b;
  Vector r = cross_product(x, y);
  return new Vector(r);
}</pre>
</div>
<p> In order for the wrapper code to compile, <tt>Vector</tt> must
 define a copy constructor and a default constructor.</p>
<p> If <tt>Vector</tt> is defined as a class in the interface, but it
 does not support a default constructor, SWIG changes the wrapper code
 by encapsulating the arguments inside a special C++ template wrapper
 class, through a process called the &quot;Fulton Transform&quot;. This produces a
 wrapper that looks like this:</p>
<div class="code">
<pre>
Vector cross_product(Vector *a, Vector *b) {
  SwigValueWrapper&lt;Vector&gt; x = *a;
  SwigValueWrapper&lt;Vector&gt; y = *b;
  SwigValueWrapper&lt;Vector&gt; r = cross_product(x, y);
  return new Vector(r);
}
</pre>
</div>
<p> This transformation is a little sneaky, but it provides support for
 pass-by-value even when a class does not provide a default constructor
 and it makes it possible to properly support a number of SWIG's
 customization options. The definition of <tt>SwigValueWrapper</tt> can
 be found by reading the SWIG wrapper code. This class is really nothing
 more than a thin wrapper around a pointer.</p>
<p> Although SWIG usually detects the classes to which the Fulton
 Transform should be applied, in some situations it's necessary to
 override it. That's done with <tt>%feature(&quot;valuewrapper&quot;)</tt> to
 ensure it is used and <tt>%feature(&quot;novaluewrapper&quot;)</tt> to ensure it
 is not used:</p>
<div class="code">
<pre>
%feature(&quot;novaluewrapper&quot;) A;    
class A;

%feature(&quot;valuewrapper&quot;) B;
struct B { 
  B();
  // ....
};   
</pre>
</div>
<p> It is well worth considering turning this feature on for classes
 that do have a default constructor. It will remove a redundant
 constructor call at the point of the variable declaration in the
 wrapper, so will generate notably better performance for large objects
 or for classes with expensive construction. Alternatively consider
 returning a reference or a pointer.</p>
<p><b> Note:</b> this transformation has no effect on typemaps or any
 other part of SWIG---it should be transparent except that you may see
 this code when reading the SWIG output file.</p>
<p><b> Note:</b> This template transformation is new in SWIG-1.3.11 and
 may be refined in future SWIG releases. In practice, it is only
 absolutely necessary to do this for classes that don't define a default
 constructor.</p>
<p><b> Note:</b> The use of this template only occurs when objects are
 passed or returned by value. It is not used for C++ pointers or
 references.</p>
<h2><a name="SWIGPlus_nn20">6.12 Inheritance</a></h2>
<p> SWIG supports C++ inheritance of classes and allows both single and
 multiple inheritance, as limited or allowed by the target language. The
 SWIG type-checker knows about the relationship between base and derived
 classes and allows pointers to any object of a derived class to be used
 in functions of a base class. The type-checker properly casts pointer
 values and is safe to use with multiple inheritance.</p>
<p> SWIG treats private or protected inheritance as close to the C++
 spirit, and target language capabilities, as possible. In most cases,
 this means that SWIG will parse the non-public inheritance
 declarations, but that will have no effect in the generated code,
 besides the implicit policies derived for constructors and destructors.</p>
<p> The following example shows how SWIG handles inheritance. For
 clarity, the full C++ code has been omitted.</p>
<div class="code">
<pre>
// shapes.i
%module shapes
%{
#include &quot;shapes.h&quot;
%}

class Shape {
public:
  double x, y;
  virtual double area() = 0;
  virtual double perimeter() = 0;
  void    set_location(double x, double y);
};
class Circle : public Shape {
public:
  Circle(double radius);
  ~Circle();
  double area();
  double perimeter();
};
class Square : public Shape {
public:
  Square(double size);
  ~Square();
  double area();
  double perimeter();
}
</pre>
</div>
<p> When wrapped into Python, we can perform the following operations
 (shown using the low level Python accessors):</p>
<div class="targetlang">
<pre>
$ python
&gt;&gt;&gt; import shapes
&gt;&gt;&gt; circle = shapes.new_Circle(7)
&gt;&gt;&gt; square = shapes.new_Square(10)
&gt;&gt;&gt; print shapes.Circle_area(circle)
153.93804004599999757
&gt;&gt;&gt; print shapes.Shape_area(circle)
153.93804004599999757
&gt;&gt;&gt; print shapes.Shape_area(square)
100.00000000000000000
&gt;&gt;&gt; shapes.Shape_set_location(square, 2, -3)
&gt;&gt;&gt; print shapes.Shape_perimeter(square)
40.00000000000000000
&gt;&gt;&gt;
</pre>
</div>
<p> In this example, Circle and Square objects have been created. Member
 functions can be invoked on each object by making calls to <tt>
Circle_area</tt>, <tt>Square_area</tt>, and so on. However, the same
 results can be accomplished by simply using the <tt>Shape_area</tt>
 function on either object.</p>
<p> One important point concerning inheritance is that the low-level
 accessor functions are only generated for classes in which they are
 actually declared. For instance, in the above example, the method <tt>
set_location()</tt> is only accessible as <tt>Shape_set_location()</tt>
 and not as <tt>Circle_set_location()</tt> or <tt>Square_set_location()</tt>
. Of course, the <tt>Shape_set_location()</tt> function will accept any
 kind of object derived from Shape. Similarly, accessor functions for
 the attributes <tt>x</tt> and <tt>y</tt> are generated as <tt>
Shape_x_get()</tt>, <tt>Shape_x_set()</tt>, <tt>Shape_y_get()</tt>, and <tt>
Shape_y_set()</tt>. Functions such as <tt>Circle_x_get()</tt> are not
 available--instead you should use <tt>Shape_x_get()</tt>.</p>
<p> Note that there is a one to one correlation between the low-level
 accessor functions and the proxy methods and therefore there is also a
 one to one correlation between the C++ class methods and the generated
 proxy class methods.</p>
<p><b> Note:</b> For the best results, SWIG requires all base classes to
 be defined in an interface. Otherwise, you may get a warning message
 like this:</p>
<div class="shell">
<pre>
example.i:18: Warning 401: Nothing known about base class 'Foo'. Ignored.
</pre>
</div>
<p> If any base class is undefined, SWIG still generates correct type
 relationships. For instance, a function accepting a <tt>Foo *</tt> will
 accept any object derived from <tt>Foo</tt> regardless of whether or
 not SWIG actually wrapped the <tt>Foo</tt> class. If you really don't
 want to generate wrappers for the base class, but you want to silence
 the warning, you might consider using the <tt>%import</tt> directive to
 include the file that defines <tt>Foo</tt>. <tt>%import</tt> simply
 gathers type information, but doesn't generate wrappers. Alternatively,
 you could just define <tt>Foo</tt> as an empty class in the SWIG
 interface or use <a href="#Warnings_suppression">warning suppression</a>
.</p>
<p><b> Note:</b> <tt>typedef</tt>-names<em> can</em> be used as base
 classes. For example:</p>
<div class="code">
<pre>
class Foo {
...
};

typedef Foo FooObj;
class Bar : public FooObj {     // Ok.  Base class is Foo
...
};
</pre>
</div>
<p> Similarly, <tt>typedef</tt> allows unnamed structures to be used as
 base classes. For example:</p>
<div class="code">
<pre>
typedef struct {
  ...
} Foo;

class Bar : public Foo {    // Ok. 
...
};
</pre>
</div>
<p><b> Compatibility Note:</b> Starting in version 1.3.7, SWIG only
 generates low-level accessor wrappers for the declarations that are
 actually defined in each class. This differs from SWIG1.1 which used to
 inherit all of the declarations defined in base classes and regenerate
 specialized accessor functions such as <tt>Circle_x_get()</tt>, <tt>
Square_x_get()</tt>, <tt>Circle_set_location()</tt>, and <tt>
Square_set_location()</tt>. This behavior resulted in huge amounts of
 replicated code for large class hierarchies and made it awkward to
 build applications spread across multiple modules (since accessor
 functions are duplicated in every single module). It is also
 unnecessary to have such wrappers when advanced features like proxy
 classes are used.<b> Note:</b> Further optimizations are enabled when
 using the <tt>-fvirtual</tt> option, which avoids the regenerating of
 wrapper functions for virtual members that are already defined in a
 base class.</p>
<h2><a name="SWIGPlus_nn21">6.13 A brief discussion of multiple
 inheritance, pointers, and type checking</a></h2>
<p> When a target scripting language refers to a C++ object, it normally
 uses a tagged pointer object that contains both the value of the
 pointer and a type string. For example, in Tcl, a C++ pointer might be
 encoded as a string like this:</p>
<div class="diagram">
<pre>
_808fea88_p_Circle
</pre>
</div>
<p> A somewhat common question is whether or not the type-tag could be
 safely removed from the pointer. For instance, to get better
 performance, could you strip all type tags and just use simple integers
 instead?</p>
<p> In general, the answer to this question is no. In the wrappers, all
 pointers are converted into a common data representation in the target
 language. Typically this is the equivalent of casting a pointer to <tt>
void *</tt>. This means that any C++ type information associated with
 the pointer is lost in the conversion.</p>
<p> The problem with losing type information is that it is needed to
 properly support many advanced C++ features--especially multiple
 inheritance. For example, suppose you had code like this:</p>
<div class="code">
<pre>
class A {
public:
  int x;
};

class B {
public:
  int y;
};

class C : public A, public B {
};

int A_function(A *a) {
  return a-&gt;x;
}

int B_function(B *b) {
  return b-&gt;y;
}
</pre>
</div>
<p> Now, consider the following code that uses <tt>void *</tt>.</p>
<div class="code">
<pre>
C *c = new C();
void *p = (void *) c;
...
int x = A_function((A *) p);
int y = B_function((B *) p);
</pre>
</div>
<p> In this code, both <tt>A_function()</tt> and <tt>B_function()</tt>
 may legally accept an object of type <tt>C *</tt> (via inheritance).
 However, one of the functions will always return the wrong result when
 used as shown. The reason for this is that even though <tt>p</tt>
 points to an object of type <tt>C</tt>, the casting operation doesn't
 work like you would expect. Internally, this has to do with the data
 representation of <tt>C</tt>. With multiple inheritance, the data from
 each base class is stacked together. For example:</p>
<div class="diagram">
<pre>
             ------------    &lt;--- (C *),  (A *)
            |     A      |
            |------------|   &lt;--- (B *)
            |     B      |
             ------------   
</pre>
</div>
<p> Because of this stacking, a pointer of type <tt>C *</tt> may change
 value when it is converted to a <tt>A *</tt> or <tt>B *</tt>. However,
 this adjustment does<em> not</em> occur if you are converting from a <tt>
void *</tt>.</p>
<p> The use of type tags marks all pointers with the real type of the
 underlying object. This extra information is then used by SWIG
 generated wrappers to correctly cast pointer values under inheritance
 (avoiding the above problem).</p>
<p> Some of the language modules are able to solve the problem by
 storing multiple instances of the pointer, for example, <tt>A *</tt>,
 in the A proxy class as well as <tt>C *</tt> in the C proxy class. The
 correct cast can then be made by choosing the correct <tt>void *</tt>
 pointer to use and is guaranteed to work as the cast to a void pointer
 and back to the same type does not lose any type information:</p>
<div class="code">
<pre>
C *c = new C();
void *p = (void *) c;
void *pA = (void *) c;
void *pB = (void *) c;
...
int x = A_function((A *) pA);
int y = B_function((B *) pB);
</pre>
</div>
<p> In practice, the pointer is held as an integral number in the target
 language proxy class.</p>
<h2><a name="SWIGPlus_default_args">6.14 Default arguments</a></h2>
<p> SWIG will wrap all types of functions that have default arguments.
 For example member functions:</p>
<div class="code">
<pre>
class Foo {
public:
  void bar(int x, int y = 3, int z = 4);
};
</pre>
</div>
<p> SWIG handles default arguments by generating an extra overloaded
 method for each defaulted argument. SWIG is effectively handling
 methods with default arguments as if it was wrapping the equivalent
 overloaded methods. Thus for the example above, it is as if we had
 instead given the following to SWIG:</p>
<div class="code">
<pre>
class Foo {
public:
  void bar(int x, int y, int z);
  void bar(int x, int y);
  void bar(int x);
};
</pre>
</div>
<p> The wrappers produced are exactly the same as if the above code was
 instead fed into SWIG. Details of this are covered in the next section <a
href="#SWIGPlus_overloaded_methods">Overloaded functions and methods</a>
. This approach allows SWIG to wrap all possible default arguments, but
 can be verbose. For example if a method has ten default arguments, then
 eleven wrapper methods are generated.</p>
<p> Please see the <a href="#Customization_features_default_args">
Features and default arguments</a> section for more information on using
 <tt>%feature</tt> with functions with default arguments. The <a href="#SWIGPlus_ambiguity_resolution_renaming">
Renaming and ambiguity resolution</a> section also deals with using <tt>
%rename</tt> and <tt>%ignore</tt> on methods with default arguments. If
 you are writing your own typemaps for types used in methods with
 default arguments, you may also need to write a <tt>typecheck</tt>
 typemap. See the <a href="#Typemaps_overloading">Typemaps and
 overloading</a> section for details or otherwise use the <tt>
compactdefaultargs</tt> feature flag as mentioned below.</p>
<p><b> Compatibility note:</b> Versions of SWIG prior to SWIG-1.3.23
 wrapped default arguments slightly differently. Instead a single
 wrapper method was generated and the default values were copied into
 the C++ wrappers so that the method being wrapped was then called with
 all the arguments specified. If the size of the wrappers are a concern
 then this approach to wrapping methods with default arguments can be
 re-activated by using the <tt>compactdefaultargs</tt> <a href="#Customization_feature_flags">
feature flag</a>.</p>
<div class="code">
<pre>
%feature(&quot;compactdefaultargs&quot;) Foo::bar;
class Foo {
public:
  void bar(int x, int y = 3, int z = 4);
};
</pre>
</div>
<p> This is great for reducing the size of the wrappers, but the caveat
 is it does not work for the statically typed languages, such as C# and
 Java, which don't have optional arguments in the language, Another
 restriction of this feature is that it cannot handle default arguments
 that are not public. The following example illustrates this:</p>
<div class="code">
<pre>
class Foo {
private:
  static const int spam;
public:
  void bar(int x, int y = spam);   // Won't work with %feature(&quot;compactdefaultargs&quot;) -
                                   // private default value
};
</pre>
</div>
<p> This produces uncompilable wrapper code because default values in
 C++ are evaluated in the same scope as the member function whereas SWIG
 evaluates them in the scope of a wrapper function (meaning that the
 values have to be public).</p>
<p> The <tt>compactdefaultargs</tt> feature is automatically turned on
 when wrapping <a href="#SWIG_default_args">C code with default
 arguments</a>. Some target languages will also automatically turn on
 this feature if the keyword arguments feature (kwargs) is specified for
 either C or C++ functions, and the target language supports kwargs, the
 <tt>compactdefaultargs</tt> feature is also automatically turned on.
 Keyword arguments are a language feature of some scripting languages,
 for example Ruby and Python. SWIG is unable to support kwargs when
 wrapping overloaded methods, so the default approach cannot be used.</p>
<h2><a name="SWIGPlus_overloaded_methods">6.15 Overloaded functions and
 methods</a></h2>
<p> In many language modules, SWIG provides partial support for
 overloaded functions, methods, and constructors. For example, if you
 supply SWIG with overloaded functions like this:</p>
<div class="code">
<pre>
void foo(int x) {
  printf(&quot;x is %d\n&quot;, x);
}
void foo(char *x) {
  printf(&quot;x is '%s'\n&quot;, x);
}
</pre>
</div>
<p> The function is used in a completely natural way. For example:</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; foo(3)
x is 3
&gt;&gt;&gt; foo(&quot;hello&quot;)
x is 'hello'
&gt;&gt;&gt;
</pre>
</div>
<p> Overloading works in a similar manner for methods and constructors.
 For example if you have this code,</p>
<div class="code">
<pre>
class Foo {
public:
  Foo();
  Foo(const Foo &amp;);   // Copy constructor
  void bar(int x);
  void bar(char *s, int y);
};
</pre>
</div>
<p> it might be used like this</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; f = Foo()          # Create a Foo
&gt;&gt;&gt; f.bar(3)
&gt;&gt;&gt; g = Foo(f)         # Copy Foo
&gt;&gt;&gt; f.bar(&quot;hello&quot;, 2)
</pre>
</div>
<h3><a name="SWIGPlus_nn24">6.15.1 Dispatch function generation</a></h3>
<p> The implementation of overloaded functions and methods is somewhat
 complicated due to the dynamic nature of scripting languages. Unlike
 C++, which binds overloaded methods at compile time, SWIG must
 determine the proper function as a runtime check for scripting language
 targets. This check is further complicated by the typeless nature of
 certain scripting languages. For instance, in Tcl, all types are simply
 strings. Therefore, if you have two overloaded functions like this,</p>
<div class="code">
<pre>
void foo(char *x);
void foo(int x);
</pre>
</div>
<p> the order in which the arguments are checked plays a rather critical
 role.</p>
<p> For statically typed languages, SWIG uses the language's method
 overloading mechanism. To implement overloading for the scripting
 languages, SWIG generates a dispatch function that checks the number of
 passed arguments and their types. To create this function, SWIG first
 examines all of the overloaded methods and ranks them according to the
 following rules:</p>
<ol>
<li><b>Number of required arguments.</b> Methods are sorted by
 increasing number of required arguments.</li>
<li>
<p><b>Argument type precedence.</b> All C++ datatypes are assigned a
 numeric type precedence value (which is determined by the language
 module).</p>
<div class="diagram">
<pre>
Type              Precedence
----------------  ----------
TYPE *            0     (High)
void *            20
Integers          40
Floating point    60
char              80
Strings           100   (Low)
</pre>
</div>
<p> Using these precedence values, overloaded methods with the same
 number of required arguments are sorted in increased order of
 precedence values.</p>
</li>
</ol>
<p> This may sound very confusing, but an example will help. Consider
 the following collection of overloaded methods:</p>
<div class="code">
<pre>
void foo(double);
void foo(int);
void foo(Bar *);
void foo();
void foo(int x, int y, int z, int w);
void foo(int x, int y, int z = 3);
void foo(double x, double y);
void foo(double x, Bar *z);
</pre>
</div>
<p> The first rule simply ranks the functions by required argument
 count. This would produce the following list:</p>
<div class="diagram">
<pre>
rank
-----
[0]   foo()
[1]   foo(double);
[2]   foo(int);
[3]   foo(Bar *);
[4]   foo(int x, int y, int z = 3);
[5]   foo(double x, double y)
[6]   foo(double x, Bar *z)
[7]   foo(int x, int y, int z, int w);
</pre>
</div>
<p> The second rule, simply refines the ranking by looking at argument
 type precedence values.</p>
<div class="diagram">
<pre>
rank
-----
[0]   foo()
[1]   foo(Bar *);
[2]   foo(int);
[3]   foo(double);
[4]   foo(int x, int y, int z = 3);
[5]   foo(double x, Bar *z)
[6]   foo(double x, double y)
[7]   foo(int x, int y, int z, int w);
</pre>
</div>
<p> Finally, to generate the dispatch function, the arguments passed to
 an overloaded method are simply checked in the same order as they
 appear in this ranking.</p>
<p> If you're still confused, don't worry about it---SWIG is probably
 doing the right thing.</p>
<h3><a name="SWIGPlus_nn25">6.15.2 Ambiguity in overloading</a></h3>
<p> Regrettably, SWIG is not able to support every possible use of valid
 C++ overloading. Consider the following example:</p>
<div class="code">
<pre>
void foo(int x);
void foo(long x);
</pre>
</div>
<p> In C++, this is perfectly legal. However, in a scripting language,
 there is generally only one kind of integer object. Therefore, which
 one of these functions do you pick? Clearly, there is no way to truly
 make a distinction just by looking at the value of the integer itself (<tt>
int</tt> and <tt>long</tt> may even be the same precision). Therefore,
 when SWIG encounters this situation, it may generate a warning message
 like this for scripting languages:</p>
<div class="shell">
<pre>
example.i:4: Warning 509: Overloaded method foo(long) effectively ignored,
example.i:3: Warning 509: as it is shadowed by foo(int).
</pre>
</div>
<p> or for statically typed languages like Java:</p>
<div class="shell">
<pre>
example.i:4: Warning 516: Overloaded method foo(long) ignored,
example.i:3: Warning 516: using foo(int) instead.
at example.i:3 used.
</pre>
</div>
<p> This means that the second overloaded function will be inaccessible
 from a scripting interface or the method won't be wrapped at all. This
 is done as SWIG does not know how to disambiguate it from an earlier
 method.</p>
<p> Ambiguity problems are known to arise in the following situations:</p>
<ul>
<li>Integer conversions. Datatypes such as <tt>int</tt>, <tt>long</tt>,
 and <tt>short</tt> cannot be disambiguated in some languages. Shown
 above.</li>
<li>Floating point conversion. <tt>float</tt> and <tt>double</tt> can
 not be disambiguated in some languages.</li>
<li>Pointers and references. For example, <tt>Foo *</tt> and <tt>Foo &amp;</tt>
.</li>
<li>Pointers and arrays. For example, <tt>Foo *</tt> and <tt>Foo [4]</tt>
.</li>
<li>Pointers and instances. For example, <tt>Foo</tt> and <tt>Foo *</tt>
. Note: SWIG converts all instances to pointers.</li>
<li>Qualifiers. For example, <tt>const Foo *</tt> and <tt>Foo *</tt>.</li>
<li>Default vs. non default arguments. For example, <tt>foo(int a, int
 b)</tt> and <tt>foo(int a, int b = 3)</tt>.</li>
</ul>
<p> When an ambiguity arises, methods are checked in the same order as
 they appear in the interface file. Therefore, earlier methods will
 shadow methods that appear later.</p>
<p> When wrapping an overloaded function, there is a chance that you
 will get a warning message like this:</p>
<div class="shell">
<pre>
example.i:3: Warning 467: Overloaded foo(int) not supported (incomplete type checking rule - 
no precedence level in typecheck typemap for 'int').
</pre>
</div>
<p> This error means that the target language module supports
 overloading, but for some reason there is no type-checking rule that
 can be used to generate a working dispatch function. The resulting
 behavior is then undefined. You should report this as a bug to the <a href="http://www.swig.org/bugs.html">
SWIG bug tracking database</a> if this is due to one of the typemaps
 supplied with SWIG.</p>
<p> If you get an error message such as the following,</p>
<div class="shell">
<pre>
foo.i:6. Overloaded declaration ignored.  Spam::foo(double )
foo.i:5. Previous declaration is Spam::foo(int )
foo.i:7. Overloaded declaration ignored.  Spam::foo(Bar *, Spam *, int )
foo.i:5. Previous declaration is Spam::foo(int )
</pre>
</div>
<p> it means that the target language module has not yet implemented
 support for overloaded functions and methods. The only way to fix the
 problem is to read the next section.</p>
<h3><a name="SWIGPlus_ambiguity_resolution_renaming">6.15.3 Renaming and
 ambiguity resolution</a></h3>
<p> If an ambiguity in overload resolution occurs or if a module doesn't
 allow overloading, there are a few strategies for dealing with the
 problem. First, you can tell SWIG to ignore one of the methods. This is
 easy---simply use the <tt>%ignore</tt> directive. For example:</p>
<div class="code">
<pre>
%ignore foo(long);

void foo(int);
void foo(long);       // Ignored.  Oh well.
</pre>
</div>
<p> The other alternative is to rename one of the methods. This can be
 done using <tt>%rename</tt>. For example:</p>
<div class="code">
<pre>
%rename(&quot;foo_short&quot;) foo(short);
%rename(foo_long) foo(long);

void foo(int);
void foo(short);      // Accessed as foo_short()
void foo(long);       // Accessed as foo_long()
</pre>
</div>
<p> Note that the quotes around the new name are optional, however,
 should the new name be a C/C++ keyword they would be essential in order
 to avoid a parsing error. The <tt>%ignore</tt> and <tt>%rename</tt>
 directives are both rather powerful in their ability to match
 declarations. When used in their simple form, they apply to both global
 functions and methods. For example:</p>
<div class="code">
<pre>
/* Forward renaming declarations */
%rename(foo_i) foo(int); 
%rename(foo_d) foo(double);
...
void foo(int);           // Becomes 'foo_i'
void foo(char *c);       // Stays 'foo' (not renamed)

class Spam {
public:
  void foo(int);      // Becomes 'foo_i'
  void foo(double);   // Becomes 'foo_d'
  ...
};
</pre>
</div>
<p> If you only want the renaming to apply to a certain scope, the C++
 scope resolution operator (::) can be used. For example:</p>
<div class="code">
<pre>
%rename(foo_i) ::foo(int);      // Only rename foo(int) in the global scope.
                                // (will not rename class members)

%rename(foo_i) Spam::foo(int);  // Only rename foo(int) in class Spam
</pre>
</div>
<p> When a renaming operator is applied to a class as in <tt>
Spam::foo(int)</tt>, it is applied to that class and all derived
 classes. This can be used to apply a consistent renaming across an
 entire class hierarchy with only a few declarations. For example:</p>
<div class="code">
<pre>
%rename(foo_i) Spam::foo(int);
%rename(foo_d) Spam::foo(double);

class Spam {
public:
  virtual void foo(int);      // Renamed to foo_i
  virtual void foo(double);   // Renamed to foo_d
  ...
};

class Bar : public Spam {
public:
  virtual void foo(int);      // Renamed to foo_i
  virtual void foo(double);   // Renamed to foo_d
  ...
};

class Grok : public Bar {
public:
  virtual void foo(int);      // Renamed to foo_i
  virtual void foo(double);   // Renamed to foo_d
  ...
};
</pre>
</div>
<p> It is also possible to include <tt>%rename</tt> specifications in
 the class definition itself. For example:</p>
<div class="code">
<pre>
class Spam {
  %rename(foo_i) foo(int);
  %rename(foo_d) foo(double);
public:
  virtual void foo(int);      // Renamed to foo_i
  virtual void foo(double);   // Renamed to foo_d
  ...
};

class Bar : public Spam {
public:
  virtual void foo(int);      // Renamed to foo_i
  virtual void foo(double);   // Renamed to foo_d
...
};
</pre>
</div>
<p> In this case, the <tt>%rename</tt> directives still get applied
 across the entire inheritance hierarchy, but it's no longer necessary
 to explicitly specify the class prefix <tt>Spam::</tt>.</p>
<p> A special form of <tt>%rename</tt> can be used to apply a renaming
 just to class members (of all classes):</p>
<div class="code">
<pre>
%rename(foo_i) *::foo(int);   // Only rename foo(int) if it appears in a class.
</pre>
</div>
<p> Note: the <tt>*::</tt> syntax is non-standard C++, but the '*' is
 meant to be a wildcard that matches any class name (we couldn't think
 of a better alternative so if you have a better idea, send email to the
 <a href="http://www.swig.org/mail.html">swig-devel mailing list</a>.</p>
<p> Although this discussion has primarily focused on <tt>%rename</tt>
 all of the same rules also apply to <tt>%ignore</tt>. For example:</p>
<div class="code">
<pre>
%ignore foo(double);          // Ignore all foo(double)
%ignore Spam::foo;            // Ignore foo in class Spam
%ignore Spam::foo(double);    // Ignore foo(double) in class Spam
%ignore *::foo(double);       // Ignore foo(double) in all classes
</pre>
</div>
<p> When applied to a base class, <tt>%ignore</tt> forces all
 definitions in derived classes to disappear. For example, <tt>%ignore
 Spam::foo(double)</tt> will eliminate <tt>foo(double)</tt> in <tt>Spam</tt>
 and all classes derived from <tt>Spam</tt>.</p>
<p><b> Notes on %rename and %ignore:</b></p>
<ul>
<li>
<p>Since, the <tt>%rename</tt> declaration is used to declare a renaming
 in advance, it can be placed at the start of an interface file. This
 makes it possible to apply a consistent name resolution without having
 to modify header files. For example:</p>
<div class="code">
<pre>
%module foo

/* Rename these overloaded functions */
%rename(foo_i) foo(int); 
%rename(foo_d) foo(double);

%include &quot;header.h&quot;
</pre>
</div></li>
<li>
<p>The scope qualifier (::) can also be used on simple names. For
 example:</p>
<div class="code">
<pre>
%rename(bar) ::foo;       // Rename foo to bar in global scope only
%rename(bar) Spam::foo;   // Rename foo to bar in class Spam only
%rename(bar) *::foo;      // Rename foo in classes only
</pre>
</div></li>
<li>
<p>Name matching tries to find the most specific match that is defined.
 A qualified name such as <tt>Spam::foo</tt> always has higher
 precedence than an unqualified name <tt>foo</tt>. <tt>Spam::foo</tt>
 has higher precedence than <tt>*::foo</tt> and <tt>*::foo</tt> has
 higher precedence than <tt>foo</tt>. A parameterized name has higher
 precedence than an unparameterized name within the same scope level.
 However, an unparameterized name with a scope qualifier has higher
 precedence than a parameterized name in global scope (e.g., a renaming
 of <tt>Spam::foo</tt> takes precedence over a renaming of <tt>foo(int)</tt>
).</p>
</li>
<li>
<p> The order in which <tt>%rename</tt> directives are defined does not
 matter as long as they appear before the declarations to be renamed.
 Thus, there is no difference between saying:</p>
<div class="code">
<pre>
%rename(bar) foo;
%rename(foo_i) Spam::foo(int);
%rename(Foo) Spam::foo;
</pre>
</div>
<p> and this</p>
<div class="code">
<pre>
%rename(Foo) Spam::foo;
%rename(bar) foo;
%rename(foo_i) Spam::foo(int);
</pre>
</div>
<p> (the declarations are not stored in a linked list and order has no
 importance). Of course, a repeated <tt>%rename</tt> directive will
 change the setting for a previous <tt>%rename</tt> directive if exactly
 the same name, scope, and parameters are supplied.</p>
</li>
<li>For multiple inheritance where renaming rules are defined for
 multiple base classes, the first renaming rule found on a depth-first
 traversal of the class hierarchy is used.</li>
<li>
<p>The name matching rules strictly follow member qualifier rules. For
 example, if you have a class and member with a member that is const
 qualified like this:</p>
<div class="code">
<pre>
class Spam {
public:
  ...
  void bar() const;
  ...
};
</pre>
</div>
<p> the declaration</p>
<div class="code">
<pre>
%rename(name) Spam::bar();
</pre>
</div>
<p> will not apply as there is no unqualified member <tt>bar()</tt>. The
 following will apply the rename as the qualifier matches correctly:</p>
<div class="code">
<pre>
%rename(name) Spam::bar() const;
</pre>
</div>
<p> Similarly for combinations of cv-qualifiers and ref-qualifiers, all
 the qualifiers must be specified to match correctly:</p>
<div class="code">
<pre>
%rename(name) Jam::bar();          // will not match
%rename(name) Jam::bar() &amp;;        // will not match
%rename(name) Jam::bar() const;    // will not match
%rename(name) Jam::bar() const &amp;;  // ok, will match

class Jam {
public:
  ...
  void bar() const &amp;;
  ...
};
</pre>
</div>
<p> An often overlooked C++ feature is that classes can define two
 different overloaded members that differ only in their qualifiers, like
 this:</p>
<div class="code">
<pre>
class Spam {
public:
  ...
  void bar();         // Unqualified member
  void bar() const;   // Qualified member
  ...
};
</pre>
</div>
<p> %rename can then be used to target each of the overloaded methods
 individually. For example we can give them separate names in the target
 language:</p>
<div class="code">
<pre>
%rename(name1) Spam::bar();
%rename(name2) Spam::bar() const;
</pre>
</div>
<p> Similarly, if you merely wanted to ignore one of the declarations,
 use <tt>%ignore</tt> with the full qualifier. For example, the
 following directive would tell SWIG to ignore the <tt>const</tt>
 version of <tt>bar()</tt> above:</p>
<div class="code">
<pre>
%ignore Spam::bar() const;   // Ignore bar() const, but leave other bar() alone
</pre>
</div></li>
<li>
<p> Currently no resolution is performed in order to match function
 parameters. This means function parameter types must match exactly. For
 example, namespace qualifiers and typedefs will not work. The following
 usage of typedefs demonstrates this:</p>
<div class="code">
<pre>
typedef int Integer;

%rename(foo_i) foo(int);

class Spam {
public:
  void foo(Integer);  // Stays 'foo' (not renamed)
};
class Ham {
public:
  void foo(int);      // Renamed to foo_i
};
</pre>
</div></li>
<li>
<p> The name matching rules also use default arguments for finer control
 when wrapping methods that have default arguments. Recall that methods
 with default arguments are wrapped as if the equivalent overloaded
 methods had been parsed (<a href="#SWIGPlus_default_args">Default
 arguments</a> section). Let's consider the following example class:</p>
<div class="code">
<pre>
class Spam {
public:
  ...
  void bar(int i=-1, double d=0.0);
  ...
};
</pre>
</div>
<p> The following <tt>%rename</tt> will match exactly and apply to all
 the target language overloaded methods because the declaration with the
 default arguments exactly matches the wrapped method:</p>
<div class="code">
<pre>
%rename(newbar) Spam::bar(int i=-1, double d=0.0);
</pre>
</div>
<p> The C++ method can then be called from the target language with the
 new name no matter how many arguments are specified, for example: <tt>
newbar(2, 2.0)</tt>, <tt>newbar(2)</tt> or <tt>newbar()</tt>. However,
 if the <tt>%rename</tt> does not contain the default arguments:</p>
<div class="code">
<pre>
%rename(newbar) Spam::bar(int i, double d);
</pre>
</div>
<p> then only one of the three equivalent overloaded methods will be
 renamed and wrapped as if SWIG parsed:</p>
<div class="code">
<pre>
void Spam::newbar(int i, double d);
void Spam::bar(int i);
void Spam::bar();
</pre>
</div>
<p> The C++ method must then be called from the target language with the
 new name <tt>newbar(2, 2.0)</tt> when both arguments are supplied or
 with the original name as <tt>bar(2)</tt> (one argument) or <tt>bar()</tt>
 (no arguments).</p>
<p> In fact it is possible to use <tt>%rename</tt> on the equivalent
 overloaded methods, to rename all the equivalent overloaded methods:</p>
<div class="code">
<pre>
%rename(bar_2args)   Spam::bar(int i, double d);
%rename(bar_1arg)    Spam::bar(int i);
%rename(bar_default) Spam::bar();
</pre>
</div>
<p> Similarly, the extra overloaded methods can be selectively ignored
 using <tt>%ignore</tt>.</p>
<p><b> Compatibility note:</b> The <tt>%rename</tt> directive introduced
 the default argument matching rules in SWIG-1.3.23 at the same time as
 the changes to wrapping methods with default arguments was introduced.</p>
</li>
</ul>
<h3><a name="SWIGPlus_nn27">6.15.4 Comments on overloading</a></h3>
<p> Support for overloaded methods was first added in SWIG-1.3.14. The
 implementation is somewhat unusual when compared to similar tools. For
 instance, the order in which declarations appear is largely irrelevant
 in SWIG. Furthermore, SWIG does not rely upon trial execution or
 exception handling to figure out which method to invoke.</p>
<p> Internally, the overloading mechanism is completely configurable by
 the target language module. Therefore, the degree of overloading
 support may vary from language to language. As a general rule,
 statically typed languages like Java are able to provide more support
 than dynamically typed languages like Perl, Python, Ruby, and Tcl.</p>
<h2><a name="SWIGPlus_nn28">6.16 Overloaded operators</a></h2>
<p> C++ overloaded operator declarations can be wrapped. For example,
 consider a class like this:</p>
<div class="code">
<pre>
class Complex {
private:
  double rpart, ipart;
public:
  Complex(double r = 0, double i = 0) : rpart(r), ipart(i) { }
  Complex(const Complex &amp;c) : rpart(c.rpart), ipart(c.ipart) { }
  Complex &amp;operator=(const Complex &amp;c) {
    rpart = c.rpart;
    ipart = c.ipart;
    return *this;
  }
  Complex operator+(const Complex &amp;c) const {
    return Complex(rpart+c.rpart, ipart+c.ipart);
  }
  Complex operator-(const Complex &amp;c) const {
    return Complex(rpart-c.rpart, ipart-c.ipart);
  }
  Complex operator*(const Complex &amp;c) const {
    return Complex(rpart*c.rpart - ipart*c.ipart,
                   rpart*c.ipart + c.rpart*ipart);
  }
  Complex operator-() const {
    return Complex(-rpart, -ipart);
  }
  double re() const { return rpart; }
  double im() const { return ipart; }
};
</pre>
</div>
<p> When operator declarations appear, they are handled in<em> exactly</em>
 the same manner as regular methods. However, the names of these methods
 are set to strings like &quot;<tt>operator +</tt>&quot; or &quot;<tt>operator -</tt>&quot;.
 The problem with these names is that they are illegal identifiers in
 most scripting languages. For instance, you can't just create a method
 called &quot;<tt>operator +</tt>&quot; in Python--there won't be any way to call
 it.</p>
<p> Some language modules already know how to automatically handle
 certain operators (mapping them into operators in the target language).
 However, the underlying implementation of this is really managed in a
 very general way using the <tt>%rename</tt> directive. For example, in
 Python a declaration similar to this is used:</p>
<div class="code">
<pre>
%rename(__add__) Complex::operator+;
</pre>
</div>
<p> This binds the + operator to a method called <tt>__add__</tt> (which
 is conveniently the same name used to implement the Python + operator).
 Internally, the generated wrapper code for a wrapped operator will look
 something like this pseudocode:</p>
<div class="code">
<pre>
_wrap_Complex___add__(args) {
  ... get args ...
  obj-&gt;operator+(args);
  ...
}
</pre>
</div>
<p> When used in the target language, it may now be possible to use the
 overloaded operator normally. For example:</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; a = Complex(3, 4)
&gt;&gt;&gt; b = Complex(5, 2)
&gt;&gt;&gt; c = a + b           # Invokes __add__ method
</pre>
</div>
<p> It is important to realize that there is nothing magical happening
 here. The <tt>%rename</tt> directive really only picks a valid method
 name. If you wrote this:</p>
<div class="code">
<pre>
%rename(add) operator+;
</pre>
</div>
<p> The resulting scripting interface might work like this:</p>
<div class="targetlang">
<pre>
a = Complex(3, 4)
b = Complex(5, 2)
c = a.add(b)      # Call a.operator+(b)
</pre>
</div>
<p> All of the techniques described to deal with overloaded functions
 also apply to operators. For example:</p>
<div class="code">
<pre>
%ignore Complex::operator=;             // Ignore = in class Complex
%ignore *::operator=;                   // Ignore = in all classes
%ignore operator=;                      // Ignore = everywhere.

%rename(__sub__) Complex::operator-; 
%rename(__neg__) Complex::operator-();  // Unary - 
</pre>
</div>
<p> The last part of this example illustrates how multiple definitions
 of the <tt>operator-</tt> method might be handled.</p>
<p> Handling operators in this manner is mostly straightforward.
 However, there are a few subtle issues to keep in mind:</p>
<ul>
<li>
<p>In C++, it is fairly common to define different versions of the
 operators to account for different types. For example, a class might
 also include a friend function like this:</p>
<div class="code">
<pre>
class Complex {
public:
  friend Complex operator+(Complex &amp;, double);
};
Complex operator+(Complex &amp;, double);
</pre>
</div>
<p> SWIG simply ignores all <tt>friend</tt> declarations. Furthermore,
 it doesn't know how to associate the associated <tt>operator+</tt> with
 the class (because it's not a member of the class).</p>
<p> It's still possible to make a wrapper for this operator, but you'll
 have to handle it like a normal function. For example:</p>
<div class="code">
<pre>
%rename(add_complex_double) operator+(Complex &amp;, double);
</pre>
</div></li>
<li>
<p>Certain operators are ignored by default. For instance, <tt>new</tt>
 and <tt>delete</tt> operators are ignored as well as conversion and
 index operators. A warning such as the one below is shown:</p>
<div class="shell">
<pre>
example.i:12: Warning 503: Can't wrap 'operator []' unless renamed to a valid identifier.
</pre>
</div></li>
<li>
<p>The index operator, <tt>operator[]</tt>, is particularly difficult to
 overload due to differences in C++ implementations. Specifically, the
 get and set operators in other languages typically are separated into
 two methods such that additional logic can be packed into the
 operations; C# uses <tt>this[type key] { get { ... } set { ... }}</tt>,
 Python uses <tt>__getitem__</tt> and <tt>__setitem__</tt>, etc. In C++
 if the return type of <tt>operator[]</tt> is a reference and the method
 is const, it is often indicative of the<i> setter</i>, and the<i>
 getter</i> is usually a const function return an object by value. In
 the absence of any hard and fast rules and the fact that there may be
 multiple index operators, it is up to the user to choose the getter and
 setter to use by using %rename as shown earlier.</p>
</li>
<li>The semantics of certain C++ operators may not match those in the
 target language.</li>
</ul>
<h2><a name="SWIGPlus_class_extension">6.17 Class extension</a></h2>
<p> New methods can be added to a class using the <tt>%extend</tt>
 directive. This directive is primarily used in conjunction with proxy
 classes to add additional functionality to an existing class. For
 example :</p>
<div class="code">
<pre>
%module vector
%{
#include &quot;vector.h&quot;
%}

class Vector {
public:
  double x, y, z;
  Vector();
  ~Vector();
  ... bunch of C++ methods ...
  %extend {
    char *__str__() {
      static char temp[256];
      sprintf(temp, &quot;[ %g, %g, %g ]&quot;, $self-&gt;x, $self-&gt;y, $self-&gt;z);
      return &amp;temp[0];
    }
  }
};
</pre>
</div>
<p> This code adds a <tt>__str__</tt> method to our class for producing
 a string representation of the object. In Python, such a method would
 allow us to print the value of an object using the <tt>print</tt>
 command.</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt;
&gt;&gt;&gt; v = Vector();
&gt;&gt;&gt; v.x = 3
&gt;&gt;&gt; v.y = 4
&gt;&gt;&gt; v.z = 0
&gt;&gt;&gt; print(v)
[ 3.0, 4.0, 0.0 ]
&gt;&gt;&gt;

</pre>
</div>
<p> The C++ 'this' pointer is often needed to access member variables,
 methods etc. The <tt>$self</tt> special variable should be used
 wherever you could use 'this'. The example above demonstrates this for
 accessing member variables. Note that the members dereferenced by <tt>
$self</tt> must be public members as the code is ultimately generated
 into a global function and so will not have any access to non-public
 members. The implicit 'this' pointer that is present in C++ methods is
 not present in <tt>%extend</tt> methods. In order to access anything in
 the extended class or its base class, an explicit 'this' is required.
 The following example shows how one could access base class members:</p>
<div class="code">
<pre>
struct Base {
  virtual void method(int v) {
    ...
  }
  int value;
};
struct Derived : Base {
};
%extend Derived {
  virtual void method(int v) {
    $self-&gt;Base::method(v); // akin to this-&gt;Base::method(v);
    $self-&gt;value = v;       // akin to this-&gt;value = v;
    ...
  }
}
</pre>
</div>
<p> The following special variables are expanded if used within a
 %extend block: $name, $symname, $overname, $decl, $fulldecl,
 $parentclassname and $parentclasssymname. The <a href="#Customization_exception_special_variables">
Special variables</a> section provides more information each of these
 special variables.</p>
<p> The <tt>%extend</tt> directive follows all of the same conventions
 as its use with C structures. Please refer to the <a href="#SWIG_adding_member_functions">
Adding member functions to C structures</a> section for further details.</p>
<p><b> Compatibility note:</b> The <tt>%extend</tt> directive is a new
 name for the <tt>%addmethods</tt> directive in SWIG1.1. Since <tt>
%addmethods</tt> could be used to extend a structure with more than just
 methods, a more suitable directive name has been chosen.</p>
<h2><a name="SWIGPlus_nn30">6.18 Templates</a></h2>
<p> Template type names may appear anywhere a type is expected in an
 interface file. For example:</p>
<div class="code">
<pre>
void foo(vector&lt;int&gt; *a, int n);
void bar(list&lt;int, 100&gt; *x);
</pre>
</div>
<p> There are some restrictions on the use of non-type arguments. Simple
 literals are supported, and so are some constant expressions. However,
 use of '&lt;' and '&gt;' within a constant expressions currently is not
 supported by SWIG ('&lt;=' and '&gt;=' are though). For example:</p>
<div class="code">
<pre>
void bar(list&lt;int, 100&gt; *x);                // OK
void bar(list&lt;int, 2*50&gt; *x);               // OK
void bar(list&lt;int, (2&gt;1 ? 100 : 50)&gt; *x)    // Not supported
</pre>
</div>
<p> The type system is smart enough to figure out clever games you might
 try to play with <tt>typedef</tt>. For instance, consider this code:</p>
<div class="code">
<pre>
typedef int Integer;
void foo(vector&lt;int&gt; *x, vector&lt;Integer&gt; *y);
</pre>
</div>
<p> In this case, <tt>vector&lt;Integer&gt;</tt> is exactly the same type as <tt>
vector&lt;int&gt;</tt>. The wrapper for <tt>foo()</tt> will accept either
 variant.</p>
<h3><a name="SWIGPlus_template_directive">6.18.1 The %template directive</a>
</h3>
<p> There are a couple of important points about template wrapping.
 First, a bare C++ template does not define any sort of runnable
 object-code for which SWIG can normally create a wrapper. Therefore, in
 order to wrap a template, you need to give SWIG information about a
 particular template instantiation (e.g., <tt>vector&lt;int&gt;</tt>, <tt>
array&lt;double&gt;</tt>, etc.). Second, an instantiation name such as <tt>
vector&lt;int&gt;</tt> is generally not a valid identifier name in most target
 languages. Thus, you will need to give the template instantiation a
 more suitable name such as <tt>intvector</tt>.</p>
<p> To illustrate, consider the following class template definition:</p>
<div class="code">
<pre>
template&lt;class T&gt; class List {
private:
  T *data;
  int nitems;
  int maxitems;
public:
  List(int max) {
    data = new T [max];
    nitems = 0;
    maxitems = max;
  }
  ~List() {
    delete [] data;
  };
  void append(T obj) {
    if (nitems &lt; maxitems) {
      data[nitems++] = obj;
    }
  }
  int length() {
    return nitems;
  }
  T get(int n) {
    return data[n];
  }
};
</pre>
</div>
<p> By itself, this class template is useless--SWIG simply ignores it
 because it doesn't know how to generate any code unless a definition of
 <tt>T</tt> is provided. The <tt>%template</tt> directive is required to
 instantiate the template for use in a target language. The directive
 requires an identifier name for use in the target language plus the
 template for instantiation. The example below instantiates <tt>
List&lt;int&gt;</tt> for use as a class named <tt>intList</tt>:</p>
<div class="code">
<pre>
%template(intList) List&lt;int&gt;;
</pre>
</div>
<p> The instantiation expands the template code as a C++ compiler would
 do and then makes it available under the given identifier name.
 Essentially it is the same as wrapping the following concept code where
 the class template definition has <tt>T</tt> expanded to <tt>int</tt>
 (note that this is not entirely valid syntax):</p>
<div class="code">
<pre>
%rename(intList) List&lt;int&gt;;       // Rename to a suitable identifier
class List&lt;int&gt; {
private:
  int *data;
  int nitems;
  int maxitems;
public:
  List(int max);
  ~List();
  void append(int obj);
  int length();
  int get(int n);
};
</pre>
</div>
<p> The argument to <tt>%template()</tt> is the name of the
 instantiation in the target language. The name you choose should not
 conflict with any other declarations in the interface file with one
 exception---it is okay for the template name to match that of a typedef
 declaration. For example:</p>
<div class="code">
<pre>
%template(intList) List&lt;int&gt;;
...
typedef List&lt;int&gt; intList;    // OK
</pre>
</div>
<p> The <tt>%template</tt> directive must always appear<em> after</em>
 the definition of the template to be expanded, so the following will
 work:</p>
<div class="code">
<pre>
template&lt;class T&gt; class List { ... };
%template(intList) List&lt;int&gt;;
</pre>
</div>
<p> but if %template is used before the template definition, such as:</p>
<div class="code">
<pre>
%template(intList) List&lt;int&gt;;
template&lt;class T&gt; class List { ... };
</pre>
</div>
<p> SWIG will generate an error:</p>
<div class="shell">
<pre>
example.i:3: Error: Template 'List' undefined.
</pre>
</div>
<p> Since the type system knows how to handle <tt>typedef</tt>, it is
 generally not necessary to instantiate different versions of a template
 for typenames that are equivalent. For instance, consider this code:</p>
<div class="code">
<pre>
%template(intList) List&lt;int&gt;;
typedef int Integer;
...
void foo(List&lt;Integer&gt; *x);
</pre>
</div>
<p> In this case, <tt>List&lt;Integer&gt;</tt> is exactly the same type as <tt>
List&lt;int&gt;</tt>. Any use of <tt>List&lt;Integer&gt;</tt> is mapped back to the
 instantiation of <tt>List&lt;int&gt;</tt> created earlier. Therefore, it is
 not necessary to instantiate a new class for the type <tt>Integer</tt>
 (doing so is redundant and will simply result in code bloat).</p>
<p> The template provided to <tt>%template</tt> for instantiation must
 be the actual template and not a typedef to a template.</p>
<div class="code">
<pre>
typedef List&lt;int&gt; ListOfInt;

%template(intList) List&lt;int&gt;; // ok
%template(intList) ListOfInt; // illegal - Syntax error
</pre>
</div>
<h3><a name="SWIGPlus_template_functions">6.18.2 Function templates</a></h3>
<p> SWIG can also generate wrappers for function templates using a
 similar technique to that shown above for class templates. For example:</p>
<div class="code">
<pre>
// Function template
template&lt;class T&gt; T max(T a, T b) { return a &gt; b ? a : b; }

// Make some different versions of this function
%template(maxint) max&lt;int&gt;;
%template(maxdouble) max&lt;double&gt;;
</pre>
</div>
<p> In this case, <tt>maxint</tt> and <tt>maxdouble</tt> become unique
 names for specific instantiations of the function.</p>
<p> SWIG even supports overloaded templated functions. As usual the <tt>
%template</tt> directive is used to wrap templated functions. For
 example:</p>
<div class="code">
<pre>
template&lt;class T&gt; void foo(T x) { };
template&lt;class T&gt; void foo(T x, T y) { };

%template(foo) foo&lt;int&gt;;
</pre>
</div>
<p> This will generate two overloaded wrapper methods, the first will
 take a single integer as an argument and the second will take two
 integer arguments.</p>
<h3><a name="SWIGPlus_template_classes">6.18.3 Default template
 arguments</a></h3>
<p> The number of arguments supplied to <tt>%template</tt> should match
 that in the original template definition. Template default arguments
 are supported. For example:</p>
<div class="code">
<pre>
template vector&lt;typename T, int max=100&gt; class vector {
...
};

%template(intvec) vector&lt;int&gt;;           // OK
%template(vec1000) vector&lt;int, 1000&gt;;     // OK
</pre>
</div>
<p> The <tt>%template</tt> directive should not be used to wrap the same
 template instantiation more than once in the same scope. This will
 generate an error. For example:</p>
<div class="code">
<pre>
%template(intList) List&lt;int&gt;;
%template(Listint) List&lt;int&gt;;    // Error.   Template already wrapped.
</pre>
</div>
<p> This error is caused because the template expansion results in two
 identical classes with the same name. This generates a symbol table
 conflict. Besides, it probably more efficient to only wrap a specific
 instantiation only once in order to reduce the potential for code
 bloat.</p>
<h3><a name="SWIGPlus_template_class_inheritance">6.18.4 Template base
 classes</a></h3>
<p> When a template is instantiated using <tt>%template</tt>,
 information about that class is saved by SWIG and used elsewhere in the
 program. For example, if you wrote code like this,</p>
<div class="code">
<pre>
...
%template(intList) List&lt;int&gt;;
...
class UltraList : public List&lt;int&gt; {
  ...
};
</pre>
</div>
<p> then SWIG knows that <tt>List&lt;int&gt;</tt> was already wrapped as a
 class called <tt>intList</tt> and arranges to handle the inheritance
 correctly. If, on the other hand, nothing is known about <tt>List&lt;int&gt;</tt>
, you will get a warning message similar to this:</p>
<div class="shell">
<pre>
example.h:42: Warning 401. Nothing known about class 'List&lt; int &gt;'. Ignored. 
example.h:42: Warning 401. Maybe you forgot to instantiate 'List&lt; int &gt;' using %template. 
</pre>
</div>
<p> If a class template inherits from another class template, you need
 to make sure that base classes are instantiated before derived classes.
 For example:</p>
<div class="code">
<pre>
template&lt;class T&gt; class Foo {
...
};

template&lt;class T&gt; class Bar : public Foo&lt;T&gt; {
...
};

// Instantiate base classes first 
%template(intFoo) Foo&lt;int&gt;;
%template(doubleFoo) Foo&lt;double&gt;;

// Now instantiate derived classes
%template(intBar) Bar&lt;int&gt;;
%template(doubleBar) Bar&lt;double&gt;;
</pre>
</div>
<p> The order is important since SWIG uses the instantiation names to
 properly set up the inheritance hierarchy in the resulting wrapper code
 (and base classes need to be wrapped before derived classes). Don't
 worry--if you get the order wrong, SWIG should generate a warning
 message.</p>
<p> Occasionally, you may need to tell SWIG about base classes that are
 defined by templates, but which aren't supposed to be wrapped. Since
 SWIG is not able to automatically instantiate templates for this
 purpose, you must do it manually. To do this, simply use the empty
 template instantiation, that is, <tt>%template</tt> with no name. For
 example:</p>
<div class="code">
<pre>
// Instantiate traits&lt;double, double&gt;, but don't wrap it.
%template() traits&lt;double, double&gt;;
</pre>
</div>
<p> If you have to instantiate a lot of different classes for many
 different types, you might consider writing a SWIG macro. For example:</p>
<div class="code">
<pre>
%define TEMPLATE_WRAP(prefix, T...) 
%template(prefix ## Foo) Foo&lt;T &gt;;
%template(prefix ## Bar) Bar&lt;T &gt;;
...
%enddef

TEMPLATE_WRAP(int, int)
TEMPLATE_WRAP(double, double)
TEMPLATE_WRAP(String, char *)
TEMPLATE_WRAP(PairStringInt, std::pair&lt;string, int&gt;)
...
</pre>
</div>
<p> Note the use of a vararg macro for the type T. If this wasn't used,
 the comma in the templated type in the last example would not be
 possible.</p>
<h3><a name="SWIGPlus_template_specialization">6.18.5 Template
 specialization</a></h3>
<p> The SWIG template mechanism<em> does</em> support specialization.
 For instance, if you define a class like this,</p>
<div class="code">
<pre>
template&lt;&gt; class List&lt;int&gt; {
private:
  int *data;
  int nitems;
  int maxitems;
public:
  List(int max);
  ~List();
  void append(int obj);
  int length();
  int get(int n);
};
</pre>
</div>
<p> then SWIG will use this code whenever the user expands <tt>List&lt;int&gt;</tt>
. In practice, this may have very little effect on the underlying
 wrapper code since specialization is often used to provide slightly
 modified method bodies (which are ignored by SWIG). However, special
 SWIG directives such as <tt>%typemap</tt>, <tt>%extend</tt>, and so
 forth can be attached to a specialization to provide customization for
 specific types.</p>
<p> Partial template specialization is partially supported by SWIG. For
 example, this code defines a template that is applied when the template
 argument is a pointer.</p>
<div class="code">
<pre>
template&lt;class T&gt; class List&lt;T*&gt; {
private:
  T *data;
  int nitems;
  int maxitems;
public:
  List(int max);
  ~List();
  void append(T obj);
  int length();
  T get(int n);
};
</pre>
</div>
<p> SWIG supports both template explicit specialization and partial
 specialization. Consider:</p>
<div class="code">
<pre>
template&lt;class T1, class T2&gt; class Foo { };                     // (1) primary template
template&lt;&gt;                   class Foo&lt;double *, int *&gt; { };    // (2) explicit specialization
template&lt;class T1, class T2&gt; class Foo&lt;T1, T2 *&gt; { };           // (3) partial specialization
</pre>
</div>
<p> SWIG is able to properly match explicit instantiations:</p>
<div class="code">
<pre>
<tt>Foo&lt;double *, int *&gt;</tt>     // explicit specialization matching (2)
</pre>
</div>
<p> SWIG implements template argument deduction so that the following
 partial specialization examples work just like they would with a C++
 compiler:</p>
<div class="code">
<pre>
<tt>Foo&lt;int *, int *&gt;</tt>        // partial specialization matching (3)
<tt>Foo&lt;int *, const int *&gt;</tt>  // partial specialization matching (3)
<tt>Foo&lt;int *, int **&gt;</tt>       // partial specialization matching (3)
</pre>
</div>
<h3><a name="SWIGPlus_template_member">6.18.6 Member templates</a></h3>
<p> Member templates are supported. The underlying principle is the same
 as for normal templates--SWIG can't create a wrapper unless you provide
 more information about types. For example, a class with a member
 function template might look like this:</p>
<div class="code">
<pre>
class Foo {
public:
  template&lt;class T&gt; void bar(T x, T y) { ... };
  ...
};
</pre>
</div>
<p> To expand the template, simply use <tt>%template</tt> inside the
 class.</p>
<div class="code">
<pre>
class Foo {
public:
  template&lt;class T&gt; void bar(T x, T y) { ... };
  ...
  %template(barint)    bar&lt;int&gt;;
  %template(bardouble) bar&lt;double&gt;;
};
</pre>
</div>
<p> Or, if you want to leave the original class definition alone, just
 do this:</p>
<div class="code">
<pre>
class Foo {
public:
  template&lt;class T&gt; void bar(T x, T y) { ... };
  ...
};
...
%extend Foo {
  %template(barint)    bar&lt;int&gt;;
  %template(bardouble) bar&lt;double&gt;;
};
</pre>
</div>
<p> or simply</p>
<div class="code">
<pre>
class Foo {
public:
  template&lt;class T&gt; void bar(T x, T y) { ... };
  ...
};
...

%template(bari) Foo::bar&lt;int&gt;;
%template(bard) Foo::bar&lt;double&gt;;
</pre>
</div>
<p> In this case, the <tt>%extend</tt> directive is not needed, and <tt>
%template</tt> does exactly the same job, i.e., it adds two new methods
 to the Foo class.</p>
<p> Now, if your target language supports overloading, you can even try</p>
<div class="code">
<pre>
%template(bar) Foo::bar&lt;int&gt;;
%template(bar) Foo::bar&lt;double&gt;;
</pre>
</div>
<p> and since the two new wrapped methods have the same name 'bar', they
 will be overloaded, and when called, the correct method will be
 dispatched depending on the argument type.</p>
<p> When used with members, the <tt>%template</tt> directive may be
 placed in another class template. Here is a slightly perverse example:</p>
<div class="code">
<pre>
// A template
template&lt;class T&gt; class Foo {
public:
  // A member template
  template&lt;class S&gt; T bar(S x, S y) { ... };
  ...
};

// Expand a few member templates
%extend Foo {
  %template(bari) bar&lt;int&gt;;
  %template(bard) bar&lt;double&gt;;
}

// Create some wrappers for the template
%template(Fooi) Foo&lt;int&gt;;
%template(Food) Foo&lt;double&gt;;
</pre>
</div>
<p> Miraculously, you will find that each expansion of <tt>Foo</tt> has
 member functions <tt>bari()</tt> and <tt>bard()</tt> added.</p>
<p> A common use of member templates is to define constructors for
 copies and conversions. For example:</p>
<div class="code">
<pre>
template&lt;class T1, class T2&gt; struct pair {
  T1 first;
  T2 second;
  pair() : first(T1()), second(T2()) { }
  pair(const T1 &amp;x, const T2 &amp;y) : first(x), second(y) { }
  template&lt;class U1, class U2&gt; pair(const pair&lt;U1, U2&gt; &amp;x)
                                       : first(x.first), second(x.second) { }
};
</pre>
</div>
<p> This declaration is perfectly acceptable to SWIG, but the
 constructor template will be ignored unless you explicitly expand it.
 To do that, you could expand a few versions of the constructor in the
 class template itself. For example:</p>
<div class="code">
<pre>
%extend pair {
  %template(pair) pair&lt;T1, T2&gt;;        // Generate default copy constructor
};
</pre>
</div>
<p> When using <tt>%extend</tt> in this manner, notice how you can still
 use the template parameters in the original template definition.</p>
<p> Alternatively, you could expand the constructor template in selected
 instantiations. For example:</p>
<div class="code">
<pre>
// Instantiate a few versions
%template(pairii) pair&lt;int, int&gt;;
%template(pairdd) pair&lt;double, double&gt;;

// Create a default constructor only 
%extend pair&lt;int, int&gt; {
  %template(paird) pair&lt;int, int&gt;;         // Default constructor
};

// Create default and conversion constructors 
%extend pair&lt;double, double&gt; {
  %template(paird) pair&lt;double, dobule&gt;;   // Default constructor
  %template(pairc) pair&lt;int, int&gt;;         // Conversion constructor
};
</pre>
</div>
<p>And if your target language supports overloading, then you can try
 instead:</p>
<div class="code">
<pre>
// Create default and conversion constructors 
%extend pair&lt;double, double&gt; {
  %template(pair) pair&lt;double, dobule&gt;;   // Default constructor
  %template(pair) pair&lt;int, int&gt;;         // Conversion constructor
};
</pre>
</div>
<p> In this case, the default and conversion constructors have the same
 name. Hence, SWIG will overload them and define an unique visible
 constructor, that will dispatch the proper call depending on the
 argument type.</p>
<h3><a name="SWIGPlus_template_scoping">6.18.7 Scoping and templates</a></h3>
<p> The <tt>%template</tt> directive for a class template is the
 equivalent to an explicit instantiation of a C++ class template. The
 scope for a valid <tt>%template</tt> instantiation is the same as the
 scope required for a valid explicit instantiation of a C++ template. A
 definition of the template for the explicit instantiation must be in
 scope where the instantiation is declared and must not be enclosed
 within a different namespace.</p>
<p> For example, a few <tt>%template</tt> instantiations and C++
 explicit instantiations are shown below:</p>
<div class="code">
<pre>
namespace N {
  template&lt;typename T&gt; class C {};
}

// valid
%template(cin) N::C&lt;int&gt;;
template class N::C&lt;int&gt;;

// valid
namespace N {
  %template(cin) C&lt;int&gt;;
  template class C&lt;int&gt;;
}

// valid
using namespace N;
%template(cin) C&lt;int&gt;;
template class C&lt;int&gt;;

// valid
using N::C;
%template(cin) C&lt;int&gt;;
template class C&lt;int&gt;;

// ill-formed
namespace unrelated {
  using N::C;
  %template(cin) C&lt;int&gt;;
  template class C&lt;int&gt;;
}

// ill-formed
namespace unrelated {
  using namespace N;
  %template(cin) C&lt;int&gt;;
  template class C&lt;int&gt;;
}

// ill-formed
namespace unrelated {
  namespace N {
    %template(cin) C&lt;int&gt;;
    template class C&lt;int&gt;;
  }
}

// ill-formed
namespace unrelated {
  %template(cin) N::C&lt;int&gt;;
  template class N::C&lt;int&gt;;
}
</pre>
</div>
<p> When the scope is incorrect, such as for the ill-formed examples
 above, an error occurs:</p>
<div class="shell">
<pre>
cpp_template_scope.i:34: Error: 'C' resolves to 'N::C' and was incorrectly instantiated
in scope 'unrelated' instead of within scope 'N'.
</pre>
</div>
<p> A note for the C++ standard geeks out there; a valid instantiation
 is one which conforms to the C++03 standard as C++11 made a change to
 disallow using declarations and using directives to find a template.</p>
<div class="code">
<pre>
// valid C++03, ill-formed C++11
using N::C;
template class C&lt;int&gt;;
</pre>
</div>
<p><b> Compatibility Note</b>: Versions prior to SWIG-4.0.0 did not
 error out with incorrectly scoped <tt>%template</tt> declarations, but
 this led to numerous subtle template scope problems.</p>
<h3><a name="SWIGPlus_template_more">6.18.8 More on templates</a></h3>
<p> If all of this isn't quite enough and you really want to make
 someone's head explode, SWIG directives such as <tt>%rename</tt>, <tt>
%extend</tt>, and <tt>%typemap</tt> can be included directly in template
 definitions. For example:</p>
<div class="code">
<pre>
// File : list.h
template&lt;class T&gt; class List {
  ...
public:
  %rename(__getitem__) get(int);
  List(int max);
  ~List();
  ...
  T get(int index);
  %extend {
    char *__str__() {
      /* Make a string representation */
      ...
    }
  }
};
</pre>
</div>
<p> In this example, the extra SWIG directives are propagated to<em>
 every</em> template instantiation.</p>
<p> It is also possible to separate these declarations from the class
 template. For example:</p>
<div class="code">
<pre>
%rename(__getitem__) List::get;
%extend List {
  char *__str__() {
    /* Make a string representation */
    ...
  }
  /* Make a copy */
  T *__copy__() {
    return new List&lt;T&gt;(*$self);
  }
};

...
template&lt;class T&gt; class List {
  ...
  public:
  List() { }
  T get(int index);
  ...
};
</pre>
</div>
<p> When <tt>%extend</tt> is decoupled from the class definition, it is
 legal to use the same template parameters as provided in the class
 definition. These are replaced when the template is expanded. In
 addition, the <tt>%extend</tt> directive can be used to add additional
 methods to a specific instantiation. For example:</p>
<div class="code">
<pre>
%template(intList) List&lt;int&gt;;

%extend List&lt;int&gt; {
  void blah() {
    printf(&quot;Hey, I'm an List&lt;int&gt;!\n&quot;);
  }
};
</pre>
</div>
<p> It is even possible to extend a class via <tt>%extend</tt> with
 template methods, for example:</p>
<div class="code">
<pre>
%include &lt;std_string.i&gt;

%inline %{
class ExtendMe {
public:
  template &lt;typename T&gt;
  T do_stuff_impl(int a, T b, double d) {
    return b;
  }
};
%}

%extend ExtendMe {
  template&lt;typename T&gt;
  T do_overloaded_stuff(T b) {
    return $self-&gt;do_stuff_impl(0, b, 4.0);
  }
}
%template(do_overloaded_stuff) ExtendMe::do_overloaded_stuff&lt;std::string&gt;;
%template(do_overloaded_stuff) ExtendMe::do_overloaded_stuff&lt;double&gt;;
</pre>
</div>
<p> The wrapped <tt>ExtendMe</tt> class will then have two (overloaded)
 methods called <tt>do_overloaded_stuff</tt>.</p>
<p><b> Compatibility Note</b>: Extending a class with template methods
 was added in version 3.0.12</p>
<p> Needless to say, SWIG's template support provides plenty of
 opportunities to break the universe. That said, an important final
 point is that<b> SWIG does not perform extensive error checking of
 templates!</b> Specifically, SWIG does not perform type checking nor
 does it check to see if the actual contents of the template declaration
 make any sense. Since the C++ compiler checks this when it compiles the
 resulting wrapper file, there is no practical reason for SWIG to
 duplicate this functionality.</p>
 <a name="SWIGPlus_template_nested_class_example"></a>
<p> As SWIG's template support does not perform type checking <tt>
%template</tt> can be used as early as after a template declaration. You
 can, and rarely have to, use <tt>%template</tt> before the template
 parameters have been declared. For example:</p>
<div class="code">
<pre>
template &lt;class T&gt; class OuterTemplateClass {};

// The nested class OuterClass::InnerClass inherits from the class template
// OuterTemplateClass&lt;OuterClass::InnerStruct&gt; and thus the template needs
// to be expanded with %template before the OuterClass declaration.
%template(OuterTemplateClass_OuterClass__InnerStruct)
  OuterTemplateClass&lt;OuterClass::InnerStruct&gt;


// Don't forget to use %feature(&quot;flatnested&quot;) for OuterClass::InnerStruct and
// OuterClass::InnerClass if the target language doesn't support nested classes.
class OuterClass {
  public:
    // Forward declarations:
    struct InnerStruct;
    class InnerClass;
};

struct OuterClass::InnerStruct {};

// Expanding the template at this point with %template is too late as the
// OuterClass::InnerClass declaration is processed inside OuterClass.

class OuterClass::InnerClass : public OuterTemplateClass&lt;InnerStruct&gt; {};
</pre>
</div>
<p><b> Compatibility Note</b>: The first implementation of template
 support relied heavily on macro expansion in the preprocessor.
 Templates have been more tightly integrated into the parser and type
 system in SWIG-1.3.12 and the preprocessor is no longer used. Code that
 relied on preprocessing features in template expansion will no longer
 work. However, SWIG still allows the # operator to be used to generate
 a string from a template argument.</p>
<p><b> Compatibility Note</b>: In earlier versions of SWIG, the <tt>
%template</tt> directive introduced a new class name. This name could
 then be used with other directives. For example:</p>
<div class="code">
<pre>
%template(vectori) vector&lt;int&gt;;
%extend vectori {
  void somemethod() { }
};
</pre>
</div>
<p> This behavior is no longer supported. Instead, you should use the
 original template name as the class name. For example:</p>
<div class="code">
<pre>
%template(vectori) vector&lt;int&gt;;
%extend vector&lt;int&gt; {
  void somemethod() { }
};
</pre>
</div>
<p> Similar changes apply to typemaps and other customization features.</p>
<h2><a name="SWIGPlus_namespaces">6.19 Namespaces</a></h2>
<p> Support for C++ namespaces is comprehensive, but by default simple,
 however, some target languages can turn on more advanced namespace
 support via the <a href="#SWIGPlus_nspace">nspace feature</a>,
 described later. Code within unnamed namespaces is ignored as there is
 no external access to symbols declared within the unnamed namespace.
 Before detailing the default implementation for named namespaces, it is
 worth noting that the semantics of C++ namespaces is extremely
 non-trivial--especially with regard to the C++ type system and class
 machinery. At a most basic level, namespaces are sometimes used to
 encapsulate common functionality. For example:</p>
<div class="code">
<pre>
namespace math {
  double sin(double);
  double cos(double);

  class Complex {
    double im, re;
  public:
    ...
  };
  ...
};
</pre>
</div>
<p> Members of the namespace are accessed in C++ by prepending the
 namespace prefix to names. For example:</p>
<div class="code">
<pre>
double x = math::sin(1.0);
double magnitude(math::Complex *c);
math::Complex c;
...
</pre>
</div>
<p> At this level, namespaces are relatively easy to manage. However,
 things start to get very ugly when you throw in the other ways a
 namespace can be used. For example, selective symbols can be exported
 from a namespace with <tt>using</tt>.</p>
<div class="code">
<pre>
using math::Complex;
double magnitude(Complex *c);       // Namespace prefix stripped
</pre>
</div>
<p> Similarly, the contents of an entire namespace can be made available
 like this:</p>
<div class="code">
<pre>
using namespace math;
double x = sin(1.0);
double magnitude(Complex *c);
</pre>
</div>
<p> Alternatively, a namespace can be aliased:</p>
<div class="code">
<pre>
namespace M = math;
double x = M::sin(1.0);
double magnitude(M::Complex *c);
</pre>
</div>
<p> Using combinations of these features, it is possible to write
 head-exploding code like this:</p>
<div class="code">
<pre>
namespace A {
  class Foo {
  };
}

namespace B {
  namespace C {
    using namespace A;
  }
  typedef C::Foo FooClass;
}

namespace BIGB = B;

namespace D {
  using BIGB::FooClass;
  class Bar : public FooClass {
  }
};

class Spam : public D::Bar {
};

void evil(A::Foo *a, B::FooClass *b, B::C::Foo *c, BIGB::FooClass *d,
          BIGB::C::Foo *e, D::FooClass *f);

</pre>
</div>
<p> Given the possibility for such perversion, it's hard to imagine how
 every C++ programmer might want such code wrapped into the target
 language. Clearly this code defines three different classes. However,
 one of those classes is accessible under at least six different names!</p>
<p> SWIG fully supports C++ namespaces in its internal type system and
 class handling code. If you feed SWIG the above code, it will be parsed
 correctly, it will generate compilable wrapper code, and it will
 produce a working scripting language module. However, the default
 wrapping behavior is to flatten namespaces in the target language. This
 means that the contents of all namespaces are merged together in the
 resulting scripting language module. For example, if you have code like
 this,</p>
<div class="code">
<pre>
%module foo
namespace foo {
  void bar(int);
  void spam();
}

namespace bar {
  void blah();
}

</pre>
</div>
<p> then SWIG simply creates three wrapper functions <tt>bar()</tt>, <tt>
spam()</tt>, and <tt>blah()</tt> in the target language. SWIG does not
 prepend the names with a namespace prefix nor are the functions
 packaged in any kind of nested scope. Note that the default handling of
 flattening all the namespace scopes in the target language can be
 changed via the <a href="#SWIGPlus_nspace">nspace feature</a>.</p>
<p> There is some rationale for taking this approach. Since C++
 namespaces are often used to define modules in C++, there is a natural
 correlation between the likely contents of a SWIG module and the
 contents of a namespace. For instance, it would not be unreasonable to
 assume that a programmer might make a separate extension module for
 each C++ namespace. In this case, it would be redundant to prepend
 everything with an additional namespace prefix when the module itself
 already serves as a namespace in the target language. Or put another
 way, if you want SWIG to keep namespaces separate, simply wrap each
 namespace with its own SWIG interface.</p>
<p> Because namespaces are flattened, it is possible for symbols defined
 in different namespaces to generate a name conflict in the target
 language. For example:</p>
<div class="code">
<pre>
namespace A {
  void foo(int);
}
namespace B {
  void foo(double);
}
</pre>
</div>
<p> When this conflict occurs, you will get an error message that
 resembles this:</p>
<div class="shell">
<pre>
example.i:26. Error. 'foo' is multiply defined in the generated target language module.
example.i:23. Previous declaration of 'foo'
</pre>
</div>
<p> To resolve this error, simply use <tt>%rename</tt> to disambiguate
 the declarations. For example:</p>
<div class="code">
<pre>
%rename(B_foo) B::foo;
...
namespace A {
  void foo(int);
}
namespace B {
  void foo(double);     // Gets renamed to B_foo
}
</pre>
</div>
<p> Similarly, <tt>%ignore</tt> can be used to ignore declarations.</p>
<p> <tt>using</tt> declarations do not have any effect on the generated
 wrapper code. They are ignored by SWIG language modules and they do not
 result in any code. However, these declarations<em> are</em> used by
 the internal type system to track type-names. Therefore, if you have
 code like this:</p>
<div class="code">
<pre>
namespace A {
  typedef int Integer;
}
using namespace A;
void foo(Integer x);
</pre>
</div>
<p> SWIG knows that <tt>Integer</tt> is the same as <tt>A::Integer</tt>
 which is the same as <tt>int</tt>.</p>
<p> Namespaces may be combined with templates. If necessary, the <tt>
%template</tt> directive can be used to expand a template defined in a
 different namespace. For example:</p>
<div class="code">
<pre>
namespace foo {
  template&lt;typename T&gt; T max(T a, T b) { return a &gt; b ? a : b; }
}

using foo::max;

%template(maxint)   max&lt;int&gt;;           // Okay.
%template(maxfloat) foo::max&lt;float&gt;;    // Okay (qualified name).

namespace bar {
  using namespace foo;
  %template(maxdouble)  max&lt;double&gt;;    // Okay.
}
</pre>
</div>
<p> The combination of namespaces and other SWIG directives may
 introduce subtle scope-related problems. The key thing to keep in mind
 is that all SWIG generated wrappers are produced in the<em> global</em>
 namespace. Symbols from other namespaces are always accessed using
 fully qualified names---names are never imported into the global space
 unless the interface happens to do so with a <tt>using</tt>
 declaration. In almost all cases, SWIG adjusts typenames and symbols to
 be fully qualified. However, this is not done in code fragments such as
 function bodies, typemaps, exception handlers, and so forth. For
 example, consider the following:</p>
<div class="code">
<pre>
namespace foo {
  typedef int Integer;
  class bar {
    public:
    ...
  };
}

%extend foo::bar {
  Integer add(Integer x, Integer y) {
    Integer r = x + y;        // Error. Integer not defined in this scope
    return r;
  }
};
</pre>
</div>
<p> In this case, SWIG correctly resolves the added method parameters
 and return type to <tt>foo::Integer</tt>. However, since function
 bodies aren't parsed and such code is emitted in the global namespace,
 this code produces a compiler error about <tt>Integer</tt>. To fix the
 problem, make sure you use fully qualified names. For example:</p>
<div class="code">
<pre>
%extend foo::bar {
  Integer add(Integer x, Integer y) {
    foo::Integer r = x + y;        // Ok.
    return r;
  }
};
</pre>
</div>
<p><b> Note:</b> SWIG does<em> not</em> propagate <tt>using</tt>
 declarations to the resulting wrapper code. If these declarations
 appear in an interface, they should<em> also</em> appear in any header
 files that might have been included in a <tt>%{ ... %}</tt> section. In
 other words, don't insert extra <tt>using</tt> declarations into a SWIG
 interface unless they also appear in the underlying C++ code.</p>
<p><b> Note:</b> Code inclusion directives such as <tt>%{ ... %}</tt> or
 <tt>%inline %{ ... %}</tt> should not be placed inside a namespace
 declaration. The code emitted by these directives will not be enclosed
 in a namespace and you may get very strange results. If you need to use
 namespaces with these directives, consider the following:</p>
<div class="code">
<pre>
// Good version
%inline %{
namespace foo {
  void bar(int) { ... }
  ...
}
%}

// Bad version.  Emitted code not placed in namespace.
namespace foo {
%inline %{
  void bar(int) { ... }   /* I'm bad */
  ...
  %}
}
</pre>
</div>
<p><b> Note:</b> When the <tt>%extend</tt> directive is used inside a
 namespace, the namespace name is included in the generated functions.
 For example, if you have code like this,</p>
<div class="code">
<pre>
namespace foo {
  class bar {
    public:
      %extend {
        int blah(int x);
      };
  };
}
</pre>
</div>
<p> the added method <tt>blah()</tt> is mapped to a function <tt>int
 foo_bar_blah(foo::bar *self, int x)</tt>. This function resides in the
 global namespace.</p>
<p><b> Note:</b> Although namespaces are flattened in the target
 language, the SWIG generated wrapper code observes the same namespace
 conventions as used in the input file. Thus, if there are no symbol
 conflicts in the input, there will be no conflicts in the generated
 code.</p>
<p><b> Note:</b> In the same way that no resolution is performed on
 parameters, a conversion operator name must match exactly to how it is
 defined. Do not change the qualification of the operator. For example,
 suppose you had an interface like this:</p>
<div class="code">
<pre>
namespace foo {
  class bar;
  class spam {
    public:
    ...
    operator bar();      // Conversion of spam -&gt; bar
    ...
  };
}
</pre>
</div>
<p> The following is how the feature is expected to be written for a
 successful match:</p>
<div class="code">
<pre>
%rename(tofoo) foo::spam::operator bar();
</pre>
</div>
<p> The following does not work as no namespace resolution is performed
 in the matching of conversion operator names:</p>
<div class="code">
<pre>
%rename(tofoo) foo::spam::operator <b>foo::</b>bar();
</pre>
</div>
<p> Note, however, that if the operator is defined using a qualifier in
 its name, then the feature must use it too...</p>
<div class="code">
<pre>
%rename(tofoo) foo::spam::operator bar();      // will not match
%rename(tofoo) foo::spam::operator foo::bar(); // will match
namespace foo {
  class bar;
  class spam {
    public:
    ...
    operator foo::bar();
    ...
  };
}
</pre>
</div>
<p><b> Compatibility Note:</b> Versions of SWIG prior to 1.3.32 were
 inconsistent in this approach. A fully qualified name was usually
 required, but would not work in some situations.</p>
<p><b> Note:</b> The flattening of namespaces is only intended to serve
 as a basic namespace implementation. More advanced handling of
 namespaces is discussed next.</p>
<h3><a name="SWIGPlus_nspace">6.19.1 The nspace feature for namespaces</a>
</h3>
<p> Some target languages provide support for the <tt>nspace</tt> <a href="#Customization_features">
feature</a>. The feature can be applied to any class, struct, union or
 enum declared within a named namespace. The feature wraps the type
 within the target language specific concept of a namespace, for
 example, a Java package or C# namespace. Please see the language
 specific sections to see if the target language you are interested in
 supports the nspace feature.</p>
<p> The feature is demonstrated below for C# using the following
 example:</p>
<div class="code">
<pre>
%feature(&quot;nspace&quot;) MyWorld::Material::Color;
%nspace MyWorld::Wrapping::Color; // %nspace is a macro for %feature(&quot;nspace&quot;)

namespace MyWorld {
  namespace Material {
    class Color {
    ...
    };
  }
  namespace Wrapping {
    class Color {
    ...
    };
  }
}
</pre>
</div>
<p> Without the <tt>nspace</tt> feature directives above or <tt>%rename</tt>
, you would get the following warning resulting in just one of the <tt>
Color</tt> classes being available for use from the target language:</p>
<div class="shell">
<pre>
example.i:9: Error: 'Color' is multiply defined in the generated target language module.
example.i:5: Error: Previous declaration of 'Color'
</pre>
</div>
<p> With the <tt>nspace</tt> feature the two <tt>Color</tt> classes are
 wrapped into the equivalent C# namespaces. A fully qualified
 constructor call of each these two types in C# is then:</p>
<div class="targetlang">
<pre>
MyWorld.Material.Color materialColor = new MyWorld.Material.Color();
MyWorld.Wrapping.Color wrappingColor = new MyWorld.Wrapping.Color();
</pre>
</div>
<p> Note that the <tt>nspace</tt> feature does not apply to variables
 and functions simply declared in a namespace. For example, the
 following symbols cannot co-exist in the target language without
 renaming. This may change in a future version.</p>
<div class="code">
<pre>
namespace MyWorld {
  namespace Material {
    int quantity;
    void dispatch();
  }
  namespace Wrapping {
    int quantity;
    void dispatch();
  }
}
</pre>
</div>
<p><b> Compatibility Note:</b> The nspace feature was first introduced
 in SWIG-2.0.0.</p>
<h2><a name="SWIGPlus_renaming_templated_types_namespaces">6.20 Renaming
 templated types in namespaces</a></h2>
<p> As has been mentioned, when %rename includes parameters, the
 parameter types must match exactly (no typedef or namespace resolution
 is performed). SWIG treats templated types slightly differently and has
 an additional matching rule so unlike non-templated types, an exact
 match is not always required. If the fully qualified templated type is
 specified, it will have a higher precedence over the generic template
 type. In the example below, the generic template type is used to rename
 to <tt>bbb</tt> and the fully qualified type is used to rename to <tt>
ccc</tt>.</p>
<div class="code">
<pre>
%rename(bbb) Space::ABC::aaa(T t);                     // will match but with lower precedence than ccc
%rename(ccc) Space::ABC&lt;Space::XYZ&gt;::aaa(Space::XYZ t);// will match but with higher precedence
                                                       // than bbb

namespace Space {
  class XYZ {};
  template&lt;typename T&gt; struct ABC {
    void aaa(T t) {}
  };
}
%template(ABCXYZ) Space::ABC&lt;Space::XYZ&gt;;
</pre>
</div>
<p> It should now be apparent that there are many ways to achieve a
 renaming with %rename. This is demonstrated by the following two
 examples, which are effectively the same as the above example. Below
 shows how %rename can be placed inside a namespace.</p>
<div class="code">
<pre>
namespace Space {
  %rename(bbb) ABC::aaa(T t);                     // will match but with lower precedence than ccc
  %rename(ccc) ABC&lt;Space::XYZ&gt;::aaa(Space::XYZ t);// will match but with higher precedence than bbb
  %rename(ddd) ABC&lt;Space::XYZ&gt;::aaa(XYZ t);       // will not match
}

namespace Space {
  class XYZ {};
  template&lt;typename T&gt; struct ABC {
    void aaa(T t) {}
  };
}
%template(ABCXYZ) Space::ABC&lt;Space::XYZ&gt;;
</pre>
</div>
<p> Note that <tt>ddd</tt> does not match as there is no namespace
 resolution for parameter types and the fully qualified type must be
 specified for template type expansion. The following example shows how
 %rename can be placed within %extend.</p>
<div class="code">
<pre>
namespace Space {
  %extend ABC {
    %rename(bbb) aaa(T t);         // will match but with lower precedence than ccc
  }
  %extend ABC&lt;Space::XYZ&gt; {
    %rename(ccc) aaa(Space::XYZ t);// will match but with higher precedence than bbb
    %rename(ddd) aaa(XYZ t);       // will not match
  }
}

namespace Space {
  class XYZ {};
  template&lt;typename T&gt; struct ABC {
    void aaa(T t) {}
  };
}
%template(ABCXYZ) Space::ABC&lt;Space::XYZ&gt;;
</pre>
</div>
<h2><a name="SWIGPlus_exception_specifications">6.21 Exception
 specifications</a></h2>
<p> When C++ programs utilize exceptions, exceptional behavior is
 sometimes specified as part of a function or method declaration. For
 example:</p>
<div class="code">
<pre>
class Error { };

class Foo {
public:
  ...
  void blah() throw(Error);
  ...
};
</pre>
</div>
<p> If an exception specification is used, SWIG automatically generates
 wrapper code for catching the indicated exception and, when possible,
 rethrowing it into the target language, or converting it into an error
 in the target language otherwise. For example, in Python, you can write
 code like this:</p>
<div class="targetlang">
<pre>
f = Foo()
try:
    f.blah()
except Error, e:
    # e is a wrapped instance of &quot;Error&quot;
</pre>
</div>
<p> Details of how to tailor code for handling the caught C++ exception
 and converting it into the target language's exception/error handling
 mechanism is outlined in the <a href="#Typemaps_throws_typemap">
&quot;throws&quot; typemap</a> section.</p>
<p> Since exception specifications are sometimes only used sparingly,
 this alone may not be enough to properly handle C++ exceptions. To do
 that, a different set of special SWIG directives are used. Consult the
 &quot;<a href="#Customization_exception">Exception handling with %exception</a>
&quot; section for details. The next section details a way of simulating an
 exception specification or replacing an existing one.</p>
<h2><a name="SWIGPlus_catches">6.22 Exception handling with %catches</a></h2>
<p> Exceptions are automatically handled for methods with an exception
 specification. Similar handling can be achieved for methods without
 exception specifications through the <tt>%catches</tt> feature. It is
 also possible to replace any declared exception specification using the
 <tt>%catches</tt> feature. In fact, <tt>%catches</tt> uses the same <a href="#Typemaps_throws_typemap">
&quot;throws&quot; typemaps</a> that SWIG uses for exception specifications in
 handling exceptions. The <tt>%catches</tt> feature must contain a list
 of possible types that can be thrown. For each type that is in the
 list, SWIG will generate a catch handler, in the same way that it would
 for types declared in the exception specification. Note that the list
 can also include the catch all specification &quot;...&quot;. For example,</p>
<div class="code">
<pre>
struct EBase { virtual ~EBase(); };
struct Error1 : EBase { };
struct Error2 : EBase { };
struct Error3 : EBase { };
struct Error4 : EBase { };

%catches(Error1, Error2, ...) Foo::bar();
%catches(EBase) Foo::blah();

class Foo {
public:
  ...
  void bar();
  void blah() throw(Error1, Error2, Error3, Error4);
  ...
};
</pre>
</div>
<p> For the <tt>Foo::bar()</tt> method, which can throw anything, SWIG
 will generate catch handlers for <tt>Error1</tt>, <tt>Error2</tt> as
 well as a catch all handler (...). Each catch handler will convert the
 caught exception and convert it into a target language error/exception.
 The catch all handler will convert the caught exception into an unknown
 error/exception.</p>
<p> Without the <tt>%catches</tt> feature being attached to <tt>
Foo::blah()</tt>, SWIG will generate catch handlers for all of the types
 in the exception specification, that is, <tt>Error1, Error2, Error3,
 Error4</tt>. However, with the <tt>%catches</tt> feature above, just a
 single catch handler for the base class, <tt>EBase</tt> will be
 generated to convert the C++ exception into a target language
 error/exception.</p>
<h2><a name="SWIGPlus_nn33">6.23 Pointers to Members</a></h2>
<p> Starting with SWIG-1.3.7, there is limited parsing support for
 pointers to C++ class members. For example:</p>
<div class="code">
<pre>
double do_op(Object *o, double (Object::*callback)(double, double));
extern double (Object::*fooptr)(double, double);
%constant double (Object::*FOO)(double, double) = &amp;Object::foo;
</pre>
</div>
<p> Although these kinds of pointers can be parsed and represented by
 the SWIG type system, few language modules know how to handle them due
 to implementation differences from standard C pointers. Readers are<em>
 strongly</em> advised to consult an advanced text such as the &quot;The
 Annotated C++ Manual&quot; for specific details.</p>
<p> When pointers to members are supported, the pointer value might
 appear as a special string like this:</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; print example.FOO
_ff0d54a800000000_m_Object__f_double_double__double
&gt;&gt;&gt;
</pre>
</div>
<p> In this case, the hexadecimal digits represent the entire value of
 the pointer which is usually the contents of a small C++ structure on
 most machines.</p>
<p> SWIG's type-checking mechanism is also more limited when working
 with member pointers. Normally SWIG tries to keep track of inheritance
 when checking types. However, no such support is currently provided for
 member pointers.</p>
<h2><a name="SWIGPlus_smart_pointers">6.24 Smart pointers and
 operator-&gt;()</a></h2>
<p> In some C++ programs, objects are often encapsulated by
 smart-pointers or proxy classes. This is sometimes done to implement
 automatic memory management (reference counting) or persistence.
 Typically a smart-pointer is defined by a class template where the <tt>
-&gt;</tt> operator has been overloaded. This class is then wrapped around
 some other class. For example:</p>
<div class="code">
<pre>
// Smart-pointer class
template&lt;class T&gt; class SmartPtr {
  T *pointee;
public:
  SmartPtr(T *p) : pointee(p) { ... }
  T *operator-&gt;() {
    return pointee;
  }
  ...
};

// Ordinary class
class Foo_Impl {
public:
  int x;
  virtual void bar();
  ...
};

// Smart-pointer wrapper
typedef SmartPtr&lt;Foo_Impl&gt; Foo;

// Create smart pointer Foo
Foo make_Foo() {
  return SmartPtr&lt;Foo_Impl&gt;(new Foo_Impl());
}

// Do something with smart pointer Foo
void do_something(Foo f) {
  printf(&quot;x = %d\n&quot;, f-&gt;x);
  f-&gt;bar();
}

// Call the wrapped smart pointer proxy class in the target language 'Foo'
%template(Foo) SmartPtr&lt;Foo_Impl&gt;;
</pre>
</div>
<p> A key feature of this approach is that by defining <tt>operator-&gt;</tt>
 the methods and attributes of the object wrapped by a smart pointer are
 transparently accessible. For example, expressions such as these (from
 the previous example),</p>
<div class="code">
<pre>
f-&gt;x
f-&gt;bar()
</pre>
</div>
<p> are transparently mapped to the following</p>
<div class="code">
<pre>
(f.operator-&gt;())-&gt;x;
(f.operator-&gt;())-&gt;bar();
</pre>
</div>
<p> When generating wrappers, SWIG tries to emulate this functionality
 to the extent that it is possible. To do this, whenever <tt>
operator-&gt;()</tt> is encountered in a class, SWIG looks at its returned
 type and uses it to generate wrappers for accessing attributes of the
 underlying object. For example, wrapping the above code produces
 wrappers like this:</p>
<div class="code">
<pre>
int Foo_x_get(Foo *f) {
  return (*f)-&gt;x;
}
void Foo_x_set(Foo *f, int value) {
  (*f)-&gt;x = value;
}
void Foo_bar(Foo *f) {
  (*f)-&gt;bar();
}
</pre>
</div>
<p> These wrappers take a smart-pointer instance as an argument, but
 dereference it in a way to gain access to the object returned by <tt>
operator-&gt;()</tt>. You should carefully compare these wrappers to those
 in the first part of this chapter (they are slightly different).</p>
<p> The end result is that access looks very similar to C++. For
 example, you could do this in Python:</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; f = make_Foo()
&gt;&gt;&gt; print f.x
0
&gt;&gt;&gt; f.bar()
&gt;&gt;&gt;
</pre>
</div>
<p> When generating wrappers through a smart-pointer, SWIG tries to
 generate wrappers for all methods and attributes that might be
 accessible through <tt>operator-&gt;()</tt>. This includes any methods
 that might be accessible through inheritance. However, there are a
 number of restrictions:</p>
<ul>
<li>Member variables and methods are wrapped through a smart pointer.
 Enumerations, constructors, and destructors are not wrapped.</li>
<li>
<p>If the smart-pointer class and the underlying object both define a
 method or variable of the same name, then the smart-pointer version has
 precedence. For example, if you have this code</p>
<div class="code">
<pre>
class Foo {
public:
  int x;
};

class Bar {
public:
  int x;       
  Foo *operator-&gt;();
};
</pre>
</div>
<p> then the wrapper for <tt>Bar::x</tt> accesses the <tt>x</tt> defined
 in <tt>Bar</tt>, and not the <tt>x</tt> defined in <tt>Foo</tt>.</p>
</li>
</ul>
<p> If your intent is to only expose the smart-pointer class in the
 interface, it is not necessary to wrap both the smart-pointer class and
 the class for the underlying object. However, you must still tell SWIG
 about both classes if you want the technique described in this section
 to work. To only generate wrappers for the smart-pointer class, you can
 use the %ignore directive. For example:</p>
<div class="code">
<pre>
%ignore Foo;
class Foo {       // Ignored
};

class Bar {
public:
  Foo *operator-&gt;();
  ...
};
</pre>
</div>
<p> Alternatively, you can import the definition of <tt>Foo</tt> from a
 separate file using <tt>%import</tt>.</p>
<p><b> Note:</b> When a class defines <tt>operator-&gt;()</tt>, the
 operator itself is wrapped as a method <tt>__deref__()</tt>. For
 example:</p>
<div class="targetlang">
<pre>
f = Foo()               # Smart-pointer
p = f.__deref__()       # Raw pointer from operator-&gt;
</pre>
</div>
<p><b> Note:</b> To disable the smart-pointer behavior, use <tt>%ignore</tt>
 to ignore <tt>operator-&gt;()</tt>. For example:</p>
<div class="code">
<pre>
%ignore Bar::operator-&gt;;
</pre>
</div>
<p><b> Note:</b> Smart pointer support was first added in SWIG-1.3.14.</p>
<h2><a name="SWIGPlus_ref_unref">6.25 C++ reference counted objects -
 ref/unref feature</a></h2>
<p> Another similar idiom in C++ is the use of reference counted
 objects. Consider for example:</p>
<div class="code">
<pre>
class RCObj  {
  // implement the ref counting mechanism
  int add_ref();
  int del_ref();
  int ref_count();

public:
  virtual ~RCObj() = 0;

  int ref() const {
    return add_ref();
  }

  int unref() const {
    if (ref_count() == 0 || del_ref() == 0 ) {
      delete this;
      return 0;
    }
    return ref_count();
  }
};


class A : RCObj {
public:
  A();
  int foo();
};


class B {
  A *_a;

public:
  B(A *a) : _a(a) { 
    a-&gt;ref(); 
  }

  ~B() { 
    a-&gt;unref(); 
  }
};

int main() {
  A *a  = new A();       // (count: 0)
  a-&gt;ref();           // 'a' ref here (count: 1)

  B *b1 = new B(a);   // 'a' ref here (count: 2)
  if (1 + 1 == 2) {
    B *b2 = new B(a); // 'a' ref here (count: 3)
    delete b2;        // 'a' unref, but not deleted (count: 2)
  }

  delete b1;          // 'a' unref, but not deleted (count: 1)
  a-&gt;unref();         // 'a' unref and deleted (count: 0)
}
</pre>
</div>
<p> In the example above, the 'A' class instance 'a' is a reference
 counted object, which can't be deleted arbitrarily since it is shared
 between the objects 'b1' and 'b2'. 'A' is derived from a<i> Reference
 Counted Object</i> 'RCObj', which implements the ref/unref idiom.</p>
<p> To tell SWIG that 'RCObj' and all its derived classes are reference
 counted objects, use the &quot;ref&quot; and &quot;unref&quot; <a href="#Customization_features">
features</a>. These are also available as <tt>%refobject</tt> and <tt>
%unrefobject</tt>, respectively. For example:</p>
<div class="code">
<pre>
%module example
...

%feature(&quot;ref&quot;)   RCObj &quot;$this-&gt;ref();&quot;
%feature(&quot;unref&quot;) RCObj &quot;$this-&gt;unref();&quot;

%include &quot;rcobj.h&quot;
%include &quot;A.h&quot;
...
</pre>
</div>
<p> where the code passed to the &quot;ref&quot; and &quot;unref&quot; features will be
 executed as needed whenever a new object is passed to Python, or when
 Python tries to release the proxy object instance, respectively.</p>
<p> On the Python side, the use of a reference counted object is no
 different to any other regular instance:</p>
<div class="targetlang">
<pre>
def create_A():
    a = A()         # SWIG ref 'a' - new object is passed to Python (count: 1)
    b1 = B(a)       # C++ ref 'a (count: 2)
    if 1 + 1 == 2:
        b2 = B(a)   # C++ ref 'a' (count: 3)
    return a        # 'b1' and 'b2' are released and deleted, C++ unref 'a' twice (count: 1)

a = create_A()      # (count: 1)
exit                # 'a' is released, SWIG unref 'a' called in the destructor wrapper (count: 0)
</pre>
</div>
<p> Note that the user doesn't explicitly need to call 'a-&gt;ref()' nor
 'a-&gt;unref()' (and neither 'delete a'). Instead, SWIG takes cares of
 executing the &quot;ref&quot; and &quot;unref&quot; calls as needed. If the user doesn't
 specify the &quot;ref/unref&quot; feature for a type, SWIG will produce code
 equivalent to defining these features:</p>
<div class="code">
<pre>
%feature(&quot;ref&quot;)   &quot;&quot;
%feature(&quot;unref&quot;) &quot;delete $this;&quot;
</pre>
</div>
<p> In other words, SWIG will not do anything special when a new object
 is passed to Python, and it will always 'delete' the underlying object
 when Python releases the proxy instance.</p>
<p> The <a href="#Customization_ownership">%newobject feature</a> is
 designed to indicate to the target language that it should take
 ownership of the returned object. When used in conjunction with a type
 that has the &quot;ref&quot; feature associated with it, it additionally emits
 the code in the &quot;ref&quot; feature into the C++ wrapper. Consider wrapping
 the following factory function in addition to the above:</p>
<div class="code">
<pre>
%newobject AFactory;
A *AFactory() {
  return new A();
}
</pre>
</div>
<p> The <tt>AFactory</tt> function now acts much like a call to the <tt>
A</tt> constructor with respect to memory handling:</p>
<div class="targetlang">
<pre>
a = AFactory()    # SWIG ref 'a' due to %newobject (count: 1)
exit              # 'a' is released, SWIG unref 'a' called in the destructor wrapper (count: 0)
</pre>
</div>
<h2><a name="SWIGPlus_nn35">6.26 Using declarations and inheritance</a></h2>
<p> <tt>using</tt> declarations are sometimes used to adjust access to
 members of base classes. For example:</p>
<div class="code">
<pre>
class Foo {
public:
  int  blah(int x);
};

class Bar {
public:
  double blah(double x);
};

class FooBar : public Foo, public Bar {
public:
  using Foo::blah;
  using Bar::blah;
  char *blah(const char *x);
};
</pre>
</div>
<p> In this example, the <tt>using</tt> declarations make different
 versions of the overloaded <tt>blah()</tt> method accessible from the
 derived class. For example:</p>
<div class="code">
<pre>
FooBar *f;
f-&gt;blah(3);         // Ok. Invokes Foo::blah(int)
f-&gt;blah(3.5);       // Ok. Invokes Bar::blah(double)
f-&gt;blah(&quot;hello&quot;);   // Ok. Invokes FooBar::blah(const char *);
</pre>
</div>
<p> SWIG emulates the same functionality when creating wrappers. For
 example, if you wrap this code in Python, the module works just like
 you would expect:</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; import example
&gt;&gt;&gt; f = example.FooBar()
&gt;&gt;&gt; f.blah(3)
&gt;&gt;&gt; f.blah(3.5)
&gt;&gt;&gt; f.blah(&quot;hello&quot;)
</pre>
</div>
<p> <tt>using</tt> declarations can also be used to change access when
 applicable. For example:</p>
<div class="code">
<pre>
class Foo {
protected:
  int x;
  int blah(int x);
};

class Bar : public Foo {
public:
  using Foo::x;       // Make x public
  using Foo::blah;    // Make blah public
};
</pre>
</div>
<p> This also works in SWIG---the exposed declarations will be wrapped
 normally.</p>
<p> When <tt>using</tt> declarations are used as shown in these
 examples, declarations from the base classes are copied into the
 derived class and wrapped normally. When copied, the declarations
 retain any properties that might have been attached using <tt>%rename</tt>
, <tt>%ignore</tt>, or <tt>%feature</tt>. Thus, if a method is ignored
 in a base class, it will also be ignored by a <tt>using</tt>
 declaration.</p>
<p> Because a <tt>using</tt> declaration does not provide fine-grained
 control over the declarations that get imported, it may be difficult to
 manage such declarations in applications that make heavy use of SWIG
 customization features. If you can't get <tt>using</tt> to work
 correctly, you can always change the interface to the following:</p>
<div class="code">
<pre>

class FooBar : public Foo, public Bar {
public:
#ifndef SWIG
  using Foo::blah;
  using Bar::blah;
#else
  int blah(int x);         // explicitly tell SWIG about other declarations
  double blah(double x);
#endif

  char *blah(const char *x);
};
</pre>
</div>
<p><b> Notes:</b></p>
<ul>
<li>
<p>If a derived class redefines a method defined in a base class, then a
 <tt>using</tt> declaration won't cause a conflict. For example:</p>
<div class="code">
<pre>
class Foo {
public:
  int blah(int );
  double blah(double);
};

class Bar : public Foo {
public:
  using Foo::blah;    // Only imports blah(double);
  int blah(int);
};
</pre>
</div></li>
<li>
<p>Resolving ambiguity in overloading may prevent declarations from
 being imported by <tt>using</tt>. For example:</p>
<div class="code">
<pre>
%rename(blah_long) Foo::blah(long);
class Foo {
public:
  int blah(int);
  long blah(long);  // Renamed to blah_long
};

class Bar : public Foo {
public:
  using Foo::blah;     // Only imports blah(int)
  double blah(double x);
};
</pre>
</div></li>
</ul>
<h2><a name="SWIGPlus_nested_classes">6.27 Nested classes</a></h2>
<p> If the target language supports the nested classes concept (like
 Java), the nested C++ classes are wrapped as nested target language
 proxy classes. (In case of Java - &quot;static&quot; nested classes.) Only public
 nested classes are wrapped. Otherwise there is little difference
 between nested and normal classes.</p>
<p> If the target language doesn't support nested classes directly, or
 the support is not implemented in the language module (like for Python
 currently), then the visible nested classes are moved to the same name
 space as the containing class (nesting hierarchy is &quot;flattened&quot;). The
 same behaviour may be turned on for C# and Java by the %feature
 (&quot;flatnested&quot;); If there is a class with the same name in the outer
 namespace the inner class (or the global one) may be renamed or
 ignored:</p>
<div class="code">
<pre>
%rename (Bar_Foo) Bar::Foo;
class Foo {};
class Bar {
  public:
  class Foo {};
};
</pre>
</div>
<p> If a nested class, within an outer class, has to be used as a
 template parameter within the outer class, then the template will have
 to be instantiated with <tt>%template</tt> before the beginning of the
 outer class. An example can be found in the <a href="#SWIGPlus_template_nested_class_example">
Templates</a> section.</p>
<p><b> Compatibility Note:</b> Prior to SWIG-3.0.0, there was limited
 nested class support. Nested classes were treated as opaque pointers.
 However, there was a workaround for nested class support in these older
 versions requiring the user to replicate the nested class in the global
 scope, adding in a typedef for the nested class in the global scope and
 using the &quot;nestedworkaround&quot; feature on the nested class. This resulted
 in approximately the same behaviour as the &quot;flatnested&quot; feature. With
 proper nested class support now available in SWIG-3.0.0, this feature
 has been deprecated and no longer works requiring code changes. If you
 see the following warning:</p>
<div class="shell">
<pre>
example.i:8: Warning 126: The nestedworkaround feature is deprecated
</pre>
</div>
<p> consider using the &quot;flatnested&quot; feature discussed above which
 generates a non-nested proxy class, like the &quot;nestedworkaround&quot; feature
 did. Alternatively, use the default nested class code generation, which
 may generate an equivalent to a nested proxy class in the target
 language, depending on the target language support.</p>
<p> SWIG-1.3.40 and earlier versions did not have the <tt>
nestedworkaround</tt> feature and the generated code resulting from
 parsing nested classes did not always compile. Nested class warnings
 could also not be suppressed using %warnfilter.</p>
<h2><a name="SWIGPlus_const">6.28 A brief rant about const-correctness</a>
</h2>
<p> A common issue when working with C++ programs is dealing with all
 possible ways in which the <tt>const</tt> qualifier (or lack thereof)
 will break your program, all programs linked against your program, and
 all programs linked against those programs.</p>
<p> Although SWIG knows how to correctly deal with <tt>const</tt> in its
 internal type system and it knows how to generate wrappers that are
 free of const-related warnings, SWIG does not make any attempt to
 preserve const-correctness in the target language. Thus, it is possible
 to pass <tt>const</tt> qualified objects to non-const methods and
 functions. For example, consider the following code in C++:</p>
<div class="code">
<pre>
const Object * foo();
void bar(Object *);

...
// C++ code
void blah() {
  bar(foo());         // Error: bar discards const
};
</pre>
</div>
<p> Now, consider the behavior when wrapped into a Python module:</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; bar(foo())         # Okay
&gt;&gt;&gt; 
</pre>
</div>
<p> Although this is clearly a violation of the C++ type-system, fixing
 the problem doesn't seem to be worth the added implementation
 complexity that would be required to support it in the SWIG run-time
 type system. There are no plans to change this in future releases
 (although we'll never rule anything out entirely).</p>
<p> The bottom line is that this particular issue does not appear to be
 a problem for most SWIG projects. Of course, you might want to consider
 using another tool if maintaining constness is the most important part
 of your project.</p>
<h2><a name="SWIGPlus_target_language_callbacks">6.29 Callbacks to the
 target language</a></h2>
<p> C/C++ function pointers are often used for callbacks and this is
 discussed in the <a href="#SWIG_nn30">Pointers to functions and
 callbacks</a> section. The callback techniques described therein
 provide a way to control callbacks to a C/C++ function but not
 callbacks into the target language. The techniques described below show
 how the director feature can be used to support callbacks from C/C++ to
 the target language.</p>
<h3><a name="SWIGPlus_director_classes_introduction">6.29.1 Introduction
 to director classes</a></h3>
<p> The director feature enables the ability for a target language class
 to derive from a wrapped C++ class. The target language can override
 virtual methods of a wrapped C++ class, thereby supporting
 cross-language polymorphism. Code can 'call up' from C++ into the
 target language by simply calling a virtual method overridden in a
 derived class in the target language. The wrapped C++ classes that have
 this ability are termed 'director' classes. The director feature is
 documented individually in each target language and the reader should
 locate and read this to obtain a full understanding of directors.</p>
<h3><a name="SWIGPlus_directors_for_function_pointers">6.29.2 Using
 directors and target language callbacks</a></h3>
<p> SWIG's primary goal is to make it possible to call C/C++ code from a
 target language, however, the director feature enables the reverse.
 While there isn't simple direct support for calling target language
 code from C, the director feature makes this possible. It does require
 some work and additional wrapper code to be provided by the user. The
 additional code required must be C++ and not C code and hence may
 introduce a small dependency on C++ if using a pure C project. In a
 nutshell, the user must create a C++ base class and turn it into a
 director class. A virtual method in the director base class is
 required. SWIG generates the code to call up into the target language
 when wrapping the director virtual method.</p>
<p> Let's look at some details next. Consider the same function pointer
 for a callback called <tt>binary_op</tt> from the <a href="#SWIG_nn30">
Pointers to functions and callbacks</a> section. For completeness, the
 code required for the module and director feature is also shown:</p>
<div class="code">
<pre>
%module(directors=&quot;1&quot;) example

%{
int binary_op(int a, int b, int (*op)(int, int)) {
  return op(a, b);
}
%}
</pre>
</div>
<p> The goal is to have a target language function that gets called by <tt>
binary_op</tt>. The target language function should have the equivalent
 signature as the C/C++ function pointer <tt>int (*op)(int, int)</tt>.
 As we are using directors, we need a C++ virtual method with this
 signature, so let's define the C++ class and pure virtual method first
 and make it a director class via the director feature:</p>
<div class="code">
<pre>
%feature(&quot;director&quot;) BinaryOp;

%inline %{
struct BinaryOp {
  virtual int handle(int a, int b) = 0;
  virtual ~BinaryOp() {}
};
%}
</pre>
</div>
<p> The following <tt>handler_helper</tt> function and <tt>
binary_op_wrapper</tt> function completes the code needed in the
 C++/SWIG layer. The <tt>binary_op_wrapper</tt> function is wrapped by
 SWIG and is very similar to the <tt>binary_op</tt> function, however,
 it takes a pointer to the director base class <tt>BinaryOp</tt> instead
 of a C/C++ function pointer.</p>
<div class="code">
<pre>
%{
static BinaryOp *handler_ptr = NULL;
static int handler_helper(int a, int b) {
  // Make the call up to the target language when handler_ptr
  // is an instance of a target language director class
  return handler_ptr-&gt;handle(a, b);
}
// If desired, handler_ptr above could be changed to a thread-local variable in order to make thread-safe
%}

%inline %{
int binary_op_wrapper(int a, int b, BinaryOp *handler) {
  handler_ptr = handler;
  int result = binary_op(a, b, &amp;handler_helper);
  handler = NULL;
  return result;
}
%}
</pre>
</div>
<p> On the target language side, we need to derive a class from <tt>
BinaryOp</tt> and override the <tt>handle</tt> method. In Python this
 could be as simple as:</p>
<div class="targetlang">
<pre>
import example

# PythonBinaryOp class is defined and derived from C++ class BinaryOp
class PythonBinaryOp(example.BinaryOp):

    # Define Python class 'constructor'
    def __init__(self):
        # Call C++ base class constructor
        example.BinaryOp.__init__(self)

    # Override C++ method: virtual int handle(int a, int b) = 0;
    def handle(self, a, b):
        # Return the product
        return a * b
</pre>
</div>
<p> For this to work from Python, an instance of the <tt>PythonBinaryOp</tt>
 class is created and then passed to <tt>binary_op_wrapper</tt>. The net
 result is the <tt>binary_op</tt> function will in turn be called which
 will call <tt>handler_helper</tt> which will call the virtual <tt>
handle</tt> method, that is, the Python method <tt>handle</tt> in the
 PythonBinaryOp class. The result will be the product of 10 and 20 and
 make its way back to Python and hence 200 will be printed with the
 following code:</p>
<div class="targetlang">
<pre>
handler = PythonBinaryOp()
result = example.binary_op_wrapper(10, 20, handler)
print result
</pre>
</div>
<p> This has thus demonstrated a C/C++ function pointer calling back
 into a target language function. The code could be made a little more
 user friendly by using <tt>%rename</tt> to provide the original <tt>
binary_op</tt> name from the target language instead of <tt>
binary_op_wrapper</tt>. A C++ functor base class and Python functor
 class could also be used instead, but these are left as exercises for
 the reader.</p>
<h2><a name="SWIGPlus_nn42">6.30 Where to go for more information</a></h2>
<p> If you're wrapping serious C++ code, you might want to pick up a
 copy of &quot;The Annotated C++ Reference Manual&quot; by Ellis and Stroustrup.
 This is the reference document we use to guide a lot of SWIG's C++
 support.</p>

<!--  LocalWords:  destructors Enums Namespaces const SWIG's STL OO adaptor tcl
 -->

<!--  LocalWords:  debuggable cxx OBJS Wiki accessor nodefault makedefault
 -->

<!--  LocalWords:  notabstract CopyFoo
 -->
<HR NOSHADE>
<h1><a name="CPlusPlus11">7 SWIG and C++11</a></h1>

<!-- INDEX -->
<div class="sectiontoc">
<ul>
<li><a href="#CPlusPlus11_introduction">Introduction</a></li>
<li><a href="#CPlusPlus11_core_language_changes">Core language changes</a>
<ul>
<li><a href="#CPlusPlus11_rvalue_reference_and_move_semantics">Rvalue
 reference and move semantics</a></li>
<li><a href="#CPlusPlus11_generalized_constant_expressions">Generalized
 constant expressions</a></li>
<li><a href="#CPlusPlus11_extern_template">Extern template</a></li>
<li><a href="#CPlusPlus11_initializer_lists">Initializer lists</a></li>
<li><a href="#CPlusPlus11_uniform_initialization">Uniform initialization</a>
</li>
<li><a href="#CPlusPlus11_type_inference">Type inference</a></li>
<li><a href="#CPlusPlus11_range_based_for_loop">Range-based for-loop</a></li>
<li><a href="#CPlusPlus11_lambda_functions_and_expressions">Lambda
 functions and expressions</a></li>
<li><a href="#CPlusPlus11_alternate_function_syntax">Alternate function
 syntax</a></li>
<li><a href="#CPlusPlus11_object_construction_improvement">Object
 construction improvement</a></li>
<li><a href="#CPlusPlus11_explicit_overrides_final">Explicit overrides
 and final</a></li>
<li><a href="#CPlusPlus11_null_pointer_constant">Null pointer constant</a>
</li>
<li><a href="#CPlusPlus11_strongly_typed_enumerations">Strongly typed
 enumerations</a></li>
<li><a href="#CPlusPlus11_double_angle_brackets">Double angle brackets</a>
</li>
<li><a href="#CPlusPlus11_explicit_conversion_operators">Explicit
 conversion operators</a></li>
<li><a href="#CPlusPlus11_alias_templates">Type alias and alias
 templates</a></li>
<li><a href="#CPlusPlus11_unrestricted_unions">Unrestricted unions</a></li>
<li><a href="#CPlusPlus11_variadic_templates">Variadic templates</a></li>
<li><a href="#CPlusPlus11_new_char_literals">New character literals</a></li>
<li><a href="#CPlusPlus11_new_string_literals">New string literals</a></li>
<li><a href="#CPlusPlus11_user_defined_literals">User-defined literals</a>
</li>
<li><a href="#CPlusPlus11_thread_local_storage">Thread-local storage</a></li>
<li><a href="#CPlusPlus11_defaulted_deleted">Explicitly defaulted
 functions and deleted functions</a></li>
<li><a href="#CPlusPlus11_type_long_long_int">Type long long int</a></li>
<li><a href="#CPlusPlus11_static_assertions">Static assertions</a></li>
<li><a href="#CPlusPlus11_sizeof">Allow sizeof to work on members of
 classes without an explicit object</a></li>
<li><a href="#CPlusPlus11_noexcept">Exception specifications and
 noexcept</a></li>
<li><a href="#CPlusPlus11_alignment">Control and query object alignment</a>
</li>
<li><a href="#CPlusPlus11_attributes">Attributes</a></li>
<li><a href="#CPlusPlus11_ref_qualifiers">Methods with ref-qualifiers</a>
</li>
</ul>
</li>
<li><a href="#CPlusPlus11_standard_library_changes">Standard library
 changes</a>
<ul>
<li><a href="#CPlusPlus11_threading_facilities">Threading facilities</a></li>
<li><a href="#CPlusPlus11_tuple_types">Tuple types</a></li>
<li><a href="#CPlusPlus11_hash_tables">Hash tables</a></li>
<li><a href="#CPlusPlus11_regular_expressions">Regular expressions</a></li>
<li><a href="#CPlusPlus11_general_purpose_smart_pointers">
General-purpose smart pointers</a></li>
<li><a href="#CPlusPlus11_extensible_random_number_facility">Extensible
 random number facility</a></li>
<li><a href="#CPlusPlus11_wrapper_reference">Wrapper reference</a></li>
<li><a href="#CPlusPlus11_polymorphous_wrappers_for_function_objects">
Polymorphic wrappers for function objects</a></li>
<li><a href="#CPlusPlus11_type_traits_for_metaprogramming">Type traits
 for metaprogramming</a></li>
<li><a href="#CPlusPlus11_uniform_method_for_computing_return_type_of_function_objects">
Uniform method for computing return type of function objects</a></li>
</ul>
</li>
</ul>
</div>
<!-- INDEX -->
<h2><a name="CPlusPlus11_introduction">7.1 Introduction</a></h2>
<p>This chapter gives you a brief overview about the SWIG implementation
 of the C++11 standard. This part of SWIG is still a work in progress.</p>
<p>SWIG supports the new C++ syntax changes with some minor limitations
 in some areas such as decltype expressions and variadic templates.
 Wrappers for the new STL types (unordered_ containers, result_of,
 tuples) are incomplete. The wrappers for the new containers would work
 much like the C++03 containers and users are welcome to help by
 adapting the existing container interface files and submitting them as
 a patch for inclusion in future versions of SWIG.</p>
<h2><a name="CPlusPlus11_core_language_changes">7.2 Core language
 changes</a></h2>
<h3><a name="CPlusPlus11_rvalue_reference_and_move_semantics">7.2.1
 Rvalue reference and move semantics</a></h3>
<p> SWIG correctly parses the rvalue reference syntax '&amp;&amp;', for example
 the typical usage of it in the move constructor and move assignment
 operator below:</p>
<div class="code">
<pre>
class MyClass {
...
  std::vector&lt;int&gt; numbers;
public:
  MyClass(MyClass &amp;&amp;other) : numbers(std::move(other.numbers)) {}
  MyClass &amp; operator=(MyClass &amp;&amp;other) {
    numbers = std::move(other.numbers);
    return *this;
  }
};
</pre>
</div>
<p> Rvalue references are designed for C++ temporaries and so are not
 very useful when used from non-C++ target languages. Generally you
 would just ignore them via <tt>%ignore</tt> before parsing the class.
 For example, ignore the move constructor:</p>
<div class="code">
<pre>
%ignore MyClass::MyClass(MyClass &amp;&amp;);
</pre>
</div>
<p> The plan is to ignore move constructors by default in a future
 version of SWIG. Note that both normal assignment operators as well as
 move assignment operators are ignored by default in most target
 languages with the following warning:</p>
<div class="shell">
<pre>
example.i:18: Warning 503: Can't wrap 'operator =' unless renamed to a valid identifier.
</pre>
</div>
<h3><a name="CPlusPlus11_generalized_constant_expressions">7.2.2
 Generalized constant expressions</a></h3>
<p>SWIG parses and identifies the keyword <tt>constexpr</tt>, but cannot
 fully utilise it. These C++ compile time constants are usable as
 runtime constants from the target languages. Below shows example usage
 for assigning a C++ compile time constant from a compile time constant
 function:</p>
<div class="code">
<pre>
constexpr int XXX() { return 10; }
constexpr int YYY = XXX() + 100;
</pre>
</div>
<p> When either of these is used from a target language, a runtime call
 is made to obtain the underlying constant.</p>
<h3><a name="CPlusPlus11_extern_template">7.2.3 Extern template</a></h3>
<p>SWIG correctly parses the keywords <tt>extern template</tt>. However,
 this template instantiation suppression in a translation unit has no
 relevance outside of the C++ compiler and so is not used by SWIG. SWIG
 only uses <tt>%template</tt> for instantiating and wrapping templates.</p>
<div class="code">
<pre>
template class std::vector&lt;int&gt;;        // C++03 explicit instantiation in C++
extern template class std::vector&lt;int&gt;; // C++11 explicit instantiation suppression in C++
%template(VectorInt) std::vector&lt;int&gt;;  // SWIG instantiation
</pre>
</div>
<h3><a name="CPlusPlus11_initializer_lists">7.2.4 Initializer lists</a></h3>
<p> Initializer lists are very much a C++ compiler construct and are not
 very accessible from wrappers as they are intended for compile time
 initialization of classes using the special <tt>std::initializer_list</tt>
 type. SWIG detects usage of initializer lists and will emit a special
 informative warning each time one is used:</p>
<div class="shell">
<pre>
example.i:33: Warning 476: Initialization using std::initializer_list.
</pre>
</div>
<p> Initializer lists usually appear in constructors but can appear in
 any function or method. They often appear in constructors which are
 overloaded with alternative approaches to initializing a class, such as
 the std container's push_back method for adding elements to a
 container. The recommended approach then is to simply ignore the
 initializer-list constructor, for example:</p>
<div class="code">
<pre>
%ignore Container::Container(std::initializer_list&lt;int&gt;);
class Container {
public:
  Container(std::initializer_list&lt;int&gt;); // initializer-list constructor
  Container();
  void push_back(const int &amp;);
  ...
};
</pre>
</div>
<p>Alternatively you could modify the class and add another constructor
 for initialization by some other means, for example by a <tt>
std::vector</tt>:</p>
<div class="code">
<pre>
%include &lt;std_vector.i&gt;
class Container {
public:
  Container(const std::vector&lt;int&gt; &amp;);
  Container(std::initializer_list&lt;int&gt;); // initializer-list constructor
  Container();
  void push_back(const int &amp;);
  ...
};
</pre>
</div>
<p>And then call this constructor from your target language, for
 example, in Python, the following will call the constructor taking the <tt>
std::vector</tt>:</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; c = Container( [1, 2, 3, 4] )
</pre>
</div>
<p> If you are unable to modify the class being wrapped, consider
 ignoring the initializer-list constructor and using %extend to add in
 an alternative constructor:</p>
<div class="code">
<pre>
%include &lt;std_vector.i&gt;
%extend Container {
  Container(const std::vector&lt;int&gt; &amp;elements) {
    Container *c = new Container();
    for (int element : elements)
      c-&gt;push_back(element);
    return c;
  }
}

%ignore Container::Container(std::initializer_list&lt;int&gt;);

class Container {
public:
  Container(std::initializer_list&lt;int&gt;); // initializer-list constructor
  Container();
  void push_back(const int &amp;);
  ...
};
</pre>
</div>
<p> The above makes the wrappers look is as if the class had been
 declared as follows:</p>
<div class="code">
<pre>
%include &lt;std_vector.i&gt;
class Container {
public:
  Container(const std::vector&lt;int&gt; &amp;);
//  Container(std::initializer_list&lt;int&gt;); // initializer-list constructor (ignored)
  Container();
  void push_back(const int &amp;);
  ...
};
</pre>
</div>
<p> <tt>std::initializer_list</tt> is simply a container that can only
 be initialized at compile time. As it is just a C++ type, it is
 possible to write typemaps for a target language container to map onto <tt>
std::initializer_list</tt>. However, this can only be done for a fixed
 number of elements as initializer lists are not designed to be
 constructed with a variable number of arguments at runtime. The example
 below is a very simple approach which ignores any parameters passed in
 and merely initializes with a fixed list of fixed integer values chosen
 at compile time:</p>
<div class="code">
<pre>
%typemap(in) std::initializer_list&lt;int&gt; {
  $1 = {10, 20, 30, 40, 50};
}
class Container {
public:
  Container(std::initializer_list&lt;int&gt;); // initializer-list constructor
  Container();
  void push_back(const int &amp;);
  ...
};
</pre>
</div>
<p> Any attempt at passing in values from the target language will be
 ignored and be replaced by <tt>{10, 20, 30, 40, 50}</tt>. Needless to
 say, this approach is very limited, but could be improved upon, but
 only slightly. A typemap could be written to map a fixed number of
 elements on to the <tt>std::initializer_list</tt>, but with values
 decided at runtime. The typemaps would be target language specific.</p>
<p> Note that the default typemap for <tt>std::initializer_list</tt>
 does nothing but issue the warning and hence any user supplied typemaps
 will override it and suppress the warning.</p>
<h3><a name="CPlusPlus11_uniform_initialization">7.2.5 Uniform
 initialization</a></h3>
<p>The curly brackets {} for member initialization are fully supported
 by SWIG:</p>
<div class="code">
<pre>
struct BasicStruct {
 int x;
 double y;
};
 
struct AltStruct {
  AltStruct(int x, double y) : x_{x}, y_{y} {}
 
  int x_;
  double y_;
};

BasicStruct var1{5, 3.2}; // only fills the struct components
AltStruct var2{2, 4.3};   // calls the constructor
</pre>
</div>
<p>Uniform initialization does not affect usage from the target
 language, for example in Python:</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; a = AltStruct(10, 142.15)
&gt;&gt;&gt; a.x_
10
&gt;&gt;&gt; a.y_
142.15
</pre>
</div>
<h3><a name="CPlusPlus11_type_inference">7.2.6 Type inference</a></h3>
<p>SWIG supports <tt>decltype()</tt> with some limitations. Single
 variables are allowed, however, expressions are not supported yet. For
 example, the following code will work:</p>
<div class="code">
<pre>
int i;
decltype(i) j;
</pre>
</div>
<p>However, using an expression inside the decltype results in syntax
 error:</p>
<div class="code">
<pre>
int i; int j;
decltype(i+j) k;  // syntax error
</pre>
</div>
<h3><a name="CPlusPlus11_range_based_for_loop">7.2.7 Range-based
 for-loop</a></h3>
<p>This feature is part of the implementation block only. SWIG ignores
 it.</p>
<h3><a name="CPlusPlus11_lambda_functions_and_expressions">7.2.8 Lambda
 functions and expressions</a></h3>
<p>SWIG correctly parses most of the Lambda functions syntax. For
 example:</p>
<div class="code">
<pre>
auto val = [] { return something; };
auto sum = [](int x, int y) { return x+y; };
auto sum = [](int x, int y) -&gt; int { return x+y; };
</pre>
</div>
<p>The lambda functions are removed from the wrappers for now, because
 of the lack of support for closures (scope of the lambda functions) in
 the target languages.</p>
<p> Lambda functions used to create variables can also be parsed, but
 due to limited support of <tt>auto</tt> when the type is deduced from
 the expression, the variables are simply ignored.</p>
<div class="code">
<pre>
auto six = [](int x, int y) { return x+y; }(4, 2);
</pre>
</div>
<p> Better support should be available in a later release.</p>
<h3><a name="CPlusPlus11_alternate_function_syntax">7.2.9 Alternate
 function syntax</a></h3>
<p>SWIG fully supports the new definition of functions. For example:</p>
<div class="code">
<pre>
struct SomeStruct {
  int FuncName(int x, int y);
};
</pre>
</div>
<p>can now be written as in C++11:</p>
<div class="code">
<pre>
struct SomeStruct {
  auto FuncName(int x, int y) -&gt; int;
};
 
auto SomeStruct::FuncName(int x, int y) -&gt; int {
  return x + y;
}
</pre>
</div>
<p>The usage in the target languages remains the same, for example in
 Python:</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; a = SomeStruct()
&gt;&gt;&gt; a.FuncName(10, 5)
15
</pre>
</div>
<p>SWIG will also deal with type inference for the return type, as per
 the limitations described earlier. For example:</p>
<div class="code">
<pre>
auto square(float a, float b) -&gt; decltype(a);
</pre>
</div>
<h3><a name="CPlusPlus11_object_construction_improvement">7.2.10 Object
 construction improvement</a></h3>
<p> There are three parts to object construction improvement. The first
 improvement is constructor delegation such as the following:</p>
<div class="code">
<pre>
class A {
public:
  int a;
  int b;
  int c;

  A() : A(10) {}
  A(int aa) : A(aa, 20) {}
  A(int aa, int bb) : A(aa, bb, 30) {}
  A(int aa, int bb, int cc) { a=aa; b=bb; c=cc; }
};
</pre>
</div>
<p> where peer constructors can be called. SWIG handles this without any
 issue.</p>
<p> The second improvement is constructor inheritance via a <tt>using</tt>
 declaration. This is parsed correctly, but the additional constructors
 are not currently added to the derived proxy class in the target
 language. An example is shown below:
<!--
The extra constructors provided by the &lt;tt&gt;using&lt;/tt&gt; syntax will add the appropriate constructors into the target language proxy derived classes.
In the example below a wrapper for the &lt;tt&gt;DerivedClass(int)&lt;/tt&gt; is added to &lt;tt&gt;DerivedClass&lt;/tt&gt;:
-->
</p>
<div class="code">
<pre>
class BaseClass {
public:
  BaseClass(int iValue);
};

class DerivedClass: public BaseClass {
  public:
  using BaseClass::BaseClass; // Adds DerivedClass(int) constructor
};
</pre>
</div>
<p> The final part is member initialization at the site of the
 declaration. This kind of initialization is handled by SWIG.</p>
<div class="code">
<pre>
class SomeClass {
public:
  SomeClass() {}
  explicit SomeClass(int new_value) : value(new_value) {}

  int value = 5;
};
</pre>
</div>
<h3><a name="CPlusPlus11_explicit_overrides_final">7.2.11 Explicit
 overrides and final</a></h3>
<p> The special identifiers <tt>final</tt> and <tt>override</tt> can be
 used on methods and destructors, such as in the following example:</p>
<div class="code">
<pre>
struct BaseStruct {
  virtual void ab() const = 0;
  virtual void cd();
  virtual void ef();
  virtual ~BaseStruct();
};
struct DerivedStruct : BaseStruct {
  virtual void ab() const override;
  virtual void cd() final;
  virtual void ef() final override;
  virtual ~DerivedStruct() override;
};
</pre>
</div>
<h3><a name="CPlusPlus11_null_pointer_constant">7.2.12 Null pointer
 constant</a></h3>
<p>The <tt>nullptr</tt> constant is mostly unimportant in wrappers. In
 the few places it has an effect, it is treated like <tt>NULL</tt>.</p>
<h3><a name="CPlusPlus11_strongly_typed_enumerations">7.2.13 Strongly
 typed enumerations</a></h3>
<p>SWIG supports strongly typed enumerations and parses the new <tt>enum
 class</tt> syntax and forward declarator for the enums, such as:</p>
<div class="code">
<pre>
enum class MyEnum : unsigned int;
</pre>
</div>
<p> Strongly typed enums are often used to avoid name clashes such as
 the following:</p>
<div class="code">
<pre>
struct Color {
  enum class RainbowColors : unsigned int {
    Red, Orange, Yellow, Green, Blue, Indigo, Violet
  };
  
  enum class WarmColors {
    Yellow, Orange, Red
  };

  // Note normal enum
  enum PrimeColors {
    Red=100, Green, Blue
  };
};
</pre>
</div>
<p> There are various ways that the target languages handle enums, so it
 is not possible to precisely state how they are handled in this
 section. However, generally, most scripting languages mangle in the
 strongly typed enumeration's class name, but do not use any additional
 mangling for normal enumerations. For example, in Python, the following
 code</p>
<div class="targetlang">
<pre>
print Color.RainbowColors_Red, Color.WarmColors_Red, Color.Red
</pre>
</div>
<p> results in</p>
<div class="shell">
<pre>
0 2 100
</pre>
</div>
<p> The strongly typed languages often wrap normal enums into an enum
 class and so treat normal enums and strongly typed enums the same. The
 equivalent in Java is:</p>
<div class="targetlang">
<pre>
System.out.println(Color.RainbowColors.Red.swigValue() + &quot; &quot; + Color.WarmColors.Red.swigValue() + &quot; &quot; + Color.PrimeColors.Red.swigValue());
</pre>
</div>
<h3><a name="CPlusPlus11_double_angle_brackets">7.2.14 Double angle
 brackets</a></h3>
<p>SWIG correctly parses the symbols &gt;&gt; as closing the template block,
 if found inside it at the top level, or as the right shift operator &gt;&gt;
 otherwise.</p>
<div class="code">
<pre>
std::vector&lt;std::vector&lt;int&gt;&gt; myIntTable;
</pre>
</div>
<h3><a name="CPlusPlus11_explicit_conversion_operators">7.2.15 Explicit
 conversion operators</a></h3>
<p>SWIG correctly parses the keyword <tt>explicit</tt> for operators in
 addition to constructors now. For example:</p>
<div class="code">
<pre>
class U {
public:
  int u;
};

class V {
public:
  int v;
};

class TestClass {
public:
  //implicit converting constructor
  TestClass(U const &amp;val) { t=val.u; }

  // explicit constructor
  explicit TestClass(V const &amp;val) { t=val.v; }

  int t;
};

struct Testable {
  // explicit conversion operator
  explicit operator bool() const {
    return false;
  }
};
</pre>
</div>
<p> The effect of explicit constructors and operators has little
 relevance for the proxy classes as target languages don't have the same
 concepts of implicit conversions as C++. Conversion operators either
 with or without <tt>explicit</tt> need renaming to a valid identifier
 name in order to make them available as a normal proxy method.</p>
<h3><a name="CPlusPlus11_alias_templates">7.2.16 Type alias and alias
 templates</a></h3>
<p> A type alias is a statement of the form:</p>
<div class="code">
<pre>
using PFD = void (*)(double); // New introduced syntax
</pre>
</div>
<p> which is equivalent to the old style typedef:</p>
<div class="code">
<pre>
typedef void (*PFD)(double);  // The old style
</pre>
</div>
<p> The following is an example of an alias template:<div class="code">
<pre>
template&lt; typename T1, typename T2, int N &gt;
class SomeType {
public:
  T1 a;
  T2 b;
};

template&lt; typename T2 &gt;
using TypedefName = SomeType&lt;char*, T2, 5&gt;;
</pre>
</div></p>
<p> SWIG supports both type aliasing and alias templates. However, in
 order to use an alias template, two <tt>%template</tt> directives must
 be used:</p>
<div class="code">
<pre>
%template(SomeTypeBool) SomeType&lt;char*, bool, 5&gt;;
%template() TypedefName&lt;bool&gt;;
</pre>
</div>
<p>Firstly, the actual template is instantiated with a name to be used
 by the target language, as per any template being wrapped. Secondly,
 the empty template instantiation, <tt>%template()</tt>, is required for
 the alias template. This second requirement is necessary to add the
 appropriate instantiated template type into the type system as SWIG
 does not automatically instantiate templates. See the <a href="#SWIGPlus_nn30">
Templates</a> section for more general information on wrapping
 templates.</p>
<h3><a name="CPlusPlus11_unrestricted_unions">7.2.17 Unrestricted unions</a>
</h3>
<p>SWIG fully supports any type inside a union even if it does not
 define a trivial constructor. For example, the wrapper for the
 following code correctly provides access to all members in the union:</p>
<div class="code">
<pre>
struct point {
  point() {}
  point(int x, int y) : x_(x), y_(y) {}
  int x_, y_;
};

#include &lt;new&gt; // For placement 'new' in the constructor below
union P {
  int z;
  double w;
  point p; // Illegal in C++03; legal in C++11.
  // Due to the point member, a constructor definition is required.
  P() {
    new(&amp;p) point();
  }
} p1;
</pre>
</div>
<h3><a name="CPlusPlus11_variadic_templates">7.2.18 Variadic templates</a>
</h3>
<p>SWIG supports the variadic templates syntax (inside the &lt;&gt; block,
 variadic class inheritance and variadic constructor and initializers)
 with some limitations. The following code is correctly parsed:</p>
<div class="code">
<pre>
template &lt;typename... BaseClasses&gt; class ClassName : public BaseClasses... {
public:
  ClassName (BaseClasses &amp;&amp;... baseClasses) : BaseClasses(baseClasses)... {}
}
</pre>
</div>
<p> For now however, the <tt>%template</tt> directive only accepts one
 parameter substitution for the variable template parameters.</p>
<div class="code">
<pre>
%template(MyVariant1) ClassName&lt;&gt;         // zero argument not supported yet
%template(MyVariant2) ClassName&lt;int&gt;      // ok
%template(MyVariant3) ClassName&lt;int, int&gt; // too many arguments not supported yet
</pre>
</div>
<p>Support for the variadic <tt>sizeof()</tt> function is correctly
 parsed:</p>
<div class="code">
<pre>
const int SIZE = sizeof...(ClassName&lt;int, int&gt;);
</pre>
</div>
<p> In the above example <tt>SIZE</tt> is of course wrapped as a
 constant.</p>
<h3><a name="CPlusPlus11_new_char_literals">7.2.19 New character
 literals</a></h3>
<p> C++11 adds support for UCS-2 and UCS-4 character literals. These
 character literals are preceded by either 'u' or 'U'.</p>
<div class="code">
<pre>
char16_t a = u'a';
char32_t b = U'b';
</pre>
</div>
<p><b> Compatibility note:</b> SWIG-4.0.0 was the first version to
 support these Universal Coded Character Set (UCS) character literals.</p>
<h3><a name="CPlusPlus11_new_string_literals">7.2.20 New string literals</a>
</h3>
<p>SWIG supports wide string and Unicode string constants and raw string
 literals.</p>
<div class="code">
<pre>
// New string literals
wstring         aa =  L&quot;Wide string&quot;;
const char     *bb = u8&quot;UTF-8 string&quot;;
const char16_t *cc =  u&quot;UTF-16 string&quot;;
const char32_t *dd =  U&quot;UTF-32 string&quot;;

// Raw string literals
const char      *xx =        &quot;)I'm an \&quot;ascii\&quot; \\ string.&quot;;
const char      *ee =   R&quot;XXX()I'm an &quot;ascii&quot; \ string.)XXX&quot;; // same as xx
wstring          ff =  LR&quot;XXX(I'm a &quot;raw wide&quot; \ string.)XXX&quot;;
const char      *gg = u8R&quot;XXX(I'm a &quot;raw UTF-8&quot; \ string.)XXX&quot;;
const char16_t  *hh =  uR&quot;XXX(I'm a &quot;raw UTF-16&quot; \ string.)XXX&quot;;
const char32_t  *ii =  UR&quot;XXX(I'm a &quot;raw UTF-32&quot; \ string.)XXX&quot;;
</pre>
</div>
<p> Non-ASCII string support varies quite a bit among the various target
 languages though.</p>
<p> Note: There is a bug currently where SWIG's preprocessor incorrectly
 parses an odd number of double quotes inside raw string literals.</p>
<h3><a name="CPlusPlus11_user_defined_literals">7.2.21 User-defined
 literals</a></h3>
<p> SWIG parses the declaration of user-defined literals, that is, the <tt>
operator &quot;&quot; _mysuffix()</tt> function syntax.</p>
<p> Some examples are the raw literal:</p>
<div class="code">
<pre>
OutputType operator &quot;&quot; _myRawLiteral(const char * value);
</pre>
</div>
<p> numeric cooked literals:</p>
<div class="code">
<pre>
OutputType operator &quot;&quot; _mySuffixIntegral(unsigned long long);
OutputType operator &quot;&quot; _mySuffixFloat(long double);
</pre>
</div>
<p> and cooked string literals:</p>
<div class="code">
<pre>
OutputType operator &quot;&quot; _mySuffix(const char * string_values, size_t num_chars);
OutputType operator &quot;&quot; _mySuffix(const wchar_t * string_values, size_t num_chars);
OutputType operator &quot;&quot; _mySuffix(const char16_t * string_values, size_t num_chars);
OutputType operator &quot;&quot; _mySuffix(const char32_t * string_values, size_t num_chars);
</pre>
</div>
<p> Like other operators that SWIG parses, a warning is given about
 renaming the operator in order for it to be wrapped:</p>
<div class="shell">
<pre>
example.i:27: Warning 503: Can't wrap 'operator &quot;&quot; _myRawLiteral' unless renamed to a valid identifier.
</pre>
</div>
<p> If %rename is used, then it can be called like any other wrapped
 method. Currently you need to specify the full declaration including
 parameters for %rename:</p>
<div class="code">
<pre>
%rename(MyRawLiteral)  operator&quot;&quot; _myRawLiteral(const char * value);
</pre>
</div>
<p> Or if you just wish to ignore it altogether:</p>
<div class="code">
<pre>
%ignore operator &quot;&quot; _myRawLiteral(const char * value);
</pre>
</div>
<p> Note that use of user-defined literals such as the following still
 give a syntax error:</p>
<div class="code">
<pre>
OutputType var1 = &quot;1234&quot;_suffix;
OutputType var2 = 1234_suffix;
OutputType var3 = 3.1416_suffix;
</pre>
</div>
<h3><a name="CPlusPlus11_thread_local_storage">7.2.22 Thread-local
 storage</a></h3>
<p>SWIG correctly parses the <tt>thread_local</tt> keyword. For example,
 variables reachable by the current thread can be defined as:</p>
<div class="code">
<pre>
struct A {
  static thread_local int val;
};
thread_local int global_val;
</pre>
</div>
<p> The use of the <tt>thread_local</tt> storage specifier does not
 affect the wrapping process; it does not modify the wrapper code
 compared to when it is not specified. A variable will be thread local
 if accessed from different threads from the target language in the same
 way that it will be thread local if accessed from C++ code.</p>
<h3><a name="CPlusPlus11_defaulted_deleted">7.2.23 Explicitly defaulted
 functions and deleted functions</a></h3>
<p>SWIG handles explicitly defaulted functions, that is, <tt>= default</tt>
 added to a function declaration. Deleted definitions, which are also
 called deleted functions, have <tt>= delete</tt> added to the function
 declaration. For example:</p>
<div class="code">
<pre>
struct NonCopyable {
  NonCopyable &amp; operator=(const NonCopyable &amp;) = delete; /* Removes operator= */
  NonCopyable(const NonCopyable &amp;) = delete;             /* Removes copy constructor */
  NonCopyable() = default;                               /* Explicitly allows the empty constructor */
};
</pre>
</div>
<p> Wrappers for deleted functions will not be available in the target
 language. Wrappers for defaulted functions will of course be available
 in the target language. Explicitly defaulted functions have no direct
 effect for SWIG wrapping as the declaration is handled much like any
 other method declaration parsed by SWIG.</p>
<p> Deleted functions are also designed to prevent implicit conversions
 when calling the function. For example, the C++ compiler will not
 compile any code which attempts to use an int as the type of the
 parameter passed to <tt>f</tt> below:</p>
<div class="code">
<pre>
struct NoInt {
  void f(double i);
  void f(int) = delete;
};
</pre>
</div>
<p> This is a C++ compile time check and SWIG does not make any attempt
 to detect if the target language is using an int instead of a double
 though, so in this case it is entirely possible to pass an int instead
 of a double to <tt>f</tt> from Java, Python etc.</p>
<h3><a name="CPlusPlus11_type_long_long_int">7.2.24 Type long long int</a>
</h3>
<p>SWIG correctly parses and uses the new <tt>long long</tt> type
 already introduced in C99 some time ago.</p>
<h3><a name="CPlusPlus11_static_assertions">7.2.25 Static assertions</a></h3>
<p> SWIG correctly parses the new <tt>static_assert</tt> declarations
 (though 3.0.12 and earlier had a bug which meant this wasn't accepted
 at file scope). This is a C++ compile time directive so there isn't
 anything useful that SWIG can do with it.</p>
<div class="code">
<pre>
template &lt;typename T&gt;
struct Check {
  static_assert(sizeof(int) &lt;= sizeof(T), &quot;not big enough&quot;);
};
</pre>
</div>
<h3><a name="CPlusPlus11_sizeof">7.2.26 Allow sizeof to work on members
 of classes without an explicit object</a></h3>
<p> SWIG can parse the new sizeof() on types as well as on objects. For
 example:</p>
<div class="code">
<pre>
struct A {
  int member;
};

const int SIZE = sizeof(A::member); // does not work with C++03. Okay with C++11
</pre>
</div>
<p>In Python:</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; SIZE
8
</pre>
</div>
<h3><a name="CPlusPlus11_noexcept">7.2.27 Exception specifications and
 noexcept</a></h3>
<p> C++11 added in the noexcept specification to exception
 specifications to indicate that a function simply may or may not throw
 an exception, without actually naming any exception. SWIG understands
 these, although there isn't any useful way that this information can be
 taken advantage of by target languages, so it is as good as ignored
 during the wrapping process. Below are some examples of noexcept in
 function declarations:</p>
<div class="code">
<pre>
static void noex1() noexcept;
int noex2(int) noexcept(true);
int noex3(int, bool) noexcept(false);
</pre>
</div>
<h3><a name="CPlusPlus11_alignment">7.2.28 Control and query object
 alignment</a></h3>
<p> An <tt>alignof</tt> operator is used mostly within C++ to return
 alignment in number of bytes, but could be used to initialize a
 variable as shown below. The variable's value will be available for
 access by the target language as any other variable's compile time
 initialised value.<div class="code">
<pre>
const int align1 = alignof(A::member);
</pre>
</div></p>
<p> The <tt>alignas</tt> specifier for variable alignment is not yet
 supported. Example usage:</p>
<div class="code">
<pre>
struct alignas(16) S {
  int num;
};
alignas(double) unsigned char c[sizeof(double)];
</pre>
</div>
<p> Use the preprocessor to work around this for now:</p>
<div class="code">
<pre>
#define alignas(T)
</pre>
</div>
<h3><a name="CPlusPlus11_attributes">7.2.29 Attributes</a></h3>
<p> Attributes such as those shown below, are not yet supported and will
 give a syntax error.</p>
<div class="code">
<pre>
int [[attr1]] i [[attr2, attr3]];

[[noreturn, nothrow]] void f [[noreturn]] ();
</pre>
</div>
<h3><a name="CPlusPlus11_ref_qualifiers">7.2.30 Methods with
 ref-qualifiers</a></h3>
<p> C++11 non-static member functions can be declared with
 ref-qualifiers. Member functions declared with a <tt>&amp;</tt> lvalue
 ref-qualifiers are wrapped like any other function without
 ref-qualifiers. Member functions declared with a <tt>&amp;&amp;</tt> rvalue
 ref-qualifiers are ignored by default as they are unlikely to be
 required from non-C++ languages where the concept of<i> rvalue-ness</i>
 for the implied *this pointer does not apply. The warning is hidden by
 default, but can be displayed as described in the section on <a href="#Warnings_nn4">
Enabling extra warnings</a>.</p>
<p> Consider:</p>
<div class="code">
<pre>
struct RQ {
  void m1(int x) &amp;;
  void m2(int x) &amp;&amp;;
};
</pre>
</div>
<p> The only wrapped method will be the lvalue ref-qualified method <tt>
m1</tt> and if SWIG is run with the <tt>-Wextra</tt> command-line
 option, the following warning will be issued indicating <tt>m2</tt> is
 not wrapped:</p>
<div class="shell">
<pre>
example.i:7: Warning 405: Method with rvalue ref-qualifier m2(int) &amp;&amp; ignored.
</pre>
</div>
<p> If you unignore the method as follows, wrappers for <tt>m2</tt> will
 be generated:</p>
<div class="code">
<pre>
%feature(&quot;ignore&quot;, &quot;0&quot;) RQ::m2(int x) &amp;&amp;;
struct RQ {
  void m1(int x) &amp;;
  void m2(int x) &amp;&amp;;
};
</pre>
</div>
<p> Inspection of the generated C++ code, will show that <tt>std::move</tt>
 is used on the instance of the <tt>RQ *</tt> class:</p>
<div class="code">
<pre>
  RQ *arg1 = (RQ *) 0 ;
  int arg2 ;

  arg1 = ...marshalled from target language...
  arg2 = ...marshalled from target language...

  std::move(*arg1).m2(arg2);
</pre>
</div>
<p> This will compile but when run, the move effects may not be what you
 want. As stated earlier, rvalue ref-qualifiers aren't really applicable
 outside the world of C++. However, if you really know what you are
 doing, full control over the call to the method is possible via the
 low-level &quot;action&quot; feature. This feature completely replaces the call
 to the underlying function, that is, the last line in the snippet of
 code above.</p>
<div class="code">
<pre>
%feature(&quot;ignore&quot;, &quot;0&quot;) RQ::m2(int x) &amp;&amp;;
%feature(&quot;action&quot;) RQ::m2(int x) &amp;&amp; %{
  RQ().m2(arg2);
%}
struct RQ {
  void m1(int x) &amp;;
  void m2(int x) &amp;&amp;;
};
</pre>
</div>
<p> resulting in:</p>
<div class="code">
<pre>
  RQ *arg1 = (RQ *) 0 ;
  int arg2 ;

  arg1 = ...marshalled from target language...
  arg2 = ...marshalled from target language...

  RQ().m2(arg2);
</pre>
</div>
<p><b> Compatibility note:</b> SWIG-4.0.0 was the first version to
 support ref-qualifiers.</p>
<h2><a name="CPlusPlus11_standard_library_changes">7.3 Standard library
 changes</a></h2>
<h3><a name="CPlusPlus11_threading_facilities">7.3.1 Threading
 facilities</a></h3>
<p>SWIG does not currently wrap or use any of the new threading classes
 introduced (thread, mutex, locks, condition variables, task). The main
 reason is that SWIG target languages offer their own threading
 facilities so there is limited use for them.</p>
<h3><a name="CPlusPlus11_tuple_types">7.3.2 Tuple types</a></h3>
<p> SWIG does not provide library files for the new tuple types yet.
 Variadic template support requires further work to provide substantial
 tuple wrappers.</p>
<h3><a name="CPlusPlus11_hash_tables">7.3.3 Hash tables</a></h3>
<p> The new hash tables in the STL are <tt>unordered_set</tt>, <tt>
unordered_multiset</tt>, <tt>unordered_map</tt>, <tt>unordered_multimap</tt>
. These are not available in all target languages. Any missing support
 can in principle be easily implemented by adapting the current STL
 containers.</p>
<h3><a name="CPlusPlus11_regular_expressions">7.3.4 Regular expressions</a>
</h3>
<p> While SWIG could provide wrappers for the new C++11 regular
 expressions classes, there is little need as the target languages have
 their own regular expression facilities.</p>
<h3><a name="CPlusPlus11_general_purpose_smart_pointers">7.3.5
 General-purpose smart pointers</a></h3>
<p> SWIG provides special smart pointer handling for <tt>std::shared_ptr</tt>
 in the same way it has support for <tt>boost::shared_ptr</tt>. Please
 see the <a href="#Library_std_shared_ptr">shared_ptr smart pointer</a>
 library section. There is no special smart pointer handling available
 for <tt>std::weak_ptr</tt> and <tt>std::unique_ptr</tt> yet.</p>
<h3><a name="CPlusPlus11_extensible_random_number_facility">7.3.6
 Extensible random number facility</a></h3>
<p>This feature extends and standardizes the standard library only and
 does not effect the C++ language nor SWIG.</p>
<h3><a name="CPlusPlus11_wrapper_reference">7.3.7 Wrapper reference</a></h3>
<p> Wrapper references are similar to normal C++ references but are
 copy-constructible and copy-assignable. They could conceivably be used
 in public APIs. There is no special support for <tt>
std::reference_wrapper</tt> in SWIG though. Users would need to write
 their own typemaps if wrapper references are being used and these would
 be similar to the plain C++ reference typemaps.</p>
<h3><a name="CPlusPlus11_polymorphous_wrappers_for_function_objects">
7.3.8 Polymorphic wrappers for function objects</a></h3>
<p> SWIG supports functor classes in a few languages in a very natural
 way. However nothing is provided yet for the new <tt>std::function</tt>
 template. SWIG will parse usage of the template like any other
 template.</p>
<div class="code">
<pre>
%rename(__call__) Test::operator(); // Default renaming used for Python

struct Test {
  bool operator()(int x, int y); // function object
};

#include &lt;functional&gt;
std::function&lt;void (int, int)&gt; pF = Test;   // function template wrapper

</pre>
</div>
<p> Example of supported usage of the plain functor from Python is shown
 below. It does not involve <tt>std::function</tt>.</p>
<div class="targetlang">
<pre>
t = Test()
b = t(1, 2) # invoke C++ function object
</pre>
</div>
<h3><a name="CPlusPlus11_type_traits_for_metaprogramming">7.3.9 Type
 traits for metaprogramming</a></h3>
<p>The type_traits functions to support C++ metaprogramming is useful at
 compile time and is aimed specifically at C++ development:</p>
<div class="code">
<pre>
#include &lt;type_traits&gt;

// First way of operating.
template&lt; bool B &gt; struct algorithm {
  template&lt; class T1, class T2 &gt; static int do_it(T1 &amp;, T2 &amp;)  { /*...*/ return 1; }
};

// Second way of operating.
template&lt;&gt; struct algorithm&lt;true&gt; {
  template&lt; class T1, class T2 &gt; static int do_it(T1, T2)  { /*...*/ return 2; }
};

// Instantiating 'elaborate' will automatically instantiate the correct way to operate, depending on the types used.
template&lt; class T1, class T2 &gt; int elaborate(T1 A, T2 B) {
  // Use the second way only if 'T1' is an integer and if 'T2' is a floating point,
  // otherwise use the first way.
  return algorithm&lt; std::is_integral&lt;T1&gt;::value &amp;&amp; std::is_floating_point&lt;T2&gt;::value &gt;::do_it(A, B);
}
</pre>
</div>
<p> SWIG correctly parses the template specialization, template types
 etc. However, metaprogramming and the additional support in the
 type_traits header is really for compile time and is not much use at
 runtime for the target languages. For example, as SWIG requires
 explicit instantiation of templates via <tt>%template</tt>, there isn't
 much that <tt>std::is_integral&lt;int&gt;</tt> is going to provide by itself.
 However, template functions using such metaprogramming techniques might
 be useful to wrap. For example, the following instantiations could be
 made:</p>
<div class="code">
<pre>
%template(Elaborate) elaborate&lt;int, int&gt;;
%template(Elaborate) elaborate&lt;int, double&gt;;
</pre>
</div>
<p> Then the appropriate algorithm can be called for the subset of types
 given by the above <tt>%template</tt> instantiations from a target
 language, such as Python:</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; Elaborate(0, 0)
1
&gt;&gt;&gt; Elaborate(0, 0.0)
2
</pre>
</div>
<h3><a name="CPlusPlus11_uniform_method_for_computing_return_type_of_function_objects">
7.3.10 Uniform method for computing return type of function objects</a></h3>
<p> The new <tt>std::result_of</tt> class introduced in the &lt;functional&gt;
 header provides a generic way to obtain the return type of a function
 type via <tt>std::result_of::type</tt>. There isn't any library
 interface file to support this type. With a bit of work, SWIG will
 deduce the return type of functions when used in <tt>std::result_of</tt>
 using the approach shown below. The technique basically forward
 declares the <tt>std::result_of</tt> template class, then partially
 specializes it for the function types of interest. SWIG will use the
 partial specialization and hence correctly use the <tt>
std::result_of::type</tt> provided in the partial specialization.</p>
<div class="code">
<pre>
%inline %{
#include &lt;functional&gt;
typedef double(*fn_ptr)(double);
%}

namespace std {
  // Forward declaration of result_of
  template&lt;typename Func&gt; struct result_of;
  // Add in a partial specialization of result_of
  template&lt;&gt; struct result_of&lt; fn_ptr(double) &gt; {
    typedef double type;
  };
}

%template() std::result_of&lt; fn_ptr(double) &gt;;

%inline %{

double square(double x) {
  return (x * x);
}

template&lt;class Fun, class Arg&gt;
typename std::result_of&lt;Fun(Arg)&gt;::type test_result_impl(Fun fun, Arg arg) {
  return fun(arg);
}
%}

%template(test_result) test_result_impl&lt; fn_ptr, double &gt;;
%constant double (*SQUARE)(double) = square;
</pre>
</div>
<p> Note the first use of <tt>%template</tt> which SWIG requires to
 instantiate the template. The empty template instantiation suffices as
 no proxy class is required for <tt>std::result_of&lt;Fun(Arg)&gt;::type</tt>
 as this type is really just a <tt>double</tt>. The second <tt>%template</tt>
 instantiates the template function which is being wrapped for use as a
 callback. The <tt>%constant</tt> can then be used for any callback
 function as described in <a href="#SWIG_nn30">Pointers to functions and
 callbacks</a>.</p>
<p> Example usage from Python should give the not too surprising result:</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; test_result(SQUARE, 5.0)
25.0
</pre>
</div>
<p> Phew, that is a lot of hard work to get a callback working. You
 could just go with the more attractive option of just using <tt>double</tt>
 as the return type in the function declaration instead of <tt>result_of</tt>
!</p>
<HR NOSHADE>
<h1><a name="CPlusPlus14">8 SWIG and C++14</a></h1>

<!-- INDEX -->
<div class="sectiontoc">
<ul>
<li><a href="#CPlusPlus14_introduction">Introduction</a></li>
<li><a href="#CPlusPlus14_core_language_changes">Core language changes</a>
<ul>
<li><a href="#CPlusPlus14_binary_literals">Binary integer literals</a></li>
</ul>
</li>
<li><a href="#CPlusPlus14_standard_library_changes">Standard library
 changes</a></li>
</ul>
</div>
<!-- INDEX -->
<h2><a name="CPlusPlus14_introduction">8.1 Introduction</a></h2>
<p>This chapter gives you a brief overview about the SWIG implementation
 of the C++14 standard. There isn't much in C++14 that affects SWIG,
 however, work has only just begun on adding C++14 support.</p>
<p><b> Compatibility note:</b> SWIG-4.0.0 is the first version to
 support any C++14 features.</p>
<h2><a name="CPlusPlus14_core_language_changes">8.2 Core language
 changes</a></h2>
<h3><a name="CPlusPlus14_binary_literals">8.2.1 Binary integer literals</a>
</h3>
<p> C++14 added binary integer literals and SWIG supports these.
 Example:</p>
<div class="code">
<pre>
int b = 0b101011;
</pre>
</div>
<h2><a name="CPlusPlus14_standard_library_changes">8.3 Standard library
 changes</a></h2>
<HR NOSHADE>
<h1><a name="CPlusPlus17">9 SWIG and C++17</a></h1>

<!-- INDEX -->
<div class="sectiontoc">
<ul>
<li><a href="#CPlusPlus17_introduction">Introduction</a></li>
<li><a href="#CPlusPlus17_core_language_changes">Core language changes</a>
<ul>
<li><a href="#CPlusPlus17_nested_namespaces">Nested namespace
 definitions</a></li>
<li><a href="#CPlusPlus17_u8_char_literals">UTF-8 character literals</a></li>
<li><a href="#CPlusPlus17_hexadecimal_floating_literals">Hexadecimal
 floating literals</a></li>
</ul>
</li>
<li><a href="#CPlusPlus17_standard_library_changes">Standard library
 changes</a></li>
</ul>
</div>
<!-- INDEX -->
<h2><a name="CPlusPlus17_introduction">9.1 Introduction</a></h2>
<p>This chapter gives you a brief overview about the SWIG implementation
 of the C++17 standard. There isn't much in C++17 that affects SWIG,
 however, work has only just begun on adding C++17 support.</p>
<p><b> Compatibility note:</b> SWIG-4.0.0 is the first version to
 support any C++17 features.</p>
<h2><a name="CPlusPlus17_core_language_changes">9.2 Core language
 changes</a></h2>
<h3><a name="CPlusPlus17_nested_namespaces">9.2.1 Nested namespace
 definitions</a></h3>
<p> C++17 offers a more concise syntax for defining namespaces. SWIG has
 support for nested namespace definitions such as:</p>
<div class="code">
<pre>
namespace A::B::C {
  ...
}
</pre>
</div>
<p> This is the equivalent to the C++98 namespace definitions:</p>
<div class="code">
<pre>
namespace A {
  namespace B {
    namespace C {
      ...
    }
  }
}
</pre>
</div>
<h3><a name="CPlusPlus17_u8_char_literals">9.2.2 UTF-8 character
 literals</a></h3>
<p> C++17 added UTF-8 (u8) character literals. These are of type char.
 Example:</p>
<div class="code">
<pre>
char a = u8'a';
</pre>
</div>
<h3><a name="CPlusPlus17_hexadecimal_floating_literals">9.2.3
 Hexadecimal floating literals</a></h3>
<p> C++17 added hexadecimal floating literals. For example:</p>
<div class="code">
<pre>
double f = 0xF.68p2;
</pre>
</div>
<h2><a name="CPlusPlus17_standard_library_changes">9.3 Standard library
 changes</a></h2>
<HR NOSHADE>
<h1><a name="Preprocessor">10 Preprocessing</a></h1>

<!-- INDEX -->
<div class="sectiontoc">
<ul>
<li><a href="#Preprocessor_nn2">File inclusion</a></li>
<li><a href="#Preprocessor_nn3">File imports</a></li>
<li><a href="#Preprocessor_condition_compilation">Conditional
 Compilation</a></li>
<li><a href="#Preprocessor_nn5">Macro Expansion</a></li>
<li><a href="#Preprocessor_nn6">SWIG Macros</a></li>
<li><a href="#Preprocessor_nn7">C99 and GNU Extensions</a></li>
<li><a href="#Preprocessor_delimiters">Preprocessing and delimiters</a>
<ul>
<li><a href="#Preprocessor_nn8">Preprocessing and %{ ... %} &amp; &quot; ... &quot;
 delimiters</a></li>
<li><a href="#Preprocessor_nn9">Preprocessing and { ... } delimiters</a></li>
</ul>
</li>
<li><a href="#Preprocessor_typemap_delimiters">Preprocessor and Typemaps</a>
</li>
<li><a href="#Preprocessor_nn10">Viewing preprocessor output</a></li>
<li><a href="#Preprocessor_warning_error">The #error and #warning
 directives</a></li>
</ul>
</div>
<!-- INDEX -->
<p> SWIG includes its own enhanced version of the C preprocessor. The
 preprocessor supports the standard preprocessor directives and macro
 expansion rules. However, a number of modifications and enhancements
 have been made. This chapter describes some of these modifications.</p>
<h2><a name="Preprocessor_nn2">10.1 File inclusion</a></h2>
<p> To include another file into a SWIG interface, use the <tt>%include</tt>
 directive like this:</p>
<div class="code">
<pre>
%include &quot;pointer.i&quot;
</pre>
</div>
<p> Unlike, <tt>#include</tt>, <tt>%include</tt> includes each file once
 (and will not reload the file on subsequent <tt>%include</tt>
 declarations). Therefore, it is not necessary to use include-guards in
 SWIG interfaces.</p>
<p> By default, the <tt>#include</tt> is ignored unless you run SWIG
 with the <tt>-includeall</tt> option. The reason for ignoring
 traditional includes is that you often don't want SWIG to try and wrap
 everything included in standard header system headers and auxiliary
 files.</p>
<h2><a name="Preprocessor_nn3">10.2 File imports</a></h2>
<p> SWIG provides another file inclusion directive with the <tt>%import</tt>
 directive. For example:</p>
<div class="code">
<pre>
%import &quot;foo.i&quot;
</pre>
</div>
<p> The purpose of <tt>%import</tt> is to collect certain information
 from another SWIG interface file or a header file without actually
 generating any wrapper code. Such information generally includes type
 declarations (e.g., <tt>typedef</tt>) as well as C++ classes that might
 be used as base-classes for class declarations in the interface. The
 use of <tt>%import</tt> is also important when SWIG is used to generate
 extensions as a collection of related modules. This is an advanced
 topic and is described in later in the <a href="#Modules">Working with
 Modules</a> chapter.</p>
<p> The <tt>-importall</tt> directive tells SWIG to follow all <tt>
#include</tt> statements as imports. This might be useful if you want to
 extract type definitions from system header files without generating
 any wrappers.</p>
<h2><a name="Preprocessor_condition_compilation">10.3 Conditional
 Compilation</a></h2>
<p> SWIG fully supports the use of <tt>#if</tt>, <tt>#ifdef</tt>, <tt>
#ifndef</tt>, <tt>#else</tt>, <tt>#endif</tt> to conditionally include
 parts of an interface. The following symbols are predefined by SWIG
 when it is parsing the interface:</p>
<div class="code">
<pre>
SWIG                            Always defined when SWIG is processing a file
SWIGIMPORTED                    Defined when SWIG is importing a file with <tt>%import</tt>
SWIG_VERSION                    Hexadecimal (binary-coded decimal) number containing SWIG version,
                                such as 0x010311 (corresponding to SWIG-1.3.11).

SWIGCSHARP                      Defined when using C#
SWIGD                           Defined when using D
SWIGGO                          Defined when using Go
SWIGGUILE                       Defined when using Guile
SWIGJAVA                        Defined when using Java
SWIGJAVASCRIPT                  Defined when using Javascript
SWIG_JAVASCRIPT_JSC             Defined when using Javascript with -jsc
SWIG_JAVASCRIPT_V8              Defined when using Javascript with -v8 or -node
SWIGLUA                         Defined when using Lua
SWIGMZSCHEME                    Defined when using Mzscheme
SWIGOCAML                       Defined when using OCaml
SWIGOCTAVE                      Defined when using Octave
SWIGPERL                        Defined when using Perl
SWIGPHP                         Defined when using PHP (any version)
SWIGPHP7                        Defined when using PHP7
SWIGPYTHON                      Defined when using Python
SWIGR                           Defined when using R
SWIGRUBY                        Defined when using Ruby
SWIGSCILAB                      Defined when using Scilab
SWIGTCL                         Defined when using Tcl
SWIGXML                         Defined when using XML
</pre>
</div>
<p> In addition, SWIG defines the following set of standard C/C++
 macros:</p>
<div class="code">
<pre>
__LINE__                        Current line number
__FILE__                        Current file name
__STDC__                        Defined to indicate ISO C
__cplusplus                     Defined when -c++ option used
</pre>
</div>
<p> The following are language specific symbols that might be defined:</p>
<div class="code">
<pre>
SWIG_D_VERSION                  Unsigned integer target version when using D
SWIGGO_CGO                      Defined when using Go for cgo
SWIGGO_GCCGO                    Defined when using Go for gccgo
SWIGGO_INTGO_SIZE               Size of the Go type int when using Go (32 or 64)
SWIGPYTHON_PY3                  Defined when using Python with -py3
SWIGPYTHON_BUILTIN              Defined when using Python with -builtin
SWIG_RUBY_AUTORENAME            Defined when using Ruby with -autorename
</pre>
</div>
<p> Interface files can look at these symbols as necessary to change the
 way in which an interface is generated or to mix SWIG directives with C
 code.</p>
<h2><a name="Preprocessor_nn5">10.4 Macro Expansion</a></h2>
<p> Traditional preprocessor macros can be used in SWIG interfaces. Be
 aware that the <tt>#define</tt> statement is also used to try and
 detect constants. Therefore, if you have something like this in your
 file,</p>
<div class="code">
<pre>
#ifndef _FOO_H 1
#define _FOO_H 1
...
#endif
</pre>
</div>
<p> you may get some extra constants such as <tt>_FOO_H</tt> showing up
 in the scripting interface.</p>
<p> More complex macros can be defined in the standard way. For example:</p>
<div class="code">
<pre>
#define EXTERN extern
#ifdef __STDC__
#define ISOC_(args)   (args)
#else
#define ISOC_(args) ()
#endif
</pre>
</div>
<p> The following operators can appear in macro definitions:</p>
<ul>
<li><tt>#x</tt>
<br> Converts macro argument <tt>x</tt> to a string surrounded by double
 quotes (&quot;x&quot;).</li>
<li><tt>x ## y</tt>
<br> Concatenates x and y together to form <tt>xy</tt>.</li>
<li><tt>`x`</tt>
<br> If <tt>x</tt> is a string surrounded by double quotes, do nothing.
 Otherwise, turn into a string like <tt>#x</tt>. This is a non-standard
 SWIG extension.</li>
</ul>
<h2><a name="Preprocessor_nn6">10.5 SWIG Macros</a></h2>
<p> SWIG provides an enhanced macro capability with the <tt>%define</tt>
 and <tt>%enddef</tt> directives. For example:</p>
<div class="code">
<pre>
%define ARRAYHELPER(type, name)
%inline %{
type *new_ ## name (int nitems) {
  return (type *) malloc(sizeof(type)*nitems);
}
void delete_ ## name(type *t) {
  free(t);
}
type name ## _get(type *t, int index) {
  return t[index];
}
void name ## _set(type *t, int index, type val) {
  t[index] = val;
}
%}
%enddef

ARRAYHELPER(int, IntArray)
ARRAYHELPER(double, DoubleArray)
</pre>
</div>
<p> The primary purpose of <tt>%define</tt> is to define large macros of
 code. Unlike normal C preprocessor macros, it is not necessary to
 terminate each line with a continuation character (\)--the macro
 definition extends to the first occurrence of <tt>%enddef</tt>.
 Furthermore, when such macros are expanded, they are reparsed through
 the C preprocessor. Thus, SWIG macros can contain all other
 preprocessor directives except for nested <tt>%define</tt> statements.</p>
<p> The SWIG macro capability is a very quick and easy way to generate
 large amounts of code. In fact, many of SWIG's advanced features and
 libraries are built using this mechanism (such as C++ template
 support).</p>
<h2><a name="Preprocessor_nn7">10.6 C99 and GNU Extensions</a></h2>
<p> SWIG-1.3.12 and newer releases support variadic preprocessor macros.
 For example:</p>
<div class="code">
<pre>
#define DEBUGF(fmt, ...)   fprintf(stderr, fmt, __VA_ARGS__)
</pre>
</div>
<p> When used, any extra arguments to <tt>...</tt> are placed into the
 special variable <tt>__VA_ARGS__</tt>. This also works with special
 SWIG macros defined using <tt>%define</tt>.</p>
<p> SWIG allows a variable number of arguments to be empty. However,
 this often results in an extra comma (, ) and syntax error in the
 resulting expansion. For example:</p>
<div class="code">
<pre>
DEBUGF(&quot;hello&quot;);   --&gt; fprintf(stderr, &quot;hello&quot;, );
</pre>
</div>
<p> To get rid of the extra comma, use <tt>##</tt> like this:</p>
<div class="code">
<pre>
#define DEBUGF(fmt, ...)   fprintf(stderr, fmt, ##__VA_ARGS__)
</pre>
</div>
<p> SWIG also supports GNU-style variadic macros. For example:</p>
<div class="code">
<pre>
#define DEBUGF(fmt, args...)  fprintf(stdout, fmt, args)
</pre>
</div>
<p><b> Comment:</b> It's not entirely clear how variadic macros might be
 useful to interface building. However, they are used internally to
 implement a number of SWIG directives and are provided to make SWIG
 more compatible with C99 code.</p>
<h2><a name="Preprocessor_delimiters">10.7 Preprocessing and delimiters</a>
</h2>
<p> The preprocessor handles { }, &quot; &quot; and %{ %} delimiters differently.</p>
<h3><a name="Preprocessor_nn8">10.7.1 Preprocessing and %{ ... %} &amp; &quot;
 ... &quot; delimiters</a></h3>
<p> The SWIG preprocessor does not process any text enclosed in a code
 block %{ ... %}. Therefore, if you write code like this,</p>
<div class="code">
<pre>
%{
#ifdef NEED_BLAH
int blah() {
  ...
}
#endif
%}
</pre>
</div>
<p> the contents of the <tt>%{ ... %}</tt> block are copied without
 modification to the output (including all preprocessor directives).</p>
<h3><a name="Preprocessor_nn9">10.7.2 Preprocessing and { ... }
 delimiters</a></h3>
<p> SWIG always runs the preprocessor on text appearing inside <tt>{ ...
 }</tt>. However, sometimes it is desirable to make a preprocessor
 directive pass through to the output file. For example:</p>
<div class="code">
<pre>
%extend Foo {
  void bar() {
    #ifdef DEBUG
      printf(&quot;I'm in bar\n&quot;);
    #endif
  }
}
</pre>
</div>
<p> By default, SWIG will interpret the <tt>#ifdef DEBUG</tt> statement.
 However, if you really wanted that code to actually go into the wrapper
 file, prefix the preprocessor directives with <tt>%</tt> like this:</p>
<div class="code">
<pre>
%extend Foo {
  void bar() {
    %#ifdef DEBUG
      printf(&quot;I'm in bar\n&quot;);
    %#endif
  }
}
</pre>
</div>
<p> SWIG will strip the extra <tt>%</tt> and leave the preprocessor
 directive in the code.</p>
<h2><a name="Preprocessor_typemap_delimiters">10.8 Preprocessor and
 Typemaps</a></h2>
<p> <a href="#Typemaps">Typemaps</a> support a special attribute called <tt>
noblock</tt> where the { ... } delimiters can be used, but the
 delimiters are not actually generated into the code. The effect is then
 similar to using &quot;&quot; or %{ %} delimiters but the code<b> is</b> run
 through the preprocessor. For example:</p>
<div class="code">
<pre>
#define SWIG_macro(CAST) (CAST)$input
%typemap(in) Int {$1= SWIG_macro(int);}
</pre>
</div>
<p> might generate</p>
<div class="code">
<pre>
  {
    arg1=(int)jarg1;
  }
</pre>
</div>
<p> whereas</p>
<div class="code">
<pre>
#define SWIG_macro(CAST) (CAST)$input
%typemap(in, noblock=1) Int {$1= SWIG_macro(int);}
</pre>
</div>
<p> might generate</p>
<div class="code">
<pre>
  arg1=(int)jarg1;
</pre>
</div>
<p> and</p>
<div class="code">
<pre>
#define SWIG_macro(CAST) (CAST)$input
%typemap(in) Int %{$1=SWIG_macro(int);%}
</pre>
</div>
<p> would generate</p>
<div class="code">
<pre>
  arg1=SWIG_macro(int);
</pre>
</div>
<h2><a name="Preprocessor_nn10">10.9 Viewing preprocessor output</a></h2>
<p> Like many compilers, SWIG supports a <tt>-E</tt> command line option
 to display the output from the preprocessor. When the <tt>-E</tt>
 option is used, SWIG will not generate any wrappers. Instead the
 results after the preprocessor has run are displayed. This might be
 useful as an aid to debugging and viewing the results of macro
 expansions.</p>
<h2><a name="Preprocessor_warning_error">10.10 The #error and #warning
 directives</a></h2>
<p> SWIG supports the commonly used <tt>#warning</tt> and <tt>#error</tt>
 preprocessor directives. The <tt>#warning</tt> directive will cause
 SWIG to issue a warning then continue processing. The <tt>#error</tt>
 directive will cause SWIG to exit with a fatal error. Example usage:</p>
<div class="code">
<pre>
#error &quot;This is a fatal error message&quot;
#warning &quot;This is a warning message&quot;
</pre>
</div>
<p> The <tt>#error</tt> behaviour can be made to work like <tt>#warning</tt>
 if the <tt>-cpperraswarn</tt> commandline option is used.
 Alternatively, the <tt>#pragma</tt> directive can be used to the same
 effect, for example:</p>
<div class="code">
<pre>
  /* Modified behaviour: #error does not cause SWIG to exit with error */
  #pragma SWIG cpperraswarn=1
  /* Normal behaviour: #error does cause SWIG to exit with error */
  #pragma SWIG cpperraswarn=0
</pre>
</div><HR NOSHADE>
<h1><a name="Library">11 SWIG library</a></h1>

<!-- INDEX -->
<div class="sectiontoc">
<ul>
<li><a href="#Library_nn2">The %include directive and library search
 path</a></li>
<li><a href="#Library_nn3">C arrays and pointers</a>
<ul>
<li><a href="#Library_nn4">cpointer.i</a></li>
<li><a href="#Library_carrays">carrays.i</a></li>
<li><a href="#Library_nn6">cmalloc.i</a></li>
<li><a href="#Library_nn7">cdata.i</a></li>
</ul>
</li>
<li><a href="#Library_nn8">C string handling</a>
<ul>
<li><a href="#Library_nn9">Default string handling</a></li>
<li><a href="#Library_nn10">Passing binary data</a></li>
<li><a href="#Library_nn11">Using %newobject to release memory</a></li>
<li><a href="#Library_nn12">cstring.i</a></li>
</ul>
</li>
<li><a href="#Library_stl_cpp_library">STL/C++ library</a>
<ul>
<li><a href="#Library_std_string">std::string</a></li>
<li><a href="#Library_std_vector">std::vector</a></li>
<li><a href="#Library_stl_exceptions">STL exceptions</a></li>
<li><a href="#Library_std_shared_ptr">shared_ptr smart pointer</a>
<ul>
<li><a href="#Library_shared_ptr_basics">shared_ptr basics</a></li>
<li><a href="#Library_shared_ptr_inheritance">shared_ptr and inheritance</a>
</li>
<li><a href="#Library_shared_ptr_overloading">shared_ptr and method
 overloading</a></li>
<li><a href="#Library_shared_ptr_templates">shared_ptr and templates</a></li>
<li><a href="#Library_shared_ptr_directors">shared_ptr and directors</a></li>
</ul>
</li>
<li><a href="#Library_std_auto_ptr">auto_ptr smart pointer</a></li>
</ul>
</li>
<li><a href="#Library_nn16">Utility Libraries</a>
<ul>
<li><a href="#Library_nn17">exception.i</a></li>
</ul>
</li>
</ul>
</div>
<!-- INDEX -->
<p> To help build extension modules, SWIG is packaged with a library of
 support files that you can include in your own interfaces. These files
 often define new SWIG directives or provide utility functions that can
 be used to access parts of the standard C and C++ libraries. This
 chapter provides a reference to the current set of supported library
 files.</p>
<p><b> Compatibility note:</b> Older versions of SWIG included a number
 of library files for manipulating pointers, arrays, and other
 structures. Most these files are now deprecated and have been removed
 from the distribution. Alternative libraries provide similar
 functionality. Please read this chapter carefully if you used the old
 libraries.</p>
<h2><a name="Library_nn2">11.1 The %include directive and library search
 path</a></h2>
<p> Library files are included using the <tt>%include</tt> directive.
 When searching for files, directories are searched in the following
 order:</p>
<ol>
<li>The current directory</li>
<li>Directories specified with the <tt>-I</tt> command line option</li>
<li>.<tt>/swig_lib</tt></li>
<li>SWIG library install location as reported by <tt>swig -swiglib</tt>,
 for example <tt>/usr/local/share/swig/1.3.30</tt></li>
<li>On Windows, a directory <tt>Lib</tt> relative to the location of <tt>
swig.exe</tt> is also searched.</li>
</ol>
<p> Within directories mentioned in points 3-5, SWIG first looks for a
 subdirectory corresponding to a target language (e.g., <tt>python</tt>,
 <tt>tcl</tt>, etc.). If found, SWIG will search the language specific
 directory first. This allows for language-specific implementations of
 library files.</p>
<p> You can ignore the installed SWIG library by setting the <tt>
SWIG_LIB</tt> environment variable. Set the environment variable to hold
 an alternative library directory.</p>
<p> The directories that are searched are displayed when using <tt>
-verbose</tt> commandline option.</p>
<h2><a name="Library_nn3">11.2 C arrays and pointers</a></h2>
<p> This section describes library modules for manipulating low-level C
 arrays and pointers. The primary use of these modules is in supporting
 C declarations that manipulate bare pointers such as <tt>int *</tt>, <tt>
double *</tt>, or <tt>void *</tt>. The modules can be used to allocate
 memory, manufacture pointers, dereference memory, and wrap pointers as
 class-like objects. Since these functions provide direct access to
 memory, their use is potentially unsafe and you should exercise
 caution.</p>
<h3><a name="Library_nn4">11.2.1 cpointer.i</a></h3>
<p> The <tt>cpointer.i</tt> module defines macros that can be used to
 used to generate wrappers around simple C pointers. The primary use of
 this module is in generating pointers to primitive datatypes such as <tt>
int</tt> and <tt>double</tt>.</p>
<p><b> <tt>%pointer_functions(type, name)</tt></b></p>
<div class="indent">
<p>Generates a collection of four functions for manipulating a pointer <tt>
type *</tt>:</p>
<p> <tt>type *new_name()</tt></p>
<div class="indent">
<p> Creates a new object of type <tt>type</tt> and returns a pointer to
 it. In C, the object is created using <tt>calloc()</tt>. In C++, <tt>
new</tt> is used.</p>
</div>
<p> <tt>type *copy_name(type value)</tt></p>
<div class="indent">
<p> Creates a new object of type <tt>type</tt> and returns a pointer to
 it. An initial value is set by copying it from <tt>value</tt>. In C,
 the object is created using <tt>calloc()</tt>. In C++, <tt>new</tt> is
 used.</p>
</div>
<p> <tt>type *delete_name(type *obj)</tt></p>
<div class="indent">
<p> Deletes an object type <tt>type</tt>.</p>
</div>
<p> <tt>void name_assign(type *obj, type value)</tt></p>
<div class="indent">
<p> Assigns <tt>*obj = value</tt>.</p>
</div>
<p> <tt>type name_value(type *obj)</tt></p>
<div class="indent">
<p> Returns the value of <tt>*obj</tt>.</p>
</div>
<p> When using this macro, <tt>type</tt> may be any type and <tt>name</tt>
 must be a legal identifier in the target language. <tt>name</tt> should
 not correspond to any other name used in the interface file.</p>
<p> Here is a simple example of using <tt>%pointer_functions()</tt>:</p>
<div class="code">
<pre>
%module example
%include &quot;cpointer.i&quot;

/* Create some functions for working with &quot;int *&quot; */
%pointer_functions(int, intp);

/* A function that uses an &quot;int *&quot; */
void add(int x, int y, int *result);
</pre>
</div>
<p> Now, in Python:</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; import example
&gt;&gt;&gt; c = example.new_intp()     # Create an &quot;int&quot; for storing result
&gt;&gt;&gt; example.add(3, 4, c)       # Call function
&gt;&gt;&gt; example.intp_value(c)      # Dereference
7
&gt;&gt;&gt; example.delete_intp(c)     # Delete
</pre>
</div></div>
<p><b> <tt>%pointer_class(type, name)</tt></b></p>
<div class="indent">
<p> Wraps a pointer of <tt>type *</tt> inside a class-based interface.
 This interface is as follows:</p>
<div class="code">
<pre>
struct name {
  name();                            // Create pointer object
  ~name();                           // Delete pointer object
  void assign(type value);           // Assign value
  type value();                      // Get value
  type *cast();                      // Cast the pointer to original type
  static name *frompointer(type *);  // Create class wrapper from existing
                                     // pointer
};
</pre>
</div>
<p> When using this macro, <tt>type</tt> is restricted to a simple type
 name like <tt>int</tt>, <tt>float</tt>, or <tt>Foo</tt>. Pointers and
 other complicated types are not allowed. <tt>name</tt> must be a valid
 identifier not already in use. When a pointer is wrapped as a class,
 the &quot;class&quot; may be transparently passed to any function that expects
 the pointer.</p>
<p> If the target language does not support proxy classes, the use of
 this macro will produce the example same functions as <tt>
%pointer_functions()</tt> macro.</p>
<p> It should be noted that the class interface does introduce a new
 object or wrap a pointer inside a special structure. Instead, the raw
 pointer is used directly.</p>
<p> Here is the same example using a class instead:</p>
<div class="code">
<pre>
%module example
%include &quot;cpointer.i&quot;

/* Wrap a class interface around an &quot;int *&quot; */
%pointer_class(int, intp);

/* A function that uses an &quot;int *&quot; */
void add(int x, int y, int *result);
</pre>
</div>
<p> Now, in Python (using proxy classes)</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; import example
&gt;&gt;&gt; c = example.intp()         # Create an &quot;int&quot; for storing result
&gt;&gt;&gt; example.add(3, 4, c)       # Call function
&gt;&gt;&gt; c.value()                  # Dereference
7
</pre>
</div>
<p> Of the two macros, <tt>%pointer_class</tt> is probably the most
 convenient when working with simple pointers. This is because the
 pointers are access like objects and they can be easily garbage
 collected (destruction of the pointer object destroys the underlying
 object).</p>
</div>
<p><b> <tt>%pointer_cast(type1, type2, name)</tt></b></p>
<div class="indent">
<p> Creates a casting function that converts <tt>type1</tt> to <tt>type2</tt>
. The name of the function is <tt>name</tt>. For example:</p>
<div class="code">
<pre>
%pointer_cast(int *, unsigned int *, int_to_uint);
</pre>
</div>
<p> In this example, the function <tt>int_to_uint()</tt> would be used
 to cast types in the target language.</p>
</div>
<p><b> Note:</b> None of these macros can be used to safely work with
 strings (<tt>char *</tt> or <tt>char **</tt>).</p>
<p><b> Note:</b> When working with simple pointers, typemaps can often
 be used to provide more seamless operation.</p>
<h3><a name="Library_carrays">11.2.2 carrays.i</a></h3>
<p> This module defines macros that assist in wrapping ordinary C
 pointers as arrays. The module does not provide any safety or an extra
 layer of wrapping--it merely provides functionality for creating,
 destroying, and modifying the contents of raw C array data.</p>
<p><b> <tt>%array_functions(type, name)</tt></b></p>
<div class="indent">
<p>Creates four functions.</p>
<p> <tt>type *new_name(int nelements)</tt></p>
<div class="indent">
<p> Creates a new array of objects of type <tt>type</tt>. In C, the
 array is allocated using <tt>calloc()</tt>. In C++, <tt>new []</tt> is
 used.</p>
</div>
<p> <tt>type *delete_name(type *ary)</tt></p>
<div class="indent">
<p> Deletes an array. In C, <tt>free()</tt> is used. In C++, <tt>delete
 []</tt> is used.</p>
</div>
<p> <tt>type name_getitem(type *ary, int index)</tt></p>
<div class="indent">
<p> Returns the value <tt>ary[index]</tt>.</p>
</div>
<p> <tt>void name_setitem(type *ary, int index, type value)</tt></p>
<div class="indent">
<p> Assigns <tt>ary[index] = value</tt>.</p>
</div>
<p> When using this macro, <tt>type</tt> may be any type and <tt>name</tt>
 must be a legal identifier in the target language. <tt>name</tt> should
 not correspond to any other name used in the interface file.</p>
<p> Here is an example of <tt>%array_functions()</tt>. Suppose you had a
 function like this:</p>
<div class="code">
<pre>
void print_array(double x[10]) {
  int i;
  for (i = 0; i &lt; 10; i++) {
    printf(&quot;[%d] = %g\n&quot;, i, x[i]);
  }
}
</pre>
</div>
<p> To wrap it, you might write this:</p>
<div class="code">
<pre>
%module example

%include &quot;carrays.i&quot;
%array_functions(double, doubleArray);

void print_array(double x[10]);
</pre>
</div>
<p> Now, in a scripting language, you might write this:</p>
<div class="targetlang">
<pre>
a = new_doubleArray(10)               # Create an array
for i in range(0, 10):
    doubleArray_setitem(a, i, 2 * i)  # Set a value
print_array(a)                        # Pass to C
delete_doubleArray(a)                 # Destroy array
</pre>
</div></div>
<p><b> <tt>%array_class(type, name)</tt></b></p>
<div class="indent">
<p> Wraps a pointer of <tt>type *</tt> inside a class-based interface.
 This interface is as follows:</p>
<div class="code">
<pre>
struct name {
  name(int nelements);                  // Create an array
  ~name();                              // Delete array
  type getitem(int index);              // Return item
  void setitem(int index, type value);  // Set item
  type *cast();                         // Cast to original type
  static name *frompointer(type *);     // Create class wrapper from
                                        // existing pointer
};
</pre>
</div>
<p> When using this macro, <tt>type</tt> is restricted to a simple type
 name like <tt>int</tt> or <tt>float</tt>. Pointers and other
 complicated types are not allowed. <tt>name</tt> must be a valid
 identifier not already in use. When a pointer is wrapped as a class, it
 can be transparently passed to any function that expects the pointer.</p>
<p> When combined with proxy classes, the <tt>%array_class()</tt> macro
 can be especially useful. For example:</p>
<div class="code">
<pre>
%module example
%include &quot;carrays.i&quot;
%array_class(double, doubleArray);

void print_array(double x[10]);
</pre>
</div>
<p> Allows you to do this:</p>
<div class="targetlang">
<pre>
import example
c = example.doubleArray(10)  # Create double[10]
for i in range(0, 10):
    c[i] = 2 * i             # Assign values
example.print_array(c)       # Pass to C
</pre>
</div></div>
<p><b> Note:</b> These macros do not encapsulate C arrays inside a
 special data structure or proxy. There is no bounds checking or safety
 of any kind. If you want this, you should consider using a special
 array object rather than a bare pointer.</p>
<p><b> Note:</b> <tt>%array_functions()</tt> and <tt>%array_class()</tt>
 should not be used with types of <tt>char</tt> or <tt>char *</tt>.
 SWIG's default handling of these types is to handle them as character
 strings and the two macros do not do enough to change this.</p>
<h3><a name="Library_nn6">11.2.3 cmalloc.i</a></h3>
<p> This module defines macros for wrapping the low-level C memory
 allocation functions <tt>malloc()</tt>, <tt>calloc()</tt>, <tt>
realloc()</tt>, and <tt>free()</tt>.</p>
<p><b> <tt>%malloc(type [, name=type])</tt></b></p>
<div class="indent">
<p> Creates a wrapper around <tt>malloc()</tt> with the following
 prototype:</p>
<div class="code">
<pre>
<em>type</em> *malloc_<em>name</em>(int nbytes = sizeof(<em>type</em>));
</pre>
</div>
<p> If <tt>type</tt> is <tt>void</tt>, then the size parameter <tt>
nbytes</tt> is required. The <tt>name</tt> parameter only needs to be
 specified when wrapping a type that is not a valid identifier (e.g., &quot;<tt>
int *</tt>&quot;, &quot;<tt>double **</tt>&quot;, etc.).</p>
</div>
<p><b> <tt>%calloc(type [, name=type])</tt></b></p>
<div class="indent">
<p> Creates a wrapper around <tt>calloc()</tt> with the following
 prototype:</p>
<div class="code">
<pre>
<em>type</em> *calloc_<em>name</em>(int nobj =1, int sz = sizeof(<em>type</em>));
</pre>
</div>
<p> If <tt>type</tt> is <tt>void</tt>, then the size parameter <tt>sz</tt>
 is required.</p>
</div>
<p><b> <tt>%realloc(type [, name=type])</tt></b></p>
<div class="indent">
<p> Creates a wrapper around <tt>realloc()</tt> with the following
 prototype:</p>
<div class="code">
<pre>
<em>type</em> *realloc_<em>name</em>(<em>type</em> *ptr, int nitems);
</pre>
</div>
<p> Note: unlike the C <tt>realloc()</tt>, the wrapper generated by this
 macro implicitly includes the size of the corresponding type. For
 example, <tt>realloc_int(p, 100)</tt> reallocates <tt>p</tt> so that it
 holds 100 integers.</p>
</div>
<p><b> <tt>%free(type [, name=type])</tt></b></p>
<div class="indent">
<p> Creates a wrapper around <tt>free()</tt> with the following
 prototype:</p>
<div class="code">
<pre>
void free_<em>name</em>(<em>type</em> *ptr);
</pre>
</div></div>
<p><b> <tt>%sizeof(type [, name=type])</tt></b></p>
<div class="indent">
<p> Creates the constant:</p>
<div class="code">
<pre>
%constant int sizeof_<em>name</em> = sizeof(<em>type</em>);
</pre>
</div></div>
<p><b> <tt>%allocators(type [, name=type])</tt></b></p>
<div class="indent">
<p> Generates wrappers for all five of the above operations.</p>
</div>
<p> Here is a simple example that illustrates the use of these macros:</p>
<div class="code">
<pre>
// SWIG interface
%module example
%include &quot;cmalloc.i&quot;

%malloc(int);
%free(int);

%malloc(int *, intp);
%free(int *, intp);

%allocators(double);
</pre>
</div>
<p> Now, in a script:</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; from example import *
&gt;&gt;&gt; a = malloc_int()
&gt;&gt;&gt; a
'_000efa70_p_int'
&gt;&gt;&gt; free_int(a)
&gt;&gt;&gt; b = malloc_intp()
&gt;&gt;&gt; b
'_000efb20_p_p_int'
&gt;&gt;&gt; free_intp(b)
&gt;&gt;&gt; c = calloc_double(50)
&gt;&gt;&gt; c
'_000fab98_p_double'
&gt;&gt;&gt; c = realloc_double(100000)
&gt;&gt;&gt; free_double(c)
&gt;&gt;&gt; print sizeof_double
8
&gt;&gt;&gt;
</pre>
</div>
<h3><a name="Library_nn7">11.2.4 cdata.i</a></h3>
<p> The <tt>cdata.i</tt> module defines functions for converting raw C
 data to and from strings in the target language. The primary
 applications of this module would be packing/unpacking of binary data
 structures---for instance, if you needed to extract data from a buffer.
 The target language must support strings with embedded binary data in
 order for this to work.</p>
<p><b> <tt>const char *cdata(void *ptr, size_t nbytes)</tt></b></p>
<div class="indent">
<p> Converts <tt>nbytes</tt> of data at <tt>ptr</tt> into a string. <tt>
ptr</tt> can be any pointer.</p>
</div>
<p><b> <tt>void memmove(void *ptr, const char *s)</tt></b></p>
<div class="indent">
<p> Copies all of the string data in <tt>s</tt> into the memory pointed
 to by <tt>ptr</tt>. The string may contain embedded NULL bytes. This is
 actually a wrapper to the standard C library <tt>memmove</tt> function,
 which is declared as<b> <tt>void memmove(void *ptr, const void *src,
 size_t n)</tt></b>. The <tt>src</tt> and length <tt>n</tt> parameters
 are extracted from the language specific string <tt>s</tt> in the
 underlying wrapper code.</p>
</div>
<p> One use of these functions is packing and unpacking data from
 memory. Here is a short example:</p>
<div class="code">
<pre>
// SWIG interface
%module example
%include &quot;carrays.i&quot;
%include &quot;cdata.i&quot;

%array_class(int, intArray);
</pre>
</div>
<p> Python example:</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; a = intArray(10)
&gt;&gt;&gt; for i in range(0, 10):
...    a[i] = i
&gt;&gt;&gt; b = cdata(a, 40)
&gt;&gt;&gt; b
'\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00\x04
\x00\x00\x00\x05\x00\x00\x00\x06\x00\x00\x00\x07\x00\x00\x00\x08\x00\x00\x00\t'
&gt;&gt;&gt; c = intArray(10)
&gt;&gt;&gt; memmove(c, b)
&gt;&gt;&gt; print c[4]
4
&gt;&gt;&gt;
</pre>
</div>
<p> Since the size of data is not always known, the following macro is
 also defined:</p>
<p><b> <tt>%cdata(type [, name=type])</tt></b></p>
<div class="indent">
<p> Generates the following function for extracting C data for a given
 type.</p>
<div class="code">
<pre>
char *cdata_<em>name</em>(type* ptr, int nitems)
</pre>
</div>
<p> <tt>nitems</tt> is the number of items of the given type to extract.</p>
</div>
<p><b> Note:</b> These functions provide direct access to memory and can
 be used to overwrite data. Clearly they are unsafe.</p>
<h2><a name="Library_nn8">11.3 C string handling</a></h2>
<p> A common problem when working with C programs is dealing with
 functions that manipulate raw character data using <tt>char *</tt>. In
 part, problems arise because there are different interpretations of <tt>
char *</tt>---it could be a NULL-terminated string or it could point to
 binary data. Moreover, functions that manipulate raw strings may mutate
 data, perform implicit memory allocations, or utilize fixed-sized
 buffers.</p>
<p> The problems (and perils) of using <tt>char *</tt> are well-known.
 However, SWIG is not in the business of enforcing morality. The modules
 in this section provide basic functionality for manipulating raw C
 strings.</p>
<h3><a name="Library_nn9">11.3.1 Default string handling</a></h3>
<p> Suppose you have a C function with this prototype:</p>
<div class="code">
<pre>
char *foo(char *s);
</pre>
</div>
<p> The default wrapping behavior for this function is to set <tt>s</tt>
 to a raw <tt>char *</tt> that refers to the internal string data in the
 target language. In other words, if you were using a language like Tcl,
 and you wrote this,</p>
<div class="targetlang">
<pre>
% foo Hello
</pre>
</div>
<p> then <tt>s</tt> would point to the representation of &quot;Hello&quot; inside
 the Tcl interpreter. When returning a <tt>char *</tt>, SWIG assumes
 that it is a NULL-terminated string and makes a copy of it. This gives
 the target language its own copy of the result.</p>
<p> There are obvious problems with the default behavior. First, since a
 <tt>char *</tt> argument points to data inside the target language, it
 is<b> NOT</b> safe for a function to modify this data (doing so may
 corrupt the interpreter and lead to a crash). Furthermore, the default
 behavior does not work well with binary data. Instead, strings are
 assumed to be NULL-terminated.</p>
<h3><a name="Library_nn10">11.3.2 Passing binary data</a></h3>
<p> If you have a function that expects binary data,</p>
<div class="code">
<pre>
size_t parity(char *str, size_t len, size_t initial);
</pre>
</div>
<p> you can wrap the parameters <tt>(char *str, size_t len)</tt> as a
 single argument using a typemap. Just do this:</p>
<div class="code">
<pre>
%apply (char *STRING, size_t LENGTH) { (char *str, size_t len) };
...
size_t parity(char *str, size_t len, size_t initial);
</pre>
</div>
<p> Now, in the target language, you can use binary string data like
 this:</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; s = &quot;H\x00\x15eg\x09\x20&quot;
&gt;&gt;&gt; parity(s, 0)
</pre>
</div>
<p> In the wrapper function, the passed string will be expanded to a
 pointer and length parameter. The <tt>(char *STRING, int LENGTH)</tt>
 multi-argument typemap is also available in addition to <tt>(char
 *STRING, size_t LENGTH)</tt>.</p>
<h3><a name="Library_nn11">11.3.3 Using %newobject to release memory</a></h3>
<p> If you have a function that allocates memory like this,</p>
<div class="code">
<pre>
char *foo() {
  char *result = (char *) malloc(...);
  ...
  return result;
}
</pre>
</div>
<p> then the SWIG generated wrappers will have a memory leak--the
 returned data will be copied into a string object and the old contents
 ignored.</p>
<p> To fix the memory leak, use the <tt>%newobject</tt> directive.</p>
<div class="code">
<pre>
%newobject foo;
...
char *foo();
</pre>
</div>
<p> This will release the result if the appropriate target language
 support is available. SWIG provides the appropriate &quot;newfree&quot; typemap
 for <tt>char *</tt> so that the memory is released, however, you may
 need to provide your own &quot;newfree&quot; typemap for other types. See <a href="#Customization_ownership">
Object ownership and %newobject</a> for more details.</p>
<h3><a name="Library_nn12">11.3.4 cstring.i</a></h3>
<p> The <tt>cstring.i</tt> library file provides a collection of macros
 for dealing with functions that either mutate string arguments or which
 try to output string data through their arguments. An example of such a
 function might be this rather questionable implementation:</p>
<div class="code">
<pre>
void get_path(char *s) {
  // Potential buffer overflow---uh, oh.
  sprintf(s, &quot;%s/%s&quot;, base_directory, sub_directory);
}
...
// Somewhere else in the C program
{
  char path[1024];
  ...
  get_path(path);
  ...
}
</pre>
</div>
<p> (Off topic rant: If your program really has functions like this, you
 would be well-advised to replace them with safer alternatives involving
 bounds checking).</p>
<p> The macros defined in this module all expand to various combinations
 of typemaps. Therefore, the same pattern matching rules and ideas
 apply.</p>
<p><b> %cstring_bounded_output(parm, maxsize)</b></p>
<div class="indent">
<p> Turns parameter <tt><em>parm</em></tt> into an output value. The
 output string is assumed to be NULL-terminated and smaller than <tt><em>
maxsize</em></tt> characters. Here is an example:</p>
<div class="code">
<pre>
%cstring_bounded_output(char *path, 1024);
...
void get_path(char *path);
</pre>
</div>
<p> In the target language:</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; get_path()
/home/beazley/packages/Foo/Bar
&gt;&gt;&gt;
</pre>
</div>
<p> Internally, the wrapper function allocates a small buffer (on the
 stack) of the requested size and passes it as the pointer value. Data
 stored in the buffer is then returned as a function return value. If
 the function already returns a value, then the return value and the
 output string are returned together (multiple return values).<b> If
 more than <tt><em>maxsize</em></tt> bytes are written, your program
 will crash with a buffer overflow!</b></p>
</div>
<p><b> %cstring_chunk_output(parm, chunksize)</b></p>
<div class="indent">
<p> Turns parameter <tt><em>parm</em></tt> into an output value. The
 output string is always <tt><em>chunksize</em></tt> and may contain
 binary data. Here is an example:</p>
<div class="code">
<pre>
%cstring_chunk_output(char *packet, PACKETSIZE);
...
void get_packet(char *packet);
</pre>
</div>
<p> In the target language:</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; get_packet()
'\xa9Y:\xf6\xd7\xe1\x87\xdbH;y\x97\x7f\xd3\x99\x14V\xec\x06\xea\xa2\x88'
&gt;&gt;&gt;
</pre>
</div>
<p> This macro is essentially identical to <tt>%cstring_bounded_output</tt>
. The only difference is that the result is always <tt><em>chunksize</em>
</tt> characters. Furthermore, the result can contain binary data.<b> If
 more than <tt><em>maxsize</em></tt> bytes are written, your program
 will crash with a buffer overflow!</b></p>
</div>
<p><b> %cstring_bounded_mutable(parm, maxsize)</b></p>
<div class="indent">
<p> Turns parameter <tt><em>parm</em></tt> into a mutable string
 argument. The input string is assumed to be NULL-terminated and smaller
 than <tt><em>maxsize</em></tt> characters. The output string is also
 assumed to be NULL-terminated and less than <tt><em>maxsize</em></tt>
 characters.</p>
<div class="code">
<pre>
%cstring_bounded_mutable(char *ustr, 1024);
...
void make_upper(char *ustr);
</pre>
</div>
<p> In the target language:</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; make_upper(&quot;hello world&quot;)
'HELLO WORLD'
&gt;&gt;&gt;
</pre>
</div>
<p> Internally, this macro is almost exactly the same as <tt>
%cstring_bounded_output</tt>. The only difference is that the parameter
 accepts an input value that is used to initialize the internal buffer.
 It is important to emphasize that this function does not mutate the
 string value passed---instead it makes a copy of the input value,
 mutates it, and returns it as a result.<b> If more than <tt><em>maxsize</em>
</tt> bytes are written, your program will crash with a buffer overflow!</b>
</p>
</div>
<p><b> %cstring_mutable(parm [, expansion])</b></p>
<div class="indent">
<p> Turns parameter <tt><em>parm</em></tt> into a mutable string
 argument. The input string is assumed to be NULL-terminated. An
 optional parameter <tt><em>expansion</em></tt> specifies the number of
 extra characters by which the string might grow when it is modified.
 The output string is assumed to be NULL-terminated and less than the
 size of the input string plus any expansion characters.</p>
<div class="code">
<pre>
%cstring_mutable(char *ustr);
...
void make_upper(char *ustr);

%cstring_mutable(char *hstr, HEADER_SIZE);
...
void attach_header(char *hstr);
</pre>
</div>
<p> In the target language:</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; make_upper(&quot;hello world&quot;)
'HELLO WORLD'
&gt;&gt;&gt; attach_header(&quot;Hello world&quot;)
'header: Hello world'
&gt;&gt;&gt;
</pre>
</div>
<p> This macro differs from <tt>%cstring_bounded_mutable()</tt> in that
 a buffer is dynamically allocated (on the heap using <tt>malloc/new</tt>
). This buffer is always large enough to store a copy of the input value
 plus any expansion bytes that might have been requested. It is
 important to emphasize that this function does not directly mutate the
 string value passed---instead it makes a copy of the input value,
 mutates it, and returns it as a result.<b> If the function expands the
 result by more than <tt><em>expansion</em></tt> extra bytes, then the
 program will crash with a buffer overflow!</b></p>
</div>
<p><b> %cstring_output_maxsize(parm, maxparm)</b></p>
<div class="indent">
<p> This macro is used to handle bounded character output functions
 where both a <tt>char *</tt> and a maximum length parameter are
 provided. As input, a user simply supplies the maximum length. The
 return value is assumed to be a NULL-terminated string.</p>
<div class="code">
<pre>
%cstring_output_maxsize(char *path, int maxpath);
...
void get_path(char *path, int maxpath);
</pre>
</div>
<p> In the target language:</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; get_path(1024)
'/home/beazley/Packages/Foo/Bar'
&gt;&gt;&gt;
</pre>
</div>
<p> This macro provides a safer alternative for functions that need to
 write string data into a buffer. User supplied buffer size is used to
 dynamically allocate memory on heap. Results are placed into that
 buffer and returned as a string object.</p>
</div>
<p><b> %cstring_output_withsize(parm, maxparm)</b></p>
<div class="indent">
<p> This macro is used to handle bounded character output functions
 where both a <tt>char *</tt> and a pointer <tt>int *</tt> are passed.
 Initially, the <tt>int *</tt> parameter points to a value containing
 the maximum size. On return, this value is assumed to contain the
 actual number of bytes. As input, a user simply supplies the maximum
 length. The output value is a string that may contain binary data.</p>
<div class="code">
<pre>
%cstring_output_withsize(char *data, int *maxdata);
...
void get_data(char *data, int *maxdata);
</pre>
</div>
<p> In the target language:</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; get_data(1024)
'x627388912'
&gt;&gt;&gt; get_data(1024)
'xyzzy'
&gt;&gt;&gt;
</pre>
</div>
<p> This macro is a somewhat more powerful version of <tt>
%cstring_output_chunk()</tt>. Memory is dynamically allocated and can be
 arbitrary large. Furthermore, a function can control how much data is
 actually returned by changing the value of the <tt>maxparm</tt>
 argument.</p>
</div>
<p><b> %cstring_output_allocate(parm, release)</b></p>
<div class="indent">
<p> This macro is used to return strings that are allocated within the
 program and returned in a parameter of type <tt>char **</tt>. For
 example:</p>
<div class="code">
<pre>
void foo(char **s) {
  *s = (char *) malloc(64);
  sprintf(*s, &quot;Hello world\n&quot;);
}
</pre>
</div>
<p> The returned string is assumed to be NULL-terminated. <tt><em>
release</em></tt> specifies how the allocated memory is to be released
 (if applicable). Here is an example:</p>
<div class="code">
<pre>
%cstring_output_allocate(char **s, free(*$1));
...
void foo(char **s);
</pre>
</div>
<p> In the target language:</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; foo()
'Hello world\n'
&gt;&gt;&gt;
</pre>
</div></div>
<p><b> %cstring_output_allocate_size(parm, szparm, release)</b></p>
<div class="indent">
<p> This macro is used to return strings that are allocated within the
 program and returned in two parameters of type <tt>char **</tt> and <tt>
int *</tt>. For example:</p>
<div class="code">
<pre>
void foo(char **s, int *sz) {
  *s = (char *) malloc(64);
  *sz = 64;
  // Write some binary data
  ...
}
</pre>
</div>
<p> The returned string may contain binary data. <tt><em>release</em></tt>
 specifies how the allocated memory is to be released (if applicable).
 Here is an example:</p>
<div class="code">
<pre>
%cstring_output_allocate_size(char **s, int *slen, free(*$1));
...
void foo(char **s, int *slen);
</pre>
</div>
<p> In the target language:</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; foo()
'\xa9Y:\xf6\xd7\xe1\x87\xdbH;y\x97\x7f\xd3\x99\x14V\xec\x06\xea\xa2\x88'
&gt;&gt;&gt;
</pre>
</div>
<p> This is the safest and most reliable way to return binary string
 data in SWIG. If you have functions that conform to another prototype,
 you might consider wrapping them with a helper function. For example,
 if you had this:</p>
<div class="code">
<pre>
char  *get_data(int *len);
</pre>
</div>
<p> You could wrap it with a function like this:</p>
<div class="code">
<pre>
void my_get_data(char **result, int *len) {
  *result = get_data(len);
}
</pre>
</div></div>
<p><b> Comments:</b></p>
<ul>
<li>Support for the <tt>cstring.i</tt> module depends on the target
 language. Not all SWIG modules currently support this library.</li>
<li>Reliable handling of raw C strings is a delicate topic. There are
 many ways to accomplish this in SWIG. This library provides support for
 a few common techniques.</li>
<li>If used in C++, this library uses <tt>new</tt> and <tt>delete []</tt>
 for memory allocation. If using C, the library uses <tt>malloc()</tt>
 and <tt>free()</tt>.</li>
<li>Rather than manipulating <tt>char *</tt> directly, you might
 consider using a special string structure or class instead.</li>
</ul>
<h2><a name="Library_stl_cpp_library">11.4 STL/C++ library</a></h2>
<p> The library modules in this section provide access to parts of the
 standard C++ library including the STL. SWIG support for the STL is an
 ongoing effort. Support is quite comprehensive for some language
 modules but some of the lesser used modules do not have quite as much
 library code written.</p>
<p> The following table shows which C++ classes are supported and the
 equivalent SWIG interface library file for the C++ library.</p>
<table BORDER summary="SWIG C++ library files">
<tr VALIGN="TOP"><td><b>C++ class</b></td><td><b>C++ Library file</b></td><td>
<b>SWIG Interface library file</b></td></tr>
<tr><td>std::array (C++11)</td><td>array</td><td>std_array.i</td></tr>
<tr><td>std::auto_ptr</td><td>memory</td><td>std_auto_ptr.i</td></tr>
<tr><td>std::complex</td><td>complex</td><td>std_complex.i</td></tr>
<tr><td>std::deque</td><td>deque</td><td>std_deque.i</td></tr>
<tr><td>std::list</td><td>list</td><td>std_list.i</td></tr>
<tr><td>std::map</td><td>map</td><td>std_map.i</td></tr>
<tr><td>std::multimap (C++11)</td><td>multimap</td><td>std_multimap.i</td>
</tr>
<tr><td>std::multiset (C++11)</td><td>multiset</td><td>std_multiset.i</td>
</tr>
<tr><td>std::pair</td><td>utility</td><td>std_pair.i</td></tr>
<tr><td>std::set</td><td>set</td><td>std_set.i</td></tr>
<tr><td>std::string</td><td>string</td><td>std_string.i</td></tr>
<tr><td>std::unordered_map (C++11)</td><td>unordered_map</td><td>
std_unordered_map.i</td></tr>
<tr><td>std::unordered_multimap (C++11)</td><td>unordered_multimap</td><td>
std_unordered_multimap.i</td></tr>
<tr><td>std::unordered_multiset (C++11)</td><td>unordered_multiset</td><td>
std_unordered_multiset.i</td></tr>
<tr><td>std::unordered_set (C++11)</td><td>unordered_set</td><td>
std_unordered_set.i</td></tr>
<tr><td>std::vector</td><td>vector</td><td>std_vector.i</td></tr>
<tr><td>std::wstring</td><td>wstring</td><td>std_wstring.i</td></tr>
<tr><td>std::shared_ptr (C++11)</td><td>shared_ptr</td><td>
std_shared_ptr.i</td></tr>
</table>
<p> The list is by no means complete; some language modules support a
 subset of the above and some support additional STL classes. Please
 look for the library files in the appropriate language library
 directory.</p>
<h3><a name="Library_std_string">11.4.1 std::string</a></h3>
<p> The <tt>std_string.i</tt> library provides typemaps for converting
 C++ <tt>std::string</tt> objects to and from strings in the target
 scripting language. For example:</p>
<div class="code">
<pre>
%module example
%include &quot;std_string.i&quot;

std::string foo();
void        bar(const std::string &amp;x);
</pre>
</div>
<p> In the target language:</p>
<div class="targetlang">
<pre>
x = foo();                # Returns a string object
bar(&quot;Hello World&quot;);       # Pass string as std::string
</pre>
</div>
<p> A common problem that people encounter is that of classes/structures
 containing a <tt>std::string</tt>. This can be overcome by defining a
 typemap. For example:</p>
<div class="code">
<pre>
%module example
%include &quot;std_string.i&quot;

%apply const std::string&amp; {std::string* foo};

struct my_struct
{
  std::string foo;
};
</pre>
</div>
<p> In the target language:</p>
<div class="targetlang">
<pre>
x = my_struct();
x.foo = &quot;Hello World&quot;;    # assign with string
print x.foo;              # print as string
</pre>
</div>
<p> This module only supports types <tt>std::string</tt> and <tt>const
 std::string &amp;</tt>. Pointers and non-const references are left
 unmodified and returned as SWIG pointers.</p>
<p> This library file is fully aware of C++ namespaces. If you export <tt>
std::string</tt> or rename it with a typedef, make sure you include
 those declarations in your interface. For example:</p>
<div class="code">
<pre>
%module example
%include &quot;std_string.i&quot;

using namespace std;
typedef std::string String;
...
void foo(string s, const String &amp;t);     // std_string typemaps still applied
</pre>
</div>
<h3><a name="Library_std_vector">11.4.2 std::vector</a></h3>
<p> The <tt>std_vector.i</tt> library provides support for the C++ <tt>
std::vector</tt> class in the STL. Using this library involves the use
 of the <tt>%template</tt> directive. All you need to do is to
 instantiate different versions of <tt>vector</tt> for the types that
 you want to use. For example:</p>
<div class="code">
<pre>
%module example
%include &quot;std_vector.i&quot;

namespace std {
  %template(vectori) vector&lt;int&gt;;
  %template(vectord) vector&lt;double&gt;;
};
</pre>
</div>
<p> When a template <tt>vector&lt;X&gt;</tt> is instantiated a number of
 things happen:</p>
<ul>
<li>A class that exposes the C++ API is created in the target language .
 This can be used to create objects, invoke methods, etc. This class is
 currently a subset of the real STL vector class.</li>
<li>Input typemaps are defined for <tt>vector&lt;X&gt;</tt>, <tt>const
 vector&lt;X&gt; &amp;</tt>, and <tt>const vector&lt;X&gt; *</tt>. For each of these, a
 pointer <tt>vector&lt;X&gt; *</tt> may be passed or a native list object in
 the target language.</li>
<li>An output typemap is defined for <tt>vector&lt;X&gt;</tt>. In this case,
 the values in the vector are expanded into a list object in the target
 language.</li>
<li>For all other variations of the type, the wrappers expect to receive
 a <tt>vector&lt;X&gt; *</tt> object in the usual manner.</li>
<li>An exception handler for <tt>std::out_of_range</tt> is defined.</li>
<li>Optionally, special methods for indexing, item retrieval, slicing,
 and element assignment may be defined. This depends on the target
 language.</li>
</ul>
<p> To illustrate the use of this library, consider the following
 functions:</p>
<div class="code">
<pre>
/* File : example.h */

#include &lt;vector&gt;
#include &lt;algorithm&gt;
#include &lt;functional&gt;
#include &lt;numeric&gt;

double average(std::vector&lt;int&gt; v) {
  return std::accumulate(v.begin(), v.end(), 0.0)/v.size();
}

std::vector&lt;double&gt; half(const std::vector&lt;double&gt;&amp; v) {
  std::vector&lt;double&gt; w(v);
  for (unsigned int i=0; i&lt;w.size(); i++)
    w[i] /= 2.0;
  return w;
}

void halve_in_place(std::vector&lt;double&gt;&amp; v) {
  for (std::vector&lt;double&gt;::iterator it = v.begin(); it != v.end(); ++it)
    *it /= 2.0;
}
</pre>
</div>
<p> To wrap with SWIG, you might write the following:</p>
<div class="code">
<pre>
%module example
%{
#include &quot;example.h&quot;
%}

%include &quot;std_vector.i&quot;
// Instantiate templates used by example
namespace std {
  %template(IntVector) vector&lt;int&gt;;
  %template(DoubleVector) vector&lt;double&gt;;
}

// Include the header file with above prototypes
%include &quot;example.h&quot;
</pre>
</div>
<p> Now, to illustrate the behavior in the scripting interpreter,
 consider this Python example:</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; from example import *
&gt;&gt;&gt; iv = IntVector(4)         # Create an vector&lt;int&gt;
&gt;&gt;&gt; for i in range(0, 4):
...      iv[i] = i
&gt;&gt;&gt; average(iv)               # Call method
1.5
&gt;&gt;&gt; average([0, 1, 2, 3])        # Call with list
1.5
&gt;&gt;&gt; half([1, 2, 3])             # Half a list
(0.5, 1.0, 1.5)
&gt;&gt;&gt; halve_in_place([1, 2, 3])   # Oops
Traceback (most recent call last):
  File &quot;&lt;stdin&gt;&quot;, line 1, in ?
TypeError: Type error. Expected _p_std__vectorTdouble_t
&gt;&gt;&gt; dv = DoubleVector(4)
&gt;&gt;&gt; for i in range(0, 4):
...       dv[i] = i
&gt;&gt;&gt; halve_in_place(dv)       # Ok
&gt;&gt;&gt; for i in dv:
...       print i
...
0.0
0.5
1.0
1.5
&gt;&gt;&gt; dv[20] = 4.5
Traceback (most recent call last):
  File &quot;&lt;stdin&gt;&quot;, line 1, in ?
  File &quot;example.py&quot;, line 81, in __setitem__
    def __setitem__(*args): return apply(examplec.DoubleVector___setitem__, args)
IndexError: vector index out of range
&gt;&gt;&gt;
</pre>
</div>
<p> This library module is fully aware of C++ namespaces. If you use
 vectors with other names, make sure you include the appropriate <tt>
using</tt> or typedef directives. For example:</p>
<div class="code">
<pre>
%include &quot;std_vector.i&quot;

namespace std {
  %template(IntVector) vector&lt;int&gt;;
}

using namespace std;
typedef std::vector Vector;

void foo(vector&lt;int&gt; *x, const Vector &amp;x);
</pre>
</div>
<p><b> Note:</b> This module makes use of several advanced SWIG features
 including templatized typemaps and template partial specialization. If
 you are trying to wrap other C++ code with templates, you might look at
 the code contained in <tt>std_vector.i</tt>. Alternatively, you can
 show them the code if you want to make their head explode.</p>
<p><b> Note:</b> This module is defined for all SWIG target languages.
 However argument conversion details and the public API exposed to the
 interpreter vary.</p>
<h3><a name="Library_stl_exceptions">11.4.3 STL exceptions</a></h3>
<p> Many of the STL wrapper functions add parameter checking and will
 throw a language dependent error/exception should the values not be
 valid. The classic example is array bounds checking. The library
 wrappers are written to throw a C++ exception in the case of error. The
 C++ exception in turn gets converted into an appropriate
 error/exception for the target language. By and large this handling
 should not need customising, however, customisation can easily be
 achieved by supplying appropriate &quot;throws&quot; typemaps. For example:</p>
<div class="code">
<pre>
%module example
%include &quot;std_vector.i&quot;
%typemap(throws) std::out_of_range {
  // custom exception handler
}
%template(VectInt) std::vector&lt;int&gt;;
</pre>
</div>
<p> The custom exception handler might, for example, log the exception
 then convert it into a specific error/exception for the target
 language.</p>
<p> When using the STL it is advisable to add in an exception handler to
 catch all STL exceptions. The <tt>%exception</tt> directive can be used
 by placing the following code before any other methods or libraries to
 be wrapped:</p>
<div class="code">
<pre>
%include &quot;exception.i&quot;

%exception {
  try {
    $action
  } catch (const std::exception&amp; e) {
    SWIG_exception(SWIG_RuntimeError, e.what());
  }
}
</pre>
</div>
<p> Any thrown STL exceptions will then be gracefully handled instead of
 causing a crash.</p>
<h3><a name="Library_std_shared_ptr">11.4.4 shared_ptr smart pointer</a></h3>
<h4><a name="Library_shared_ptr_basics">11.4.4.1 shared_ptr basics</a></h4>
<p> Some target languages have support for handling the shared_ptr
 reference counted smart pointer. This smart pointer is available in the
 standard C++11 library as <tt>std::shared_ptr</tt>. It was also in TR1
 as <tt>std::tr1::shared_ptr</tt> before it was fully standardized.
 Support for the widely used <tt>boost::shared_ptr</tt> is also
 available.</p>
<p> In order to use <tt>std::shared_ptr</tt>, the <tt>std_shared_ptr.i</tt>
 library file should be included:</p>
<div class="code">
<pre>
%include &lt;std_shared_ptr.i&gt;
</pre>
</div>
<p> The pre-standard <tt>std::tr1::shared_ptr</tt> can be used by
 including the following macro before including the <tt>std_shared_ptr.i</tt>
 library file:</p>
<div class="code">
<pre>
#define SWIG_SHARED_PTR_SUBNAMESPACE tr1
%include &lt;std_shared_ptr.i&gt;
</pre>
</div>
<p> In order to use <tt>boost::shared_ptr</tt>, the <tt>
boost_shared_ptr.i</tt> library file should be included:</p>
<div class="code">
<pre>
%include &lt;boost_shared_ptr.i&gt;
</pre>
</div>
<p> You can only use one of these variants of shared_ptr in your
 interface file at a time. and all three variants must be used in
 conjunction with the <tt>%shared_ptr(T)</tt> macro, where <tt>T</tt> is
 the underlying pointer type equating to usage <tt>shared_ptr&lt;T&gt;</tt>.
 The type <tt>T</tt> must be non-primitive. A simple example
 demonstrates usage:</p>
<div class="code">
<pre>
%module example
%include &lt;boost_shared_ptr.i&gt;
%shared_ptr(IntValue)

%inline %{
#include &lt;boost/shared_ptr.hpp&gt;

struct IntValue {
  int value;
  IntValue(int v) : value(v) {}
};

static int extractValue(const IntValue &amp;t) {
  return t.value;
}

static int extractValueSmart(boost::shared_ptr&lt;IntValue&gt; t) {
  return t-&gt;value;
}
%}
</pre>
</div>
<p> Note that the <tt>%shared_ptr(IntValue)</tt> declaration occurs
 after the inclusion of the <tt>boost_shared_ptr.i</tt> library which
 provides the macro and, very importantly, before any usage or
 declaration of the type, <tt>IntValue</tt>. The <tt>%shared_ptr</tt>
 macro provides, a few things for handling this smart pointer, but
 mostly a number of typemaps. These typemaps override the default
 typemaps so that the underlying proxy class is stored and passed around
 as a pointer to a <tt>shared_ptr</tt> instead of a plain pointer to the
 underlying type. This approach means that any instantiation of the type
 can be passed to methods taking the type by value, reference, pointer
 or as a smart pointer. The interested reader might want to look at the
 generated code, however, usage is simple and no different handling is
 required from the target language. For example, a simple use case of
 the above code from Java would be:</p>
<div class="targetlang">
<pre>
IntValue iv = new IntValue(1234);
int val1 = example.extractValue(iv);
int val2 = example.extractValueSmart(iv);
System.out.println(val1 + &quot; &quot; + val2);
</pre>
</div>
<h4><a name="Library_shared_ptr_inheritance">11.4.4.2 shared_ptr and
 inheritance</a></h4>
<p> The shared_ptr library works quite differently to SWIG's normal, but
 somewhat limited, <a href="#SWIGPlus_smart_pointers">smart pointer
 handling</a>. The shared_ptr library does not generate extra wrappers,
 just for smart pointer handling, in addition to the proxy class. The
 normal proxy class including inheritance relationships is generated as
 usual. The only real change introduced by the <tt>%shared_ptr</tt>
 macro is that the proxy class stores a pointer to the shared_ptr
 instance instead of a raw pointer to the instance. A proxy class
 derived from a base which is being wrapped with shared_ptr can and<b>
 must</b> be wrapped as a shared_ptr too. In other words all classes in
 an inheritance hierarchy must all be used with the <tt>%shared_ptr</tt>
 macro. For example the following code can be used with the base class
 shown earlier:</p>
<div class="code">
<pre>
%shared_ptr(DerivedIntValue)
%inline %{
struct DerivedIntValue : IntValue {
  DerivedIntValue(int value) : IntValue(value) {}
  ...
};
%}
</pre>
</div>
<p> A shared_ptr of the derived class can now be passed to a method
 where the base is expected in the target language, just as it can in
 C++:</p>
<div class="targetlang">
<pre>
DerivedIntValue div = new DerivedIntValue(5678);
int val3 = example.extractValue(div);
int val4 = example.extractValueSmart(div);
</pre>
</div>
<p> If the <tt>%shared_ptr</tt> macro is omitted for any class in the
 inheritance hierarchy, SWIG will warn about this and the generated code
 may or may not result in a C++ compilation error. For example, the
 following input:</p>
<div class="code">
<pre>
%include &quot;boost_shared_ptr.i&quot;
%shared_ptr(Parent);

%inline %{
  #include &lt;boost/shared_ptr.hpp&gt;
  struct GrandParent {
    virtual ~GrandParent() {}
  };

  struct Parent : GrandParent {
    virtual ~Parent() {}
  };

  struct Child : Parent {
    virtual ~Child() {}
  };
%}
</pre>
</div>
<p> warns about the missing smart pointer information:</p>
<div class="shell">
<pre>
example.i:12: Warning 520: Base class 'GrandParent' of 'Parent' is not similarly marked as a smart pointer.
example.i:16: Warning 520: Derived class 'Child' of 'Parent' is not similarly marked as a smart pointer.
</pre>
</div>
<p> Adding the missing <tt>%shared_ptr</tt> macros will fix this:</p>
<div class="code">
<pre>
%include &lt;boost_shared_ptr.i&gt;
%shared_ptr(GrandParent);
%shared_ptr(Parent);
%shared_ptr(Child);

... as before ...
</pre>
</div>
<h4><a name="Library_shared_ptr_overloading">11.4.4.3 shared_ptr and
 method overloading</a></h4>
<p> A C++ compiler can disambiguate a method overloaded by a shared_ptr
 and one using the raw underlying type. For example, either one of these
 methods can be called in C++:</p>
<div class="code">
<pre>
int age(std::shared_ptr&lt;GrandParent&gt; num);
int age(GrandParent&amp; num);
</pre>
</div>
<p> When wrapped by SWIG, disambiguation is not possible using the
 overloaded names as there is just one equivalent type (<tt>GrandParent</tt>
) in the target language. SWIG will choose to wrap just the first method
 by default. <a href="#SWIGPlus_nn25">Ambiguity in overloading</a>
 discusses ways to control which method(s) gets wrapped using <tt>
%ignore</tt> or <tt>%rename</tt>. For the interested reader, SWIG
 detects that they are equivalent types via the <a href="#Typemaps_typecheck_pointer">
typecheck typemaps</a> in the shared_ptr library.</p>
<h4><a name="Library_shared_ptr_templates">11.4.4.4 shared_ptr and
 templates</a></h4>
<p> The <tt>%shared_ptr</tt> macro should be used for all the required
 instantiations of the template before each of the <tt>%template</tt>
 instantiations. For example, consider <tt>number.h</tt> containing the
 following illustrative template:</p>
<div class="code">
<pre>
#include &lt;memory&gt;

template&lt;int N&gt; struct Number {
  int num;
  Number() : num(N) {}
  static std::shared_ptr&lt;Number&lt;N&gt;&gt; make() { return std::make_shared&lt;Number&lt;N&gt;&gt;(); }
};
</pre>
</div>
<p> The SWIG code below shows the required ordering:</p>
<div class="code">
<pre>
%include &lt;std_shared_ptr.i&gt;

%shared_ptr(Number&lt;10&gt;);
%shared_ptr(Number&lt;42&gt;);

%{
  #include &quot;number.h&quot;
%}
%include &quot;number.h&quot;

%template(Number10) Number&lt;10&gt;;
%template(Number42) Number&lt;42&gt;;
</pre>
</div>
<h4><a name="Library_shared_ptr_directors">11.4.4.5 shared_ptr and
 directors</a></h4>
<p> The languages that support shared_ptr also have support for using
 shared_ptr with directors.</p>
<h3><a name="Library_std_auto_ptr">11.4.5 auto_ptr smart pointer</a></h3>
<p> While <tt>std::auto_ptr</tt> is deprecated in C++11, some existing
 code may still be using it, so SWIG provides limited support for this
 class: <tt>std_auto_ptr.i</tt> defines the typemaps which apply to the
 functions returning objects of this type. Any other use of <tt>
std_auto_ptr.i</tt> is not directly supported.</p>
<p> A typical example of use would be</p>
<div class="code">
<pre>
%include &lt;std_auto_ptr.i&gt;

%auto_ptr(Klass)
%inline %{
class Klass {
public:
  // Factory function creating objects of this class:
  static std::auto_ptr&lt;Klass&gt; Create(int value) {
    return std::auto_ptr&lt;Klass&gt;(new Klass(value));
  }

  int getValue() const { return m_value; }

private:
  DerivedIntValue(int value) : m_value(value) {}
  int m_value;
};
%}
</pre>
</div>
<p> The returned objects can be used naturally from the target language,
 e.g. from C#:</p>
<div class="targetlang">
<pre>
Klass k = Klass.Create(17);
int value = k.getValue();
</pre>
</div>
<h2><a name="Library_nn16">11.5 Utility Libraries</a></h2>
<h3><a name="Library_nn17">11.5.1 exception.i</a></h3>
<p> The <tt>exception.i</tt> library provides a language-independent
 function for raising a run-time exception in the target language. This
 library is largely used by the SWIG library writers. If possible, use
 the error handling scheme available to your target language as there is
 greater flexibility in what errors/exceptions can be thrown.</p>
<p><b> <tt>SWIG_exception(int code, const char *message)</tt></b></p>
<div class="indent">
<p> Raises an exception in the target language. <tt>code</tt> is one of
 the following symbolic constants:</p>
<div class="code">
<pre>
SWIG_MemoryError
SWIG_IOError
SWIG_RuntimeError
SWIG_IndexError
SWIG_TypeError
SWIG_DivisionByZero
SWIG_OverflowError
SWIG_SyntaxError
SWIG_ValueError
SWIG_SystemError
</pre>
</div>
<p> <tt>message</tt> is a string indicating more information about the
 problem.</p>
</div>
<p> The primary use of this module is in writing language-independent
 exception handlers. For example:</p>
<div class="code">
<pre>
%include &quot;exception.i&quot;
%exception std::vector::getitem {
  try {
    $action
  } catch (std::out_of_range&amp; e) {
    SWIG_exception(SWIG_IndexError, const_cast&lt;char*&gt;(e.what()));
  }
}
</pre>
</div><HR NOSHADE>
<h1><a name="Arguments">12 Argument Handling</a></h1>

<!-- INDEX -->
<div class="sectiontoc">
<ul>
<li><a href="#Arguments_nn2">The typemaps.i library</a>
<ul>
<li><a href="#Arguments_nn3">Introduction</a></li>
<li><a href="#Arguments_nn4">Input parameters</a></li>
<li><a href="#Arguments_nn5">Output parameters</a></li>
<li><a href="#Arguments_nn6">Input/Output parameters</a></li>
<li><a href="#Arguments_nn7">Using different names</a></li>
</ul>
</li>
<li><a href="#Arguments_nn8">Applying constraints to input values</a>
<ul>
<li><a href="#Arguments_nn9">Simple constraint example</a></li>
<li><a href="#Arguments_nn10">Constraint methods</a></li>
<li><a href="#Arguments_nn11">Applying constraints to new datatypes</a></li>
</ul>
</li>
</ul>
</div>
<!-- INDEX -->
<p> In Chapter 5, SWIG's treatment of basic datatypes and pointers was
 described. In particular, primitive types such as <tt>int</tt> and <tt>
double</tt> are mapped to corresponding types in the target language.
 For everything else, pointers are used to refer to structures, classes,
 arrays, and other user-defined datatypes. However, in certain
 applications it is desirable to change SWIG's handling of a specific
 datatype. For example, you might want to return multiple values through
 the arguments of a function. This chapter describes some of the
 techniques for doing this.</p>
<h2><a name="Arguments_nn2">12.1 The typemaps.i library</a></h2>
<p> This section describes the <tt>typemaps.i</tt> library
 file--commonly used to change certain properties of argument
 conversion.</p>
<h3><a name="Arguments_nn3">12.1.1 Introduction</a></h3>
<p> Suppose you had a C function like this:</p>
<div class="code">
<pre>
void add(double a, double b, double *result) {
  *result = a + b;
}
</pre>
</div>
<p> From reading the source code, it is clear that the function is
 storing a value in the <tt>double *result</tt> parameter. However,
 since SWIG does not examine function bodies, it has no way to know that
 this is the underlying behavior.</p>
<p> One way to deal with this is to use the <tt>typemaps.i</tt> library
 file and write interface code like this:</p>
<div class="code">
<pre>
// Simple example using typemaps
%module example
%include &quot;typemaps.i&quot;

%apply double *OUTPUT { double *result };
%inline %{
extern void add(double a, double b, double *result);
%}
</pre>
</div>
<p> The <tt>%apply</tt> directive tells SWIG that you are going to apply
 a special type handling rule to a type. The &quot;<tt>double *OUTPUT</tt>&quot;
 specification is the name of a rule that defines how to return an
 output value from an argument of type <tt>double *</tt>. This rule gets
 applied to all of the datatypes listed in curly braces-- in this case &quot;<tt>
double *result</tt>&quot;.</p>
<p> When the resulting module is created, you can now use the function
 like this (shown for Python):</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; a = add(3, 4)
&gt;&gt;&gt; print a
7
&gt;&gt;&gt;
</pre>
</div>
<p> In this case, you can see how the output value normally returned in
 the third argument has magically been transformed into a function
 return value. Clearly this makes the function much easier to use since
 it is no longer necessary to manufacture a special <tt>double *</tt>
 object and pass it to the function somehow.</p>
<p> Once a typemap has been applied to a type, it stays in effect for
 all future occurrences of the type and name. For example, you could
 write the following:</p>
<div class="code">
<pre>
%module example
%include &quot;typemaps.i&quot;

%apply double *OUTPUT { double *result };

%inline %{
extern void add(double a, double b, double *result);
extern void sub(double a, double b, double *result);
extern void mul(double a, double b, double *result);
extern void div(double a, double b, double *result);
%}
...
</pre>
</div>
<p> In this case, the <tt>double *OUTPUT</tt> rule is applied to all of
 the functions that follow.</p>
<p> Typemap transformations can even be extended to multiple return
 values. For example, consider this code:</p>
<div class="code">
<pre>
%include &quot;typemaps.i&quot;
%apply int *OUTPUT { int *width, int *height };

// Returns a pair (width, height)
void getwinsize(int winid, int *width, int *height);
</pre>
</div>
<p> In this case, the function returns multiple values, allowing it to
 be used like this:</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; w, h = genwinsize(wid)
&gt;&gt;&gt; print w
400
&gt;&gt;&gt; print h
300
&gt;&gt;&gt;
</pre>
</div>
<p> It should also be noted that although the <tt>%apply</tt> directive
 is used to associate typemap rules to datatypes, you can also use the
 rule names directly in arguments. For example, you could write this:</p>
<div class="code">
<pre>
// Simple example using typemaps
%module example
%include &quot;typemaps.i&quot;

%{
extern void add(double a, double b, double *OUTPUT);
%}
extern void add(double a, double b, double *OUTPUT);
</pre>
</div>
<p> Typemaps stay in effect until they are explicitly deleted or
 redefined to something else. To clear a typemap, the <tt>%clear</tt>
 directive should be used. For example:</p>
<div class="code">
<pre>
%clear double *result;      // Remove all typemaps for double *result
</pre>
</div>
<h3><a name="Arguments_nn4">12.1.2 Input parameters</a></h3>
<p> The following typemaps instruct SWIG that a pointer really only
 holds a single input value:</p>
<div class="code">
<pre>
int *INPUT
short *INPUT
long *INPUT
unsigned int *INPUT
unsigned short *INPUT
unsigned long *INPUT
double *INPUT
float *INPUT
</pre>
</div>
<p> When used, it allows values to be passed instead of pointers. For
 example, consider this function:</p>
<div class="code">
<pre>
double add(double *a, double *b) {
  return *a+*b;
}
</pre>
</div>
<p> Now, consider this SWIG interface:</p>
<div class="code">
<pre>
%module example
%include &quot;typemaps.i&quot;
...
%{
extern double add(double *, double *);
%}
extern double add(double *INPUT, double *INPUT);

</pre>
</div>
<p> When the function is used in the scripting language interpreter, it
 will work like this:</p>
<div class="targetlang">
<pre>
result = add(3, 4)
</pre>
</div>
<h3><a name="Arguments_nn5">12.1.3 Output parameters</a></h3>
<p> The following typemap rules tell SWIG that pointer is the output
 value of a function. When used, you do not need to supply the argument
 when calling the function. Instead, one or more output values are
 returned.</p>
<div class="code">
<pre>
int *OUTPUT
short *OUTPUT
long *OUTPUT
unsigned int *OUTPUT
unsigned short *OUTPUT
unsigned long *OUTPUT
double *OUTPUT
float *OUTPUT

</pre>
</div>
<p> These methods can be used as shown in an earlier example. For
 example, if you have this C function :</p>
<div class="code">
<pre>
void add(double a, double b, double *c) {
  *c = a+b;
}
</pre>
</div>
<p> A SWIG interface file might look like this :</p>
<div class="code">
<pre>
%module example
%include &quot;typemaps.i&quot;
...
%inline %{
extern void add(double a, double b, double *OUTPUT);
%}

</pre>
</div>
<p> In this case, only a single output value is returned, but this is
 not a restriction. An arbitrary number of output values can be returned
 by applying the output rules to more than one argument (as shown
 previously).</p>
<p> If the function also returns a value, it is returned along with the
 argument. For example, if you had this:</p>
<div class="code">
<pre>
extern int foo(double a, double b, double *OUTPUT);
</pre>
</div>
<p> The function will return two values like this:</p>
<div class="targetlang">
<pre>
iresult, dresult = foo(3.5, 2)
</pre>
</div>
<h3><a name="Arguments_nn6">12.1.4 Input/Output parameters</a></h3>
<p> When a pointer serves as both an input and output value you can use
 the following typemaps :</p>
<div class="code">
<pre>
int *INOUT
short *INOUT
long *INOUT
unsigned int *INOUT
unsigned short *INOUT
unsigned long *INOUT
double *INOUT
float *INOUT

</pre>
</div>
<p> A C function that uses this might be something like this:</p>
<div class="code">
<pre>
void negate(double *x) {
  *x = -(*x);
}

</pre>
</div>
<p> To make x function as both and input and output value, declare the
 function like this in an interface file :</p>
<div class="code">
<pre>
%module example
%include &quot;typemaps.i&quot;
...
%{
extern void negate(double *);
%}
extern void negate(double *INOUT);

</pre>
</div>
<p> Now within a script, you can simply call the function normally :</p>
<div class="targetlang">
<pre>
a = negate(3);         # a = -3 after calling this
</pre>
</div>
<p> One subtle point of the <tt>INOUT</tt> rule is that many scripting
 languages enforce mutability constraints on primitive objects (meaning
 that simple objects like integers and strings aren't supposed to
 change). Because of this, you can't just modify the object's value in
 place as the underlying C function does in this example. Therefore, the
 <tt>INOUT</tt> rule returns the modified value as a new object rather
 than directly overwriting the value of the original input object.</p>
<p><b> Compatibility note :</b> The <tt>INOUT</tt> rule used to be known
 as <tt>BOTH</tt> in earlier versions of SWIG. Backwards compatibility
 is preserved, but deprecated.</p>
<h3><a name="Arguments_nn7">12.1.5 Using different names</a></h3>
<p> As previously shown, the <tt>%apply</tt> directive can be used to
 apply the <tt>INPUT</tt>, <tt>OUTPUT</tt>, and <tt>INOUT</tt> typemaps
 to different argument names. For example:</p>
<div class="code">
<pre>
// Make double *result an output value
%apply double *OUTPUT { double *result };

// Make Int32 *in an input value
%apply int *INPUT { Int32 *in };

// Make long *x inout
%apply long *INOUT {long *x};

</pre>
</div>
<p> To clear a rule, the <tt>%clear</tt> directive is used:</p>
<div class="code">
<pre>
%clear double *result;
%clear Int32 *in, long *x;
</pre>
</div>
<p> Typemap declarations are lexically scoped so a typemap takes effect
 from the point of definition to the end of the file or a matching <tt>
%clear</tt> declaration.</p>
<h2><a name="Arguments_nn8">12.2 Applying constraints to input values</a>
</h2>
<p> In addition to changing the handling of various input values, it is
 also possible to use typemaps to apply constraints. For example, maybe
 you want to insure that a value is positive, or that a pointer is
 non-NULL. This can be accomplished including the <tt>constraints.i</tt>
 library file.</p>
<h3><a name="Arguments_nn9">12.2.1 Simple constraint example</a></h3>
<p> The constraints library is best illustrated by the following
 interface file :</p>
<div class="code">
<pre>
// Interface file with constraints
%module example
%include &quot;constraints.i&quot;

double exp(double x);
double log(double POSITIVE);         // Allow only positive values
double sqrt(double NONNEGATIVE);     // Non-negative values only
double inv(double NONZERO);          // Non-zero values
void   free(void *NONNULL);          // Non-NULL pointers only

</pre>
</div>
<p> The behavior of this file is exactly as you would expect. If any of
 the arguments violate the constraint condition, a scripting language
 exception will be raised. As a result, it is possible to catch bad
 values, prevent mysterious program crashes and so on.</p>
<h3><a name="Arguments_nn10">12.2.2 Constraint methods</a></h3>
<p> The following constraints are currently available</p>
<div class="code">
<pre>
POSITIVE                     Any number &gt; 0 (not zero)
NEGATIVE                     Any number &lt; 0 (not zero)
NONNEGATIVE                  Any number &gt;= 0
NONPOSITIVE                  Any number &lt;= 0
NONZERO                      Nonzero number
NONNULL                      Non-NULL pointer (pointers only).

</pre>
</div>
<h3><a name="Arguments_nn11">12.2.3 Applying constraints to new
 datatypes</a></h3>
<p> The constraints library only supports the primitive C datatypes, but
 it is easy to apply it to new datatypes using <tt>%apply</tt>. For
 example :</p>
<div class="code">
<pre>
// Apply a constraint to a Real variable
%apply Number POSITIVE { Real in };

// Apply a constraint to a pointer type
%apply Pointer NONNULL { Vector * };

</pre>
</div>
<p> The special types of &quot;Number&quot; and &quot;Pointer&quot; can be applied to any
 numeric and pointer variable type respectively. To later remove a
 constraint, the <tt>%clear</tt> directive can be used :</p>
<div class="code">
<pre>
%clear Real in;
%clear Vector *;
</pre>
</div><HR NOSHADE>
<h1><a name="Typemaps">13 Typemaps</a></h1>

<!-- INDEX -->
<div class="sectiontoc">
<ul>
<li><a href="#Typemaps_nn2">Introduction</a>
<ul>
<li><a href="#Typemaps_nn3">Type conversion</a></li>
<li><a href="#Typemaps_nn4">Typemaps</a></li>
<li><a href="#Typemaps_nn5">Pattern matching</a></li>
<li><a href="#Typemaps_nn6">Reusing typemaps</a></li>
<li><a href="#Typemaps_nn7">What can be done with typemaps?</a></li>
<li><a href="#Typemaps_nn8">What can't be done with typemaps?</a></li>
<li><a href="#Typemaps_aspects">Similarities to Aspect Oriented
 Programming</a></li>
<li><a href="#Typemaps_nn9">The rest of this chapter</a></li>
</ul>
</li>
<li><a href="#Typemaps_nn10">Typemap specifications</a>
<ul>
<li><a href="#Typemaps_defining">Defining a typemap</a></li>
<li><a href="#Typemaps_nn12">Typemap scope</a></li>
<li><a href="#Typemaps_nn13">Copying a typemap</a></li>
<li><a href="#Typemaps_nn14">Deleting a typemap</a></li>
<li><a href="#Typemaps_nn15">Placement of typemaps</a></li>
</ul>
</li>
<li><a href="#Typemaps_pattern_matching">Pattern matching rules</a>
<ul>
<li><a href="#Typemaps_nn17">Basic matching rules</a></li>
<li><a href="#Typemaps_typedef_reductions">Typedef reductions matching</a>
</li>
<li><a href="#Typemaps_nn19">Default typemap matching rules</a></li>
<li><a href="#Typemaps_multi_argument_typemaps_patterns">Multi-arguments
 typemaps</a></li>
<li><a href="#Typemaps_matching_template_comparison">Matching rules
 compared to C++ templates</a></li>
<li><a href="#Typemaps_debugging_search">Debugging typemap pattern
 matching</a></li>
</ul>
</li>
<li><a href="#Typemaps_nn21">Code generation rules</a>
<ul>
<li><a href="#Typemaps_nn22">Scope</a></li>
<li><a href="#Typemaps_nn23">Declaring new local variables</a></li>
<li><a href="#Typemaps_special_variables">Special variables</a></li>
<li><a href="#Typemaps_special_variable_macros">Special variable macros</a>
<ul>
<li><a href="#Typemaps_special_macro_descriptor">$descriptor(type)</a></li>
<li><a href="#Typemaps_special_macro_typemap">$typemap(method,
 typepattern)</a></li>
</ul>
</li>
<li><a href="#Typemaps_special_variable_attributes">Special variables
 and typemap attributes</a></li>
<li><a href="#Typemaps_special_variables_and_macros">Special variables
 combined with special variable macros</a></li>
</ul>
</li>
<li><a href="#Typemaps_nn25">Common typemap methods</a>
<ul>
<li><a href="#Typemaps_nn26">&quot;in&quot; typemap</a></li>
<li><a href="#Typemaps_nn27">&quot;typecheck&quot; typemap</a></li>
<li><a href="#Typemaps_nn28">&quot;out&quot; typemap</a></li>
<li><a href="#Typemaps_nn29">&quot;arginit&quot; typemap</a></li>
<li><a href="#Typemaps_nn30">&quot;default&quot; typemap</a></li>
<li><a href="#Typemaps_nn31">&quot;check&quot; typemap</a></li>
<li><a href="#Typemaps_nn32">&quot;argout&quot; typemap</a></li>
<li><a href="#Typemaps_nn33">&quot;freearg&quot; typemap</a></li>
<li><a href="#Typemaps_nn34">&quot;newfree&quot; typemap</a></li>
<li><a href="#Typemaps_ret">&quot;ret&quot; typemap</a></li>
<li><a href="#Typemaps_nn35">&quot;memberin&quot; typemap</a></li>
<li><a href="#Typemaps_nn36">&quot;varin&quot; typemap</a></li>
<li><a href="#Typemaps_nn37">&quot;varout&quot; typemap</a></li>
<li><a href="#Typemaps_throws_typemap">&quot;throws&quot; typemap</a></li>
</ul>
</li>
<li><a href="#Typemaps_nn39">Some typemap examples</a>
<ul>
<li><a href="#Typemaps_nn40">Typemaps for arrays</a></li>
<li><a href="#Typemaps_nn41">Implementing constraints with typemaps</a></li>
</ul>
</li>
<li><a href="#Typemaps_nn43">Typemaps for multiple target languages</a></li>
<li><a href="#Typemaps_optimal">Optimal code generation when returning
 by value</a></li>
<li><a href="#Typemaps_multi_argument_typemaps">Multi-argument typemaps</a>
</li>
<li><a href="#Typemaps_warnings">Typemap warnings</a></li>
<li><a href="#Typemaps_fragments">Typemap fragments</a>
<ul>
<li><a href="#Typemaps_fragment_type_specialization">Fragment type
 specialization</a></li>
<li><a href="#Typemaps_automatic_specialization">Fragments and automatic
 typemap specialization</a></li>
</ul>
</li>
<li><a href="#Typemaps_runtime_type_checker">The run-time type checker</a>
<ul>
<li><a href="#Typemaps_nn45">Implementation</a></li>
<li><a href="#Typemaps_runtime_type_checker_usage">Usage</a></li>
</ul>
</li>
<li><a href="#Typemaps_overloading">Typemaps and overloading</a>
<ul>
<li><a href="#Typemaps_typecheck_pointer">SWIG_TYPECHECK_POINTER
 precedence level and the typecheck typemap</a></li>
</ul>
</li>
<li><a href="#Typemaps_nn48">More about %apply and %clear</a></li>
<li><a href="#Typemaps_nn47">Passing data between typemaps</a></li>
<li><a href="#Typemaps_nn52">C++ &quot;this&quot; pointer</a></li>
<li><a href="#Typemaps_nn51">Where to go for more information?</a></li>
</ul>
</div>
<!-- INDEX -->
<h2><a name="Typemaps_nn2">13.1 Introduction</a></h2>
<p> Chances are, you are reading this chapter for one of two reasons;
 you either want to customize SWIG's behavior or you overheard someone
 mumbling some incomprehensible drivel about &quot;typemaps&quot; and you asked
 yourself &quot;typemaps, what are those?&quot; That said, let's start with a
 short disclaimer that &quot;typemaps&quot; are an advanced customization feature
 that provide direct access to SWIG's low-level code generator. Not only
 that, they are an integral part of the SWIG C++ type system (a
 non-trivial topic of its own). Typemaps are generally<em> not</em> a
 required part of using SWIG. Therefore, you might want to re-read the
 earlier chapters if you have found your way to this chapter with only a
 vague idea of what SWIG already does by default.</p>
<h3><a name="Typemaps_nn3">13.1.1 Type conversion</a></h3>
<p> One of the most important problems in wrapper code generation is the
 conversion or marshalling of datatypes between programming languages.
 Specifically, for every C/C++ declaration, SWIG must somehow generate
 wrapper code that allows values to be passed back and forth between
 languages. Since every programming language represents data
 differently, this is not a simple of matter of simply linking code
 together with the C linker. Instead, SWIG has to know something about
 how data is represented in each language and how it can be manipulated.</p>
<p> To illustrate, suppose you had a simple C function like this:</p>
<div class="code">
<pre>
int factorial(int n);
</pre>
</div>
<p> To access this function from Python, a pair of Python API functions
 are used to convert integer values. For example:</p>
<div class="code">
<pre>
long PyInt_AsLong(PyObject *obj);      /* Python --&gt; C */
PyObject *PyInt_FromLong(long x);      /* C --&gt; Python */
</pre>
</div>
<p> The first function is used to convert the input argument from a
 Python integer object to C <tt>long</tt>. The second function is used
 to convert a value from C back into a Python integer object.</p>
<p> Inside the wrapper function, you might see these functions used like
 this:</p>
<div class="code">
<pre>
PyObject *wrap_factorial(PyObject *self, PyObject *args) {
  int       arg1;
  int       result;
  PyObject *obj1;
  PyObject *resultobj;

  if (!PyArg_ParseTuple(&quot;O:factorial&quot;, &amp;obj1)) return NULL;
  <b>arg1 = PyInt_AsLong(obj1);</b>
  result = factorial(arg1);
  <b>resultobj = PyInt_FromLong(result);</b>
  return resultobj;
}
</pre>
</div>
<p> Every target language supported by SWIG has functions that work in a
 similar manner. For example, in Perl, the following functions are used:</p>
<div class="code">
<pre>
IV SvIV(SV *sv);                     /* Perl --&gt; C */
void sv_setiv(SV *sv, IV val);       /* C --&gt; Perl */
</pre>
</div>
<p> In Tcl:</p>
<div class="code">
<pre>
int Tcl_GetLongFromObj(Tcl_Interp *interp, Tcl_Obj *obj, long *value);
Tcl_Obj *Tcl_NewIntObj(long value);
</pre>
</div>
<p> The precise details are not so important. What is important is that
 all of the underlying type conversion is handled by collections of
 utility functions and short bits of C code like this---you simply have
 to read the extension documentation for your favorite language to know
 how it works (an exercise left to the reader).</p>
<h3><a name="Typemaps_nn4">13.1.2 Typemaps</a></h3>
<p> Since type handling is so central to wrapper code generation, SWIG
 allows it to be completely defined (or redefined) by the user. To do
 this, a special <tt>%typemap</tt> directive is used. For example:</p>
<div class="code">
<pre>
/* Convert from Python --&gt; C */
%typemap(in) int {
  $1 = PyInt_AsLong($input);
}

/* Convert from C --&gt; Python */
%typemap(out) int {
  $result = PyInt_FromLong($1);
}
</pre>
</div>
<p> At first glance, this code will look a little confusing. However,
 there is really not much to it. The first typemap (the &quot;in&quot; typemap) is
 used to convert a value from the target language to C. The second
 typemap (the &quot;out&quot; typemap) is used to convert in the other direction.
 The content of each typemap is a small fragment of code that is
 inserted directly into the SWIG generated wrapper functions. The code
 is usually C or C++ code which will be generated into the C/C++ wrapper
 functions. Note that this isn't always the case as some target language
 modules allow target language code within the typemaps which gets
 generated into target language specific files. Within this code, a
 number of special variables prefixed with a $ are expanded. These are
 really just placeholders for C/C++ variables that are generated in the
 course of creating the wrapper function. In this case, <tt>$input</tt>
 refers to an input object that needs to be converted to C/C++ and <tt>
$result</tt> refers to an object that is going to be returned by a
 wrapper function. <tt>$1</tt> refers to a C/C++ variable that has the
 same type as specified in the typemap declaration (an <tt>int</tt> in
 this example).</p>
<p> A short example might make this a little more clear. If you were
 wrapping a function like this:</p>
<div class="code">
<pre>
int gcd(int x, int y);
</pre>
</div>
<p> A wrapper function would look approximately like this:</p>
<div class="code">
<pre>
PyObject *wrap_gcd(PyObject *self, PyObject *args) {
  int arg1;
  int arg2;
  int result;
  PyObject *obj1;
  PyObject *obj2;
  PyObject *resultobj;

  if (!PyArg_ParseTuple(&quot;OO:gcd&quot;, &amp;obj1, &amp;obj2)) return NULL;

  /* &quot;in&quot; typemap, argument 1 */<b>
  {
    arg1 = PyInt_AsLong(obj1);
  }
</b>
  /* &quot;in&quot; typemap, argument 2 */<b>
  {
    arg2 = PyInt_AsLong(obj2);
  }
</b>
  result = gcd(arg1, arg2);

  /* &quot;out&quot; typemap, return value */<b>
  {
    resultobj = PyInt_FromLong(result);
  }
</b>
  return resultobj;
}
</pre>
</div>
<p> In this code, you can see how the typemap code has been inserted
 into the function. You can also see how the special $ variables have
 been expanded to match certain variable names inside the wrapper
 function. This is really the whole idea behind typemaps--they simply
 let you insert arbitrary code into different parts of the generated
 wrapper functions. Because arbitrary code can be inserted, it possible
 to completely change the way in which values are converted.</p>
<h3><a name="Typemaps_nn5">13.1.3 Pattern matching</a></h3>
<p> As the name implies, the purpose of a typemap is to &quot;map&quot; C
 datatypes to types in the target language. Once a typemap is defined
 for a C datatype, it is applied to all future occurrences of that type
 in the input file. For example:</p>
<div class="code">
<pre>
/* Convert from Perl --&gt; C */
%typemap(in) <b>int</b> {
  $1 = SvIV($input);
}

...
int factorial(<b>int</b> n);
int gcd(<b>int</b> x, <b>int</b> y);
int count(char *s, char *t, <b>int</b> max);
</pre>
</div>
<p> The matching of typemaps to C datatypes is more than a simple
 textual match. In fact, typemaps are fully built into the underlying
 type system. Therefore, typemaps are unaffected by <tt>typedef</tt>,
 namespaces, and other declarations that might hide the underlying type.
 For example, you could have code like this:</p>
<div class="code">
<pre>
/* Convert from Ruby--&gt; C */
%typemap(in) <b>int</b> {
  $1 = NUM2INT($input);
}
...
typedef int Integer;
namespace foo {
  typedef Integer Number;
};

int foo(<b>int</b> x);
int bar(<b>Integer</b> y);
int spam(<b>foo::Number</b> a, <b>foo::Number</b> b);
</pre>
</div>
<p> In this case, the typemap is still applied to the proper arguments
 even though typenames don't always match the text &quot;int&quot;. This ability
 to track types is a critical part of SWIG--in fact, all of the target
 language modules work merely define a family of typemaps for the basic
 types. Yet, it is never necessary to write new typemaps for typenames
 introduced by <tt>typedef</tt>.</p>
<p> In addition to tracking typenames, typemaps may also be specialized
 to match against a specific argument name. For example, you could write
 a typemap like this:</p>
<div class="code">
<pre>
%typemap(in) <b>double nonnegative</b> {
  $1 = PyFloat_AsDouble($input);
  if ($1 &lt; 0) {
    PyErr_SetString(PyExc_ValueError, &quot;argument must be nonnegative.&quot;);
    SWIG_fail;
  }
}

...
double sin(double x);
double cos(double x);
double sqrt(<b>double nonnegative</b>);

typedef double Real;
double log(<b>Real nonnegative</b>);
...
</pre>
</div>
<p> For certain tasks such as input argument conversion, typemaps can be
 defined for sequences of consecutive arguments. For example:</p>
<div class="code">
<pre>
%typemap(in) (<b>char *str, int len</b>) {
  $1 = PyString_AsString($input);   /* char *str */
  $2 = PyString_Size($input);       /* int len   */
}
...
int count(<b>char *str, int len</b>, char c);
</pre>
</div>
<p> In this case, a single input object is expanded into a pair of C
 arguments. This example also provides a hint to the unusual variable
 naming scheme involving <tt>$1</tt>, <tt>$2</tt>, and so forth.</p>
<h3><a name="Typemaps_nn6">13.1.4 Reusing typemaps</a></h3>
<p> Typemaps are normally defined for specific type and argument name
 patterns. However, typemaps can also be copied and reused. One way to
 do this is to use assignment like this:</p>
<div class="code">
<pre>
%typemap(in) Integer = int;   
%typemap(in) (char *buffer, int size) = (char *str, int len);
</pre>
</div>
<p> There is a more powerful way to copy a family of typemaps though.
 Consider the following family of two typemap methods, &quot;in&quot; and &quot;out&quot;
 for type <tt>int</tt>:</p>
<div class="code">
<pre>
%typemap(in) int {
  /* Convert an integer argument */
  ...
}
%typemap(out) int {
  /* Return an integer value */
  ...
}
</pre>
</div>
<p> Each of the two typemap methods could be copied individually for
 type <tt>size_t</tt> as follows:</p>
<div class="code">
<pre>
/* Apply all of the int typemaps to size_t */
%typemap(in) size_t = int;   
%typemap(out) size_t = int;   
</pre>
</div>
<p> A more powerful form of copying is available from the <tt>%apply</tt>
 directive. The code below is identical to the above:</p>
<div class="code">
<pre>
/* Apply all of the int typemaps to size_t */
%apply int { size_t };    
</pre>
</div>
<p> <tt>%apply</tt> merely takes<em> all</em> of the typemaps that are
 defined for one type and applies them to other types. Note: you can
 include a comma separated set of types in the <tt>{ ... }</tt> part of <tt>
%apply</tt>.</p>
<p> It should be noted that it is not necessary to copy typemaps for
 types that are related by <tt>typedef</tt>. For example, if you have
 this,</p>
<div class="code">
<pre>
typedef int size_t;
</pre>
</div>
<p> then SWIG already knows that the <tt>int</tt> typemaps apply. You
 don't have to do anything.</p>
<h3><a name="Typemaps_nn7">13.1.5 What can be done with typemaps?</a></h3>
<p> The primary use of typemaps is for defining wrapper generation
 behavior at the level of individual C/C++ datatypes. There are
 currently six general categories of problems that typemaps address:</p>
<p><b> Argument handling</b></p>
<div class="code">
<pre>
int foo(<b>int x, double y, char *s</b>);
</pre>
</div>
<ul>
<li>Input argument conversion (&quot;in&quot; typemap).</li>
<li>Input argument type checking for types used in overloaded methods
 (&quot;typecheck&quot; typemap).</li>
<li>Output argument handling (&quot;argout&quot; typemap).</li>
<li>Input argument value checking (&quot;check&quot; typemap).</li>
<li>Input argument initialization (&quot;arginit&quot; typemap).</li>
<li>Default arguments (&quot;default&quot; typemap).</li>
<li>Input argument resource management (&quot;freearg&quot; typemap).</li>
</ul>
<p><b> Return value handling</b></p>
<div class="code">
<pre>
<b>int</b> foo(int x, double y, char *s);
</pre>
</div>
<ul>
<li>Function return value conversion (&quot;out&quot; typemap).</li>
<li>Return value resource management (&quot;ret&quot; typemap).</li>
<li>Resource management for newly allocated objects (&quot;newfree&quot; typemap).</li>
</ul>
<p><b> Exception handling</b></p>
<div class="code">
<pre>
<b>int</b> foo(int x, double y, char *s) throw(<b>MemoryError, IndexError</b>);
</pre>
</div>
<ul>
<li>Handling of C++ exception specifications. (&quot;throw&quot; typemap).</li>
</ul>
<p><b> Global variables</b></p>
<div class="code">
<pre>
<b>int foo;</b>
</pre>
</div>
<ul>
<li>Assignment of a global variable. (&quot;varin&quot; typemap).</li>
<li>Reading a global variable. (&quot;varout&quot; typemap).</li>
</ul>
<p><b> Member variables</b></p>
<div class="code">
<pre>
struct Foo {
  <b>int x[20]</b>;
};
</pre>
</div>
<ul>
<li>Assignment of data to a class/structure member. (&quot;memberin&quot;
 typemap).</li>
</ul>
<p><b> Constant creation</b></p>
<div class="code">
<pre>
#define FOO 3
%constant int BAR = 42;
enum { ALE, LAGER, STOUT };
</pre>
</div>
<ul>
<li>Creation of constant values. (&quot;consttab&quot; or &quot;constcode&quot; typemap).</li>
</ul>
<p> Details of each of these typemaps will be covered shortly. Also,
 certain language modules may define additional typemaps that expand
 upon this list. For example, the Java module defines a variety of
 typemaps for controlling additional aspects of the Java bindings.
 Consult language specific documentation for further details.</p>
<h3><a name="Typemaps_nn8">13.1.6 What can't be done with typemaps?</a></h3>
<p> Typemaps can't be used to define properties that apply to C/C++
 declarations as a whole. For example, suppose you had a declaration
 like this,</p>
<div class="code">
<pre>
Foo *make_Foo(int n);
</pre>
</div>
<p> and you wanted to tell SWIG that <tt>make_Foo(int n)</tt> returned a
 newly allocated object (for the purposes of providing better memory
 management). Clearly, this property of <tt>make_Foo(int n)</tt> is<em>
 not</em> a property that would be associated with the datatype <tt>Foo
 *</tt> by itself. Therefore, a completely different SWIG customization
 mechanism (<tt>%feature</tt>) is used for this purpose. Consult the <a href="#Customization">
Customization Features</a> chapter for more information about that.</p>
<p> Typemaps also can't be used to rearrange or transform the order of
 arguments. For example, if you had a function like this:</p>
<div class="code">
<pre>
void foo(int, char *);
</pre>
</div>
<p> you can't use typemaps to interchange the arguments, allowing you to
 call the function like this:</p>
<div class="targetlang">
<pre>
foo(&quot;hello&quot;, 3)          # Reversed arguments
</pre>
</div>
<p> If you want to change the calling conventions of a function, write a
 helper function instead. For example:</p>
<div class="code">
<pre>
%rename(foo) wrap_foo;
%inline %{
void wrap_foo(char *s, int x) {
  foo(x, s);
}
%}
</pre>
</div>
<h3><a name="Typemaps_aspects">13.1.7 Similarities to Aspect Oriented
 Programming</a></h3>
<p> SWIG has parallels to <a href="https://en.wikipedia.org/wiki/Aspect-oriented_programming">
Aspect Oriented Software Development (AOP)</a>. The <a href="https://en.wikipedia.org/wiki/Aspect-oriented_programming#Terminology">
AOP terminology</a> with respect to SWIG typemaps can be viewed as
 follows:</p>
<ul>
<li><b> Cross-cutting concerns</b>: The cross-cutting concerns are the
 modularization of the functionality that the typemaps implement, which
 is primarily marshalling of types from/to the target language and
 C/C++.</li>
<li><b> Advice</b>: The typemap body contains code which is executed
 whenever the marshalling is required.</li>
<li><b> Pointcut</b>: The pointcuts are the positions in the wrapper
 code that the typemap code is generated into.</li>
<li><b> Aspect</b>: Aspects are the combination of the pointcut and the
 advice, hence each typemap is an aspect.</li>
</ul>
<p> SWIG can also be viewed as has having a second set of aspects based
 around <a href="#Customization">%feature</a>. Features such as <tt>
%exception</tt> are also cross-cutting concerns as they encapsulate code
 that can be used to add logging or exception handling to any function.</p>
<h3><a name="Typemaps_nn9">13.1.8 The rest of this chapter</a></h3>
<p> The rest of this chapter provides detailed information for people
 who want to write new typemaps. This information is of particular
 importance to anyone who intends to write a new SWIG target language
 module. Power users can also use this information to write application
 specific type conversion rules.</p>
<p> Since typemaps are strongly tied to the underlying C++ type system,
 subsequent sections assume that you are reasonably familiar with the
 basic details of values, pointers, references, arrays, type qualifiers
 (e.g., <tt>const</tt>), structures, namespaces, templates, and memory
 management in C/C++. If not, you would be well-advised to consult a
 copy of &quot;The C Programming Language&quot; by Kernighan and Ritchie or &quot;The
 C++ Programming Language&quot; by Stroustrup before going any further.</p>
<h2><a name="Typemaps_nn10">13.2 Typemap specifications</a></h2>
<p> This section describes the behavior of the <tt>%typemap</tt>
 directive itself.</p>
<h3><a name="Typemaps_defining">13.2.1 Defining a typemap</a></h3>
<p> New typemaps are defined using the <tt>%typemap</tt> declaration.
 The general form of this declaration is as follows (parts enclosed in [
 ... ] are optional):</p>
<div class="code">
<pre>
%typemap(<em>method</em> [, <em>modifiers</em>]) <em>typelist</em> <em>code</em> ;
</pre>
</div>
<p><em> method</em> is a simply a name that specifies what kind of
 typemap is being defined. It is usually a name like <tt>&quot;in&quot;</tt>, <tt>
&quot;out&quot;</tt>, or <tt>&quot;argout&quot;</tt>. The purpose of these methods is
 described later.</p>
<p><em> modifiers</em> is an optional comma separated list of <tt>
name=&quot;value&quot;</tt> values. These are sometimes to attach extra
 information to a typemap and is often target-language dependent. They
 are also known as typemap attributes.</p>
<p><em> typelist</em> is a list of the C++ type patterns that the
 typemap will match. The general form of this list is as follows:</p>
<div class="diagram">
<pre>
typelist    :  typepattern [, typepattern, typepattern, ... ] ;

typepattern :  type [ (parms) ]
            |  type name [ (parms) ]
            |  ( typelist ) [ (parms) ]

</pre>
</div>
<p> Each type pattern is either a simple type, a simple type and
 argument name, or a list of types in the case of multi-argument
 typemaps. In addition, each type pattern can be parameterized with a
 list of temporary variables (parms). The purpose of these variables
 will be explained shortly.</p>
<p><em>code</em> specifies the code used in the typemap. Usually this is
 C/C++ code, but in the statically typed target languages, such as Java
 and C#, this can contain target language code for certain typemaps. It
 can take any one of the following forms:</p>
<div class="diagram">
<pre>
code       : { ... }
           | &quot; ... &quot;
           | %{ ... %}
</pre>
</div>
<p> Note that the preprocessor will expand code within the {}
 delimiters, but not in the last two styles of delimiters, see <a href="#Preprocessor_delimiters">
Preprocessor and Typemaps</a>. Here are some examples of valid typemap
 specifications:</p>
<div class="code">
<pre>
/* Simple typemap declarations */
%typemap(in) int {
  $1 = PyInt_AsLong($input);
}
%typemap(in) int &quot;$1 = PyInt_AsLong($input);&quot;;
%typemap(in) int %{ 
  $1 = PyInt_AsLong($input);
%}

/* Typemap with extra argument name */
%typemap(in) int nonnegative {
  ...
}

/* Multiple types in one typemap */
%typemap(in) int, short, long { 
  $1 = SvIV($input);
}

/* Typemap with modifiers */
%typemap(in, doc=&quot;integer&quot;) int &quot;$1 = scm_to_int($input);&quot;;

/* Typemap applied to patterns of multiple arguments */
%typemap(in) (char *str, int len),
             (char *buffer, int size)
{
  $1 = PyString_AsString($input);
  $2 = PyString_Size($input);
}

/* Typemap with extra pattern parameters */
%typemap(in, numinputs=0) int *output (int temp),
                          long *output (long temp)
{
  $1 = &amp;temp;
}
</pre>
</div>
<p> Admittedly, it's not the most readable syntax at first glance.
 However, the purpose of the individual pieces will become clear.</p>
<h3><a name="Typemaps_nn12">13.2.2 Typemap scope</a></h3>
<p> Once defined, a typemap remains in effect for all of the
 declarations that follow. A typemap may be redefined for different
 sections of an input file. For example:</p>
<div class="code">
<pre>
// typemap1
%typemap(in) int {
...
}

int fact(int);                    // typemap1
int gcd(int x, int y);            // typemap1

// typemap2
%typemap(in) int {
...
}

int isprime(int);                 // typemap2
</pre>
</div>
<p> One exception to the typemap scoping rules pertains to the <tt>
%extend</tt> declaration. <tt>%extend</tt> is used to attach new
 declarations to a class or structure definition. Because of this, all
 of the declarations in an <tt>%extend</tt> block are subject to the
 typemap rules that are in effect at the point where the class itself is
 defined. For example:</p>
<div class="code">
<pre>
class Foo {
  ...
};

%typemap(in) int {
 ...
}

%extend Foo {
  int blah(int x);    // typemap has no effect.  Declaration is attached to Foo which
                      // appears before the %typemap declaration.
};
</pre>
</div>
<h3><a name="Typemaps_nn13">13.2.3 Copying a typemap</a></h3>
<p> A typemap is copied by using assignment. For example:</p>
<div class="code">
<pre>
%typemap(in) Integer = int;
</pre>
</div>
<p> or this:</p>
<div class="code">
<pre>
%typemap(in) Integer, Number, int32_t = int;
</pre>
</div>
<p> Types are often managed by a collection of different typemaps. For
 example:</p>
<div class="code">
<pre>
%typemap(in)     int { ... }
%typemap(out)    int { ... }
%typemap(varin)  int { ... }
%typemap(varout) int { ... }
</pre>
</div>
<p> To copy all of these typemaps to a new type, use <tt>%apply</tt>.
 For example:</p>
<div class="code">
<pre>
%apply int { Integer };            // Copy all int typemaps to Integer
%apply int { Integer, Number };    // Copy all int typemaps to both Integer and Number
</pre>
</div>
<p> The patterns for <tt>%apply</tt> follow the same rules as for <tt>
%typemap</tt>. For example:</p>
<div class="code">
<pre>
%apply int *output { Integer *output };                    // Typemap with name
%apply (char *buf, int len) { (char *buffer, int size) };  // Multiple arguments
</pre>
</div>
<h3><a name="Typemaps_nn14">13.2.4 Deleting a typemap</a></h3>
<p> A particular typemap can be deleted / cleared by simply defining no
 code. For example:</p>
<div class="code">
<pre>
%typemap(in) int;                 // Clears the &quot;in&quot; typemap for int
%typemap(in) int, long, short;    // Clears the &quot;in&quot; typemap for int, long, short
%typemap(in) int *output;       
</pre>
</div>
<p> The above syntax deletes a typemap for just one typemap method - the
 &quot;in&quot; method in each of the examples above. The <tt>%clear</tt>
 directive is more powerful and will delete / clear a family of
 typemaps, that is, all the typemap methods for a given type. For
 example:</p>
<div class="code">
<pre>
%clear int;                       // Delete all typemaps (&quot;in&quot;, &quot;out&quot;, &quot;varin&quot;, ...) for int
%clear int *output, long *output;
</pre>
</div>
<p><b> Note:</b> Since SWIG's default behavior is defined by typemaps,
 clearing a fundamental type like <tt>int</tt> will make that type
 unusable unless you also define a new family of typemaps immediately
 after the clear operation.</p>
<h3><a name="Typemaps_nn15">13.2.5 Placement of typemaps</a></h3>
<p> Typemap declarations can be declared in the global scope, within a
 C++ namespace, and within a C++ class. For example:</p>
<div class="code">
<pre>
%typemap(in) int {
  ...
}

namespace std {
  class string;
  %typemap(in) string {
    ...
  }
}

class Bar {
public:
  typedef const int &amp; const_reference;
  %typemap(out) const_reference {
    ...
  }
};
</pre>
</div>
<p> When a typemap appears inside a namespace or class, it stays in
 effect until the end of the SWIG input (just like before). However, the
 typemap takes the local scope into account. Therefore, this code</p>
<div class="code">
<pre>
namespace std {
  class string;
  %typemap(in) string {
    ...
  }
}
</pre>
</div>
<p> is really defining a typemap for the type <tt>std::string</tt>. You
 could have code like this:</p>
<div class="code">
<pre>
namespace std {
  class string;
  %typemap(in) string {          /* std::string */
    ...
  }
}

namespace Foo {
  class string;
  %typemap(in) string {          /* Foo::string */
    ...
  }
}
</pre>
</div>
<p> In this case, there are two completely distinct typemaps that apply
 to two completely different types (<tt>std::string</tt> and <tt>
Foo::string</tt>).</p>
<p> It should be noted that for scoping to work, SWIG has to know that <tt>
string</tt> is a typename defined within a particular namespace. In this
 example, this is done using the forward class declaration <tt>class
 string</tt>.</p>
<h2><a name="Typemaps_pattern_matching">13.3 Pattern matching rules</a></h2>
<p> The section describes the pattern matching rules by which C/C++
 datatypes are associated with typemaps. The matching rules can be
 observed in practice by using the debugging options also described.</p>
<h3><a name="Typemaps_nn17">13.3.1 Basic matching rules</a></h3>
<p> Typemaps are matched using both a type and a name (typically the
 name of a argument). For a given <tt>TYPE NAME</tt> pair, the following
 rules are applied, in order, to find a match. The first typemap found
 is used.</p>
<ul>
<li>Typemaps that exactly match <tt>TYPE</tt> and <tt>NAME</tt>.</li>
<li>Typemaps that exactly match <tt>TYPE</tt> only.</li>
<li>If <tt>TYPE</tt> is a C++ template of type <tt>T&lt; TPARMS &gt;</tt>,
 where <tt>TPARMS</tt> are the template parameters, the type is stripped
 of the template parameters and the following checks are then made:
<ul>
<li>Typemaps that exactly match <tt>T</tt> and <tt>NAME</tt>.</li>
<li>Typemaps that exactly match <tt>T</tt> only.</li>
</ul>
</li>
</ul>
<p> If <tt>TYPE</tt> includes qualifiers (const, volatile, etc.), each
 qualifier is stripped one at a time to form a new stripped type and the
 matching rules above are repeated on the stripped type. The left-most
 qualifier is stripped first, resulting in the right-most (or top-level)
 qualifier being stripped last. For example <tt>int const*const</tt> is
 first stripped to <tt>int *const</tt> then <tt>int *</tt>.</p>
<p> If <tt>TYPE</tt> is an array. The following transformation is made:</p>
<ul>
<li>Replace all dimensions to <tt>[ANY]</tt> and look for a generic
 array typemap.</li>
</ul>
<p> To illustrate, suppose that you had a function like this:</p>
<div class="code">
<pre>
int foo(const char *s);
</pre>
</div>
<p> To find a typemap for the argument <tt>const char *s</tt>, SWIG will
 search for the following typemaps:</p>
<div class="diagram">
<pre>
const char *s           Exact type and name match
const char *            Exact type match
char *s                 Type and name match (qualifier stripped)
char *                  Type match (qualifier stripped)
</pre>
</div>
<p> When more than one typemap rule might be defined, only the first
 match found is actually used. Here is an example that shows how some of
 the basic rules are applied:</p>
<div class="code">
<pre>
%typemap(in) int *x {
  ... typemap 1
}

%typemap(in) int * {
  ... typemap 2
}

%typemap(in) const int *z {
  ... typemap 3
}

%typemap(in) int [4] {
  ... typemap 4
}

%typemap(in) int [ANY] {
  ... typemap 5
}

void A(int *x);        // int *x rule       (typemap 1)
void B(int *y);        // int * rule        (typemap 2)
void C(const int *x);  // int *x rule       (typemap 1)
void D(const int *z);  // const int *z rule (typemap 3)
void E(int x[4]);      // int [4] rule      (typemap 4)
void F(int x[1000]);   // int [ANY] rule    (typemap 5)
</pre>
</div>
<p><b> Compatibility note:</b> SWIG-2.0.0 introduced stripping the
 qualifiers one step at a time. Prior versions stripped all qualifiers
 in one step.</p>
<h3><a name="Typemaps_typedef_reductions">13.3.2 Typedef reductions
 matching</a></h3>
<p> If no match is found using the rules in the previous section, SWIG
 applies a typedef reduction to the type and repeats the typemap search
 for the reduced type. To illustrate, suppose you had code like this:</p>
<div class="code">
<pre>
%typemap(in) int {
  ... typemap 1
}

typedef int Integer;
void blah(Integer x);
</pre>
</div>
<p> To find the typemap for <tt>Integer x</tt>, SWIG will first search
 for the following typemaps:</p>
<div class="diagram">
<pre>
Integer x
Integer
</pre>
</div>
<p> Finding no match, it then applies a reduction <tt>Integer -&gt; int</tt>
 to the type and repeats the search.</p>
<div class="diagram">
<pre>
int x
int      --&gt; match: typemap 1
</pre>
</div>
<p> Even though two types might be the same via typedef, SWIG allows
 typemaps to be defined for each typename independently. This allows for
 interesting customization possibilities based solely on the typename
 itself. For example, you could write code like this:</p>
<div class="code">
<pre>
typedef double  pdouble;     // Positive double

// typemap 1
%typemap(in) double {
  ... get a double ...
}
// typemap 2
%typemap(in) pdouble {
  ... get a positive double ...
}
double sin(double x);           // typemap 1
pdouble sqrt(pdouble x);        // typemap 2
</pre>
</div>
<p> When reducing the type, only one typedef reduction is applied at a
 time. The search process continues to apply reductions until a match is
 found or until no more reductions can be made.</p>
<p> For complicated types, the reduction process can generate a long
 list of patterns. Consider the following:</p>
<div class="code">
<pre>
typedef int Integer;
typedef Integer Row4[4];
void foo(Row4 rows[10]);
</pre>
</div>
<p> To find a match for the <tt>Row4 rows[10]</tt> argument, SWIG would
 check the following patterns, stopping only when it found a match:</p>
<div class="code">
<pre>
Row4 rows[10]
Row4 [10]
Row4 rows[ANY]
Row4 [ANY]

# Reduce Row4 --&gt; Integer[4]
Integer rows[10][4]
Integer [10][4]
Integer rows[ANY][ANY]
Integer [ANY][ANY]

# Reduce Integer --&gt; int
int rows[10][4]
int [10][4]
int rows[ANY][ANY]
int [ANY][ANY]
</pre>
</div>
<p> For parameterized types like templates, the situation is even more
 complicated. Suppose you had some declarations like this:</p>
<div class="code">
<pre>
typedef int Integer;
typedef foo&lt;Integer, Integer&gt; fooii;
void blah(fooii *x);
</pre>
</div>
<p> In this case, the following typemap patterns are searched for the
 argument <tt>fooii *x</tt>:</p>
<div class="code">
<pre>
fooii *x
fooii *

# Reduce fooii --&gt; foo&lt;Integer, Integer&gt;
foo&lt;Integer, Integer&gt; *x
foo&lt;Integer, Integer&gt; *

# Reduce Integer -&gt; int
foo&lt;int, Integer&gt; *x
foo&lt;int, Integer&gt; *

# Reduce Integer -&gt; int
foo&lt;int, int&gt; *x
foo&lt;int, int&gt; *
</pre>
</div>
<p> Typemap reductions are always applied to the left-most type that
 appears. Only when no reductions can be made to the left-most type are
 reductions made to other parts of the type. This behavior means that
 you could define a typemap for <tt>foo&lt;int, Integer&gt;</tt>, but a
 typemap for <tt>foo&lt;Integer, int&gt;</tt> would never be matched.
 Admittedly, this is rather esoteric--there's little practical reason to
 write a typemap quite like that. Of course, you could rely on this to
 confuse your coworkers even more.</p>
<p> As a point of clarification, it is worth emphasizing that typedef
 matching is a typedef<b> reduction</b> process only, that is, SWIG does
 not search for every single possible typedef. Given a type in a
 declaration, it will only reduce the type, it won't build it up looking
 for typedefs. For example, given the type <tt>Struct</tt>, the typemap
 below will not be used for the <tt>aStruct</tt> parameter, because <tt>
Struct</tt> is fully reduced:</p>
<div class="code">
<pre>
struct Struct {...};
typedef Struct StructTypedef;

%typemap(in) StructTypedef { 
  ...
}

void go(Struct aStruct);
</pre>
</div>
<h3><a name="Typemaps_nn19">13.3.3 Default typemap matching rules</a></h3>
<p> If the basic pattern matching rules result in no match being made,
 even after typedef reductions, the default typemap matching rules are
 used to look for a suitable typemap match. These rules match a generic
 typemap based on the reserved <tt>SWIGTYPE</tt> base type. For example
 pointers will use <tt>SWIGTYPE *</tt> and references will use <tt>
SWIGTYPE &amp;</tt>. More precisely, the rules are based on the C++ class
 template partial specialization matching rules used by C++ compilers
 when looking for an appropriate partial template specialization. This
 means that a match is chosen from the most specialized set of generic
 typemap types available. For example, when looking for a match to <tt>
int const *</tt>, the rules will prefer to match <tt>SWIGTYPE const *</tt>
 if available before matching <tt>SWIGTYPE *</tt>, before matching <tt>
SWIGTYPE</tt>.</p>
<p> Most SWIG language modules use typemaps to define the default
 behavior of the C primitive types. This is entirely straightforward.
 For example, a set of typemaps for primitives marshalled by value or
 const reference are written like this:</p>
<div class="code">
<pre>
%typemap(in) int           &quot;... convert to int ...&quot;;
%typemap(in) short         &quot;... convert to short ...&quot;;
%typemap(in) float         &quot;... convert to float ...&quot;;
...
%typemap(in) const int &amp;   &quot;... convert ...&quot;;
%typemap(in) const short &amp; &quot;... convert ...&quot;;
%typemap(in) const float &amp; &quot;... convert ...&quot;;
...
</pre>
</div>
<p> Since typemap matching follows all <tt>typedef</tt> declarations,
 any sort of type that is mapped to a primitive type by value or const
 reference through <tt>typedef</tt> will be picked up by one of these
 primitive typemaps. Most language modules also define typemaps for char
 pointers and char arrays to handle strings, so these non-default types
 will also be used in preference as the basic typemap matching rules
 provide a better match than the default typemap matching rules.</p>
<p> Below is a list of the typical default types supplied by language
 modules, showing what the &quot;in&quot; typemap would look like:</p>
<div class="code">
<pre>
%typemap(in) SWIGTYPE &amp;            { ... default reference handling ...                       };
%typemap(in) SWIGTYPE *            { ... default pointer handling ...                         };
%typemap(in) SWIGTYPE *const       { ... default pointer const handling ...                   };
%typemap(in) SWIGTYPE *const&amp;      { ... default pointer const reference handling ...         };
%typemap(in) SWIGTYPE[ANY]         { ... 1D fixed size arrays handling ...                    };
%typemap(in) SWIGTYPE []           { ... unknown sized array handling ...                     };
%typemap(in) enum SWIGTYPE         { ... default handling for enum values ...                 };
%typemap(in) const enum SWIGTYPE &amp; { ... default handling for const enum reference values ... };
%typemap(in) SWIGTYPE (CLASS::*)   { ... default pointer member handling ...                  };
%typemap(in) SWIGTYPE              { ... simple default handling ...                          };
</pre>
</div>
<p> If you wanted to change SWIG's default handling for simple pointers,
 you would simply redefine the rule for <tt>SWIGTYPE *</tt>. Note, the
 simple default typemap rule is used to match against simple types that
 don't match any other rules:</p>
<div class="code">
<pre>
%typemap(in) SWIGTYPE              { ... simple default handling ...                          } 
</pre>
</div>
<p> This typemap is important because it is the rule that gets triggered
 when call or return by value is used. For instance, if you have a
 declaration like this:</p>
<div class="code">
<pre>
double dot_product(Vector a, Vector b);
</pre>
</div>
<p> The <tt>Vector</tt> type will usually just get matched against <tt>
SWIGTYPE</tt>. The default implementation of <tt>SWIGTYPE</tt> is to
 convert the value into pointers (<a href="#SWIG_nn22">as described in
 this earlier section</a>).</p>
<p> By redefining <tt>SWIGTYPE</tt> it may be possible to implement
 other behavior. For example, if you cleared all typemaps for <tt>
SWIGTYPE</tt>, SWIG simply won't wrap any unknown datatype (which might
 be useful for debugging). Alternatively, you might modify SWIGTYPE to
 marshal objects into strings instead of converting them to pointers.</p>
<p> Let's consider an example where the following typemaps are defined
 and SWIG is looking for the best match for the enum shown below:</p>
<div class="code">
<pre>
%typemap(in) const Hello &amp;          { ... }
%typemap(in) const enum SWIGTYPE &amp;  { ... }
%typemap(in) enum SWIGTYPE &amp;        { ... }
%typemap(in) SWIGTYPE &amp;             { ... }
%typemap(in) SWIGTYPE               { ... }

enum Hello {};
const Hello &amp;hi;
</pre>
</div>
<p> The typemap at the top of the list will be chosen, not because it is
 defined first, but because it is the closest match for the type being
 wrapped. If any of the typemaps in the above list were not defined,
 then the next one on the list would have precedence.</p>
<p> The best way to explore the default typemaps is to look at the ones
 already defined for a particular language module. Typemap definitions
 are usually found in the SWIG library in a file such as <tt>java.swg</tt>
, <tt>csharp.swg</tt> etc. However, for many of the target languages the
 typemaps are hidden behind complicated macros, so the best way to view
 the default typemaps, or any typemaps for that matter, is to look at
 the preprocessed output by running <tt>swig -E</tt> on any interface
 file. Finally the best way to view the typemap matching rules in action
 is via the <a href="#Typemaps_debugging_search">debugging typemap
 pattern matching</a> options covered later on.</p>
<p><b> Compatibility note:</b> The default typemap matching rules were
 modified in SWIG-2.0.0 from a slightly simpler scheme to match the
 current C++ class template partial specialization matching rules.</p>
<h3><a name="Typemaps_multi_argument_typemaps_patterns">13.3.4
 Multi-arguments typemaps</a></h3>
<p> When multi-argument typemaps are specified, they take precedence
 over any typemaps specified for a single type. For example:</p>
<div class="code">
<pre>
%typemap(in) (char *buffer, int len) {
  // typemap 1
}

%typemap(in) char *buffer {
  // typemap 2
}

void foo(char *buffer, int len, int count); // (char *buffer, int len)
void bar(char *buffer, int blah);           // char *buffer
</pre>
</div>
<p> Multi-argument typemaps are also more restrictive in the way that
 they are matched. Currently, the first argument follows the matching
 rules described in the previous section, but all subsequent arguments
 must match exactly.</p>
<h3><a name="Typemaps_matching_template_comparison">13.3.5 Matching
 rules compared to C++ templates</a></h3>
<p> For those intimately familiar with C++ templates, a comparison of
 the typemap matching rules and template type deduction is interesting.
 The two areas considered are firstly the default typemaps and their
 similarities to partial template specialization and secondly,
 non-default typemaps and their similarities to full template
 specialization.</p>
<p> For default (SWIGTYPE) typemaps the rules are inspired by C++ class
 template partial specialization. For example, given partial
 specialization for <tt>T const&amp;</tt> :</p>
<div class="code">
<pre>
template &lt;typename T&gt; struct X             { void a(); };
template &lt;typename T&gt; struct X&lt; T const&amp; &gt; { void b(); };
</pre>
</div>
<p> The full (unspecialized) template is matched with most types, such
 as:</p>
<div class="code">
<pre>
X&lt; int &amp; &gt;            x1;  x1.a();
</pre>
</div>
<p> and the following all match the <tt>T const&amp;</tt> partial
 specialization:</p>
<div class="code">
<pre>
X&lt; int *const&amp; &gt;      x2;  x2.b();
X&lt; int const*const&amp; &gt; x3;  x3.b();
X&lt; int const&amp; &gt;       x4;  x4.b();
</pre>
</div>
<p> Now, given just these two default typemaps, where T is analogous to
 SWIGTYPE:</p>
<div class="code">
<pre>
%typemap(...) SWIGTYPE        { ... }
%typemap(...) SWIGTYPE const&amp; { ... }
</pre>
</div>
<p> The generic default typemap <tt>SWIGTYPE</tt> is used with most
 types, such as</p>
<div class="code">
<pre>
int &amp;
</pre>
</div>
<p> and the following all match the <tt>SWIGTYPE const&amp;</tt> typemap,
 just like the partial template matching:</p>
<div class="code">
<pre>
int *const&amp;
int const*const&amp;
int const&amp;
</pre>
</div>
<p> Note that the template and typemap matching rules are not identical
 for all default typemaps though, for example, with arrays.</p>
<p> For non-default typemaps, one might expect SWIG to follow the fully
 specialized template rules. This is nearly the case, but not quite.
 Consider a very similar example to the earlier partially specialized
 template but this time there is a fully specialized template:</p>
<div class="code">
<pre>
template &lt;typename T&gt; struct Y       { void a(); };
template &lt;&gt; struct Y&lt; int const &amp; &gt;  { void b(); };
</pre>
</div>
<p> Only the one type matches the specialized template exactly:</p>
<div class="code">
<pre>
Y&lt; int &amp; &gt;             y1;  y1.a();
Y&lt; int *const&amp; &gt;       y2;  y2.a();
Y&lt; int const *const&amp; &gt; y3;  y3.a();
Y&lt; int const&amp; &gt;        y4;  y4.b(); // fully specialized match
</pre>
</div>
<p> Given typemaps with the same types used for the template declared
 above, where T is again analogous to SWIGTYPE:</p>
<div class="code">
<pre>
%typemap(...) SWIGTYPE        { ... }
%typemap(...) int const&amp;      { ... }
</pre>
</div>
<p> The comparison between non-default typemaps and fully specialized
 single parameter templates turns out to be the same, as just the one
 type will match the non-default typemap:</p>
<div class="code">
<pre>
int &amp;
int *const&amp;
int const*const&amp;
int const&amp;        // matches non-default typemap int const&amp;
</pre>
</div>
<p> However, if a non-const type is used instead:</p>
<div class="code">
<pre>
%typemap(...) SWIGTYPE        { ... }
%typemap(...) int &amp;           { ... }
</pre>
</div>
<p> then there is a clear difference to template matching as both the
 const and non-const types match the typemap:</p>
<div class="code">
<pre>
int &amp;             // matches non-default typemap int &amp;
int *const&amp;
int const*const&amp;
int const&amp;        // matches non-default typemap int &amp;
</pre>
</div>
<p> There are other subtle differences such as typedef handling, but at
 least it should be clear that the typemap matching rules are similar to
 those for specialized template handling.</p>
<h3><a name="Typemaps_debugging_search">13.3.6 Debugging typemap pattern
 matching</a></h3>
<p> There are two useful debug command line options available for
 debugging typemaps, <tt>-debug-tmsearch</tt> and <tt>-debug-tmused</tt>
.</p>
<p> The <tt>-debug-tmsearch</tt> option is a verbose option for
 debugging typemap searches. This can be very useful for watching the
 pattern matching process in action and for debugging which typemaps are
 used. The option displays all the typemaps and types that are looked
 for until a successful pattern match is made. As the display includes
 searches for each and every type needed for wrapping, the amount of
 information displayed can be large. Normally you would manually search
 through the displayed information for the particular type that you are
 interested in.</p>
<p> For example, consider some of the code used in the <a href="#Typemaps_typedef_reductions">
Typedef reductions</a> section already covered:</p>
<div class="code">
<pre>
typedef int Integer;
typedef Integer Row4[4];
void foo(Row4 rows[10]);
</pre>
</div>
<p> A sample of the debugging output is shown below for the &quot;in&quot;
 typemap:</p>
<div class="shell">
<pre>
swig -perl -debug-tmsearch example.i
...
example.h:3: Searching for a suitable 'in' typemap for: Row4 rows[10]
  Looking for: Row4 rows[10]
  Looking for: Row4 [10]
  Looking for: Row4 rows[ANY]
  Looking for: Row4 [ANY]
  Looking for: Integer rows[10][4]
  Looking for: Integer [10][4]
  Looking for: Integer rows[ANY][ANY]
  Looking for: Integer [ANY][ANY]
  Looking for: int rows[10][4]
  Looking for: int [10][4]
  Looking for: int rows[ANY][ANY]
  Looking for: int [ANY][ANY]
  Looking for: SWIGTYPE rows[ANY][ANY]
  Looking for: SWIGTYPE [ANY][ANY]
  Looking for: SWIGTYPE rows[ANY][]
  Looking for: SWIGTYPE [ANY][]
  Looking for: SWIGTYPE *rows[ANY]
  Looking for: SWIGTYPE *[ANY]
  Looking for: SWIGTYPE rows[ANY]
  Looking for: SWIGTYPE [ANY]
  Looking for: SWIGTYPE rows[]
  Looking for: SWIGTYPE []
  Using: %typemap(in) SWIGTYPE []
...
</pre>
</div>
<p> showing that the best default match supplied by SWIG is the <tt>
SWIGTYPE []</tt> typemap. As the example shows, the successful match
 displays the used typemap source including typemap method, type and
 optional name in one of these simplified formats:</p>
<ul>
<li> <tt>Using: %typemap(method) type name</tt></li>
<li> <tt>Using: %typemap(method) type name = type2 name2</tt></li>
<li> <tt>Using: %apply type2 name2 { type name }</tt></li>
</ul>
<p> This information might meet your debugging needs, however, you might
 want to analyze further. If you next invoke SWIG with the <tt>-E</tt>
 option to display the preprocessed output, and search for the
 particular typemap used, you'll find the full typemap contents (example
 shown below for Python):</p>
<div class="code">
<pre>
%typemap(in, noblock=1) SWIGTYPE [] (void *argp = 0, int res = 0) {
  res = SWIG_ConvertPtr($input, &amp;argp, $descriptor, $disown |  0 );
  if (!SWIG_IsOK(res)) { 
    SWIG_exception_fail(SWIG_ArgError(res), &quot;in method '&quot; &quot;$symname&quot; &quot;', argument &quot;
                       &quot;$argnum&quot;&quot; of type '&quot; &quot;$type&quot;&quot;'&quot;); 
  } 
  $1 = ($ltype)(argp);
}
</pre>
</div>
<p> The generated code for the <tt>foo</tt> wrapper will then contain
 the snippets of the typemap with the special variables expanded. The
 rest of this chapter will need reading though to fully understand all
 of this, however, the relevant parts of the generated code for the
 above typemap can be seen below:</p>
<div class="code">
<pre>
SWIGINTERN PyObject *_wrap_foo(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
...
  void *argp1 = 0 ;
  int res1 = 0 ;
...
  res1 = SWIG_ConvertPtr(obj0, &amp;argp1, SWIGTYPE_p_a_4__int, 0 |  0 );
  if (!SWIG_IsOK(res1)) {
    SWIG_exception_fail(SWIG_ArgError(res1), &quot;in method '&quot; &quot;foo&quot; &quot;', argument &quot;
                       &quot;1&quot;&quot; of type '&quot; &quot;int [10][4]&quot;&quot;'&quot;); 
  } 
  arg1 = (int (*)[4])(argp1);
...
}
</pre>
</div>
<p> Searches for multi-argument typemaps are not mentioned unless a
 matching multi-argument typemap does actually exist. For example, the
 output for the code in the <a href="#Typemaps_multi_argument_typemaps_patterns">
earlier multi-arguments section</a> is as follows:</p>
<div class="shell">
<pre>
...
example.h:39: Searching for a suitable 'in' typemap for: char *buffer
  Looking for: char *buffer
  Multi-argument typemap found...
  Using: %typemap(in) (char *buffer, int len)
...
</pre>
</div>
<p> The second option for debugging is <tt>-debug-tmused</tt> and this
 displays the typemaps used. This option is a less verbose version of
 the <tt>-debug-tmsearch</tt> option as it only displays each
 successfully found typemap on a separate single line. The output
 displays the type, and name if present, the typemap method in brackets
 and then the actual typemap used in the same simplified format output
 by the <tt>-debug-tmsearch</tt> option. Below is the output for the
 example code at the start of this section on debugging.</p>
<div class="shell">
<pre>
$ swig -perl -debug-tmused example.i
example.h:3: Typemap for Row4 rows[10] (in) : %typemap(in) SWIGTYPE []
example.h:3: Typemap for Row4 rows[10] (typecheck) : %typemap(typecheck) SWIGTYPE *
example.h:3: Typemap for Row4 rows[10] (freearg) : %typemap(freearg) SWIGTYPE []
example.h:3: Typemap for void foo (out) : %typemap(out) void
</pre>
</div>
<p> Now, consider the following interface file:</p>
<div class="code">
<pre>
%module example

%{
void set_value(const char* val) {}
%}

%typemap(check) char *NON_NULL {
  if (!$1) {
    /* ... error handling ... */
  }
}

// use default pointer handling instead of strings
%apply SWIGTYPE * { const char* val, const char* another_value }

%typemap(check) const char* val = char* NON_NULL;

%typemap(arginit, noblock=1) const char* val {
  $1 = &quot;&quot;;
}

void set_value(const char* val);

</pre>
</div>
<p> and the output debug:</p>
<div class="shell">
<pre>
swig -perl5 -debug-tmused example.i
example.i:21: Typemap for char const *val (arginit) : %typemap(arginit) char const *val
example.i:21: Typemap for char const *val (in) : %apply SWIGTYPE * { char const *val }
example.i:21: Typemap for char const *val (typecheck) : %apply SWIGTYPE * { char const *val }
example.i:21: Typemap for char const *val (check) : %typemap(check) char const *val = char *NON_NULL
example.i:21: Typemap for char const *val (freearg) : %apply SWIGTYPE * { char const *val }
example.i:21: Typemap for void set_value (out) : %typemap(out) void
</pre>
</div>
<p> The following observations about what is displayed can be noted (the
 same applies for <tt>-debug-tmsearch</tt>):</p>
<ul>
<li> The relevant typemap is shown, but for typemap copying, the
 appropriate <tt>%typemap</tt> or <tt>%apply</tt> is displayed, for
 example, the &quot;check&quot; and &quot;in&quot; typemaps.</li>
<li> The typemap modifiers are not shown, eg the <tt>noblock=1</tt>
 modifier in the &quot;arginit&quot; typemap.</li>
<li> The exact <tt>%apply</tt> statement might look different to what is
 in the actual code. For example, the <tt>const char* another_value</tt>
 is not shown as it is not relevant here. Also the types may be
 displayed slightly differently - <tt>char const *</tt> and not <tt>
const char*</tt>.</li>
</ul>
<h2><a name="Typemaps_nn21">13.4 Code generation rules</a></h2>
<p> This section describes rules by which typemap code is inserted into
 the generated wrapper code.</p>
<h3><a name="Typemaps_nn22">13.4.1 Scope</a></h3>
<p> When a typemap is defined like this:</p>
<div class="code">
<pre>
%typemap(in) int {
  $1 = PyInt_AsLong($input);
}
</pre>
</div>
<p> the typemap code is inserted into the wrapper function using a new
 block scope. In other words, the wrapper code will look like this:</p>
<div class="code">
<pre>
wrap_whatever() {
  ...
  // Typemap code
  {
    arg1 = PyInt_AsLong(obj1);
  }
  ...
}
</pre>
</div>
<p> Because the typemap code is enclosed in its own block, it is legal
 to declare temporary variables for use during typemap execution. For
 example:</p>
<div class="code">
<pre>
%typemap(in) short {
  long temp;          /* Temporary value */
  if (Tcl_GetLongFromObj(interp, $input, &amp;temp) != TCL_OK) {
    return TCL_ERROR;
  }
  $1 = (short) temp;
}
</pre>
</div>
<p> Of course, any variables that you declare inside a typemap are
 destroyed as soon as the typemap code has executed (they are not
 visible to other parts of the wrapper function or other typemaps that
 might use the same variable names).</p>
<p> Occasionally, typemap code will be specified using a few alternative
 forms. For example:</p>
<div class="code">
<pre>
%typemap(in) int &quot;$1 = PyInt_AsLong($input);&quot;;
%typemap(in) int %{
$1 = PyInt_AsLong($input);
%}
%typemap(in, noblock=1) int {
$1 = PyInt_AsLong($input);
}
</pre>
</div>
<p> These three forms are mainly used for cosmetics--the specified code
 is not enclosed inside a block scope when it is emitted. This sometimes
 results in a less complicated looking wrapper function. Note that only
 the third of the three typemaps have the typemap code passed through
 the SWIG preprocessor.</p>
<h3><a name="Typemaps_nn23">13.4.2 Declaring new local variables</a></h3>
<p> Sometimes it is useful to declare a new local variable that exists
 within the scope of the entire wrapper function. A good example of this
 might be an application in which you wanted to marshal strings. Suppose
 you had a C++ function like this</p>
<div class="code">
<pre>
int foo(std::string *s);
</pre>
</div>
<p> and you wanted to pass a native string in the target language as an
 argument. For instance, in Perl, you wanted the function to work like
 this:</p>
<div class="targetlang">
<pre>
$x = foo(&quot;Hello World&quot;);
</pre>
</div>
<p> To do this, you can't just pass a raw Perl string as the <tt>
std::string *</tt> argument. Instead, you have to create a temporary <tt>
std::string</tt> object, copy the Perl string data into it, and then
 pass a pointer to the object. To do this, simply specify the typemap
 with an extra parameter like this:</p>
<div class="code">
<pre>
%typemap(in) std::string * <b>(std::string temp)</b> {
  unsigned int len;
  char        *s;
  s = SvPV($input, len);         /* Extract string data */
  temp.assign(s, len);           /* Assign to temp */
  $1 = &amp;temp;                   /* Set argument to point to temp */
}
</pre>
</div>
<p> In this case, <tt>temp</tt> becomes a local variable in the scope of
 the entire wrapper function. For example:</p>
<div class="code">
<pre>
wrap_foo() {
  std::string temp;    &lt;--- Declaration of temp goes here
  ...

  /* Typemap code */
  {
    ...
    temp.assign(s, len);
    ...
  }
  ...
}
</pre>
</div>
<p> When you set <tt>temp</tt> to a value, it persists for the duration
 of the wrapper function and gets cleaned up automatically on exit.</p>
<p> It is perfectly safe to use more than one typemap involving local
 variables in the same declaration. For example, you could declare a
 function as :</p>
<div class="code">
<pre>
void foo(std::string *x, std::string *y, std::string *z);
</pre>
</div>
<p> This is safely handled because SWIG actually renames all local
 variable references by appending an argument number suffix. Therefore,
 the generated code would actually look like this:</p>
<div class="code">
<pre>
wrap_foo() {
  int *arg1;    /* Actual arguments */
  int *arg2;
  int *arg3;
  std::string temp1;    /* Locals declared in the typemap */
  std::string temp2;
  std::string temp3;
  ...
  {
    char *s;
    unsigned int len;
    ...
    temp1.assign(s, len);
    arg1 = *temp1;
  }
  {
    char *s;
    unsigned int len;
    ...
    temp2.assign(s, len);
    arg2 = &amp;temp2;
  }
  {
    char *s;
    unsigned int len;
    ...
    temp3.assign(s, len);
    arg3 = &amp;temp3;
  }
  ...
}
</pre>
</div>
<p>There is an exception: if the variable name starts with the <tt>
_global_</tt> prefix, the argument number is not appended. Such
 variables can be used throughout the generated wrapper function. For
 example, the above typemap could be rewritten to use <tt>_global_temp</tt>
 instead of <tt>temp</tt> and the generated code would then contain a
 single <tt>_global_temp</tt> variable instead of <tt>temp1</tt>, <tt>
temp2</tt> and <tt>temp3</tt>:</p>
<div class="code">
<pre>
%typemap(in) std::string * <b>(std::string _global_temp)</b> {
 ... as above ...
}
</pre>
</div>
<p> Some typemaps do not recognize local variables (or they may simply
 not apply). At this time, only typemaps that apply to argument
 conversion support this (input typemaps such as the &quot;in&quot; typemap).</p>
<p><b> Note:</b></p>
<p> When declaring a typemap for multiple types, each type must have its
 own local variable declaration.</p>
<div class="code">
<pre>
%typemap(in) const std::string *, std::string * (std::string temp) // NO!
// only std::string * has a local variable
// const std::string * does not (oops)
....

%typemap(in) const std::string * (std::string temp), std::string * (std::string temp) // Correct
....
</pre>
</div>
<h3><a name="Typemaps_special_variables">13.4.3 Special variables</a></h3>
<p> Within all typemaps, the following special variables are expanded.
 This is by no means a complete list as some target languages have
 additional special variables which are documented in the language
 specific chapters.</p>
<center>
<table border="1" summary="Typemap special variables">
<tr><th>Variable</th><th>Meaning</th></tr>
<tr><td>$<em>n</em></td><td> A C local variable corresponding to type<em>
 n</em> in the typemap pattern.</td></tr>
<tr><td>$argnum</td><td>Argument number. Only available in typemaps
 related to argument conversion</td></tr>
<tr><td>$<em>n</em>_name</td><td>Argument name</td></tr>
<tr><td>$<em>n</em>_type</td><td>Real C datatype of type<em> n</em>.</td>
</tr>
<tr><td>$<em>n</em>_ltype</td><td>ltype of type<em> n</em></td></tr>
<tr><td>$<em>n</em>_mangle</td><td>Mangled form of type<em> n</em>. For
 example <tt>_p_Foo</tt></td></tr>
<tr><td>$<em>n</em>_descriptor</td><td>Type descriptor structure for
 type<em> n</em>. For example <tt>SWIGTYPE_p_Foo</tt>. This is primarily
 used when interacting with the run-time type checker (described later).</td>
</tr>
<tr><td>$*<em>n</em>_type</td><td>Real C datatype of type<em> n</em>
 with one pointer removed.</td></tr>
<tr><td>$*<em>n</em>_ltype</td><td>ltype of type<em> n</em> with one
 pointer removed.</td></tr>
<tr><td>$*<em>n</em>_mangle</td><td>Mangled form of type<em> n</em> with
 one pointer removed.</td></tr>
<tr><td>$*<em>n</em>_descriptor</td><td>Type descriptor structure for
 type<em> n</em> with one pointer removed.</td></tr>
<tr><td>$&amp;<em>n</em>_type</td><td>Real C datatype of type<em> n</em>
 with one pointer added.</td></tr>
<tr><td>$&amp;<em>n</em>_ltype</td><td>ltype of type<em> n</em> with one
 pointer added.</td></tr>
<tr><td>$&amp;<em>n</em>_mangle</td><td>Mangled form of type<em> n</em> with
 one pointer added.</td></tr>
<tr><td>$&amp;<em>n</em>_descriptor</td><td>Type descriptor structure for
 type<em> n</em> with one pointer added.</td></tr>
<tr><td>$<em>n</em>_basetype</td><td>Base typename with all pointers and
 qualifiers stripped.</td></tr>
</table>
</center>
<p> Within the table, $<em>n</em> refers to a specific type within the
 typemap specification. For example, if you write this</p>
<div class="code">
<pre>
%typemap(in) int *INPUT {

}
</pre>
</div>
<p> then $1 refers to <tt>int *INPUT</tt>. If you have a typemap like
 this,</p>
<div class="code">
<pre>
%typemap(in) (int argc, char *argv[]) {
  ...
}
</pre>
</div>
<p> then $1 refers to <tt>int argc</tt> and $2 refers to <tt>char
 *argv[]</tt>.</p>
<p> Substitutions related to types and names always fill in values from
 the actual code that was matched. This is useful when a typemap might
 match multiple C datatype. For example:</p>
<div class="code">
<pre>
%typemap(in)  int, short, long {
  $1 = ($1_ltype) PyInt_AsLong($input);
}
</pre>
</div>
<p> In this case, <tt>$1_ltype</tt> is replaced with the datatype that
 is actually matched.</p>
<p> When typemap code is emitted, the C/C++ datatype of the special
 variables <tt>$1</tt> and <tt>$2</tt> is always an &quot;ltype.&quot; An &quot;ltype&quot;
 is simply a type that can legally appear on the left-hand side of a C
 assignment operation. Here are a few examples of types and ltypes:</p>
<div class="diagram">
<pre>
type              ltype
------            ----------------
int               int
const int         int
const int *       int *
int [4]           int *
int [4][5]        int (*)[5]
</pre>
</div>
<p> In most cases a ltype is simply the C datatype with qualifiers
 stripped off. In addition, arrays are converted into pointers.</p>
<p> Variables such as <tt>$&amp;1_type</tt> and <tt>$*1_type</tt> are used
 to safely modify the type by removing or adding pointers. Although not
 needed in most typemaps, these substitutions are sometimes needed to
 properly work with typemaps that convert values between pointers and
 values.</p>
<p> If necessary, type related substitutions can also be used when
 declaring locals. For example:</p>
<div class="code">
<pre>
%typemap(in) int * ($*1_type temp) {
  temp = PyInt_AsLong($input);
  $1 = &amp;temp;
}
</pre>
</div>
<p> There is one word of caution about declaring local variables in this
 manner. If you declare a local variable using a type substitution such
 as <tt>$1_ltype temp</tt>, it won't work like you expect for arrays and
 certain kinds of pointers. For example, if you wrote this,</p>
<div class="code">
<pre>
%typemap(in) int [10][20] {
  $1_ltype temp;
}
</pre>
</div>
<p> then the declaration of <tt>temp</tt> will be expanded as</p>
<div class="code">
<pre>
int (*)[20] temp;
</pre>
</div>
<p> This is illegal C syntax and won't compile. There is currently no
 straightforward way to work around this problem in SWIG due to the way
 that typemap code is expanded and processed. However, one possible
 workaround is to simply pick an alternative type such as <tt>void *</tt>
 and use casts to get the correct type when needed. For example:</p>
<div class="code">
<pre>
%typemap(in) int [10][20] {
  void *temp;
  ...
  (($1_ltype) temp)[i][j] = x;    /* set a value */
  ...
}
</pre>
</div>
<p> Another approach, which only works for arrays is to use the <tt>
$1_basetype</tt> substitution. For example:</p>
<div class="code">
<pre>
%typemap(in) int [10][20] {
  $1_basetype temp[10][20];
  ...
  temp[i][j] = x;    /* set a value */
  ...
}
</pre>
</div>
<h3><a name="Typemaps_special_variable_macros">13.4.4 Special variable
 macros</a></h3>
<p> Special variable macros are like macro functions in that they take
 one or more input arguments which are used for the macro expansion.
 They look like macro/function calls but use the special variable <tt>$</tt>
 prefix to the macro name. Note that unlike normal macros, the expansion
 is not done by the preprocessor, it is done during the SWIG
 parsing/compilation stages. The following special variable macros are
 available across all language modules.</p>
<h4><a name="Typemaps_special_macro_descriptor">13.4.4.1
 $descriptor(type)</a></h4>
<p> This macro expands into the type descriptor structure for any C/C++
 type specified in <tt>type</tt>. It behaves like the <tt>$1_descriptor</tt>
 special variable described above except that the type to expand is
 taken from the macro argument rather than inferred from the typemap
 type. For example, <tt>$descriptor(std::vector&lt;int&gt; *)</tt> will expand
 into <tt>SWIGTYPE_p_std__vectorT_int_t</tt>. This macro is mostly used
 in the scripting target languages and is demonstrated later in the <a href="#Typemaps_runtime_type_checker_usage">
Run-time type checker usage</a> section.</p>
<h4><a name="Typemaps_special_macro_typemap">13.4.4.2 $typemap(method,
 typepattern)</a></h4>
<p> This macro uses the <a href="#Typemaps_pattern_matching">pattern
 matching rules</a> described earlier to lookup and then substitute the
 special variable macro with the code in the matched typemap. The
 typemap to search for is specified by the arguments, where <tt>method</tt>
 is the typemap method name and <tt>typepattern</tt> is a type pattern
 as per the <tt>%typemap</tt> specification in the <a href="#Typemaps_defining">
Defining a typemap</a> section.</p>
<p> The special variables within the matched typemap are expanded into
 those for the matched typemap type, not the typemap within which the
 macro is called. In practice, there is little use for this macro in the
 scripting target languages. It is mostly used in the target languages
 that are statically typed as a way to obtain the target language type
 given the C/C++ type and more commonly only when the C++ type is a
 template parameter.</p>
<p> The example below is for C# only and uses some typemap method names
 documented in the C# chapter, but it shows some of the possible syntax
 variations.</p>
<div class="code">
<pre>
%typemap(cstype) unsigned long    &quot;uint&quot;
%typemap(cstype) unsigned long bb &quot;bool&quot;
%typemap(cscode) BarClass %{
  void foo($typemap(cstype, unsigned long aa) var1,
           $typemap(cstype, unsigned long bb) var2,
           $typemap(cstype, (unsigned long bb)) var3,
           $typemap(cstype, unsigned long) var4)
  {
    // do something
  }
%}
</pre>
</div>
<p> The result is the following expansion</p>
<div class="code">
<pre>
%typemap(cstype) unsigned long    &quot;uint&quot;
%typemap(cstype) unsigned long bb &quot;bool&quot;
%typemap(cscode) BarClass %{
  void foo(uint var1,
           bool var2,
           bool var3,
           uint var4)
  {
    // do something
  }
%}
</pre>
</div>
<h3><a name="Typemaps_special_variable_attributes">13.4.5 Special
 variables and typemap attributes</a></h3>
<p> As of SWIG-3.0.7 typemap attributes will also expand special
 variables and special variable macros.</p>
<p> Example usage showing the expansion in the 'out' attribute (C#
 specific) as well as the main typemap body:</p>
<div class="code">
<pre>
%typemap(ctype, out=&quot;$*1_ltype&quot;) unsigned int&amp; &quot;$*1_ltype&quot;
</pre>
</div>
<p> is equivalent to the following as <tt>$*1_ltype</tt> expands to <tt>
unsigned int</tt>:</p>
<div class="code">
<pre>
%typemap(ctype, out=&quot;unsigned int&quot;) unsigned int&amp; &quot;unsigned int&quot;
</pre>
</div>
<h3><a name="Typemaps_special_variables_and_macros">13.4.6 Special
 variables combined with special variable macros</a></h3>
<p> Special variables can also be used within special variable macros.
 The special variables are expanded before they are used in the special
 variable macros.</p>
<p> Consider the following C# typemaps:</p>
<div class="code">
<pre>
%typemap(cstype) unsigned int &quot;uint&quot;
%typemap(cstype, out=&quot;$typemap(cstype, $*1_ltype)&quot;) unsigned int&amp; &quot;$typemap(cstype, $*1_ltype)&quot;
</pre>
</div>
<p> Special variables are expanded first and hence the above is
 equivalent to:</p>
<div class="code">
<pre>
%typemap(cstype) unsigned int &quot;uint&quot;
%typemap(cstype, out=&quot;$typemap(cstype, unsigned int)&quot;) unsigned int&amp; &quot;$typemap(cstype, unsigned int)&quot;
</pre>
</div>
<p> which then expands to:</p>
<div class="code">
<pre>
%typemap(cstype) unsigned int &quot;uint&quot;
%typemap(cstype, out=&quot;uint&quot;) unsigned int&amp; &quot;uint&quot;
</pre>
</div>
<h2><a name="Typemaps_nn25">13.5 Common typemap methods</a></h2>
<p> The family of typemaps recognized by a language module may vary.
 However, the following typemap methods are nearly universal:</p>
<h3><a name="Typemaps_nn26">13.5.1 &quot;in&quot; typemap</a></h3>
<p> The &quot;in&quot; typemap is used to convert function arguments from the
 target language to C. For example:</p>
<div class="code">
<pre>
%typemap(in) int {
  $1 = PyInt_AsLong($input);
}
</pre>
</div>
<p> The following special variables are available:</p>
<div class="code">
<pre>
$input            - Input object holding value to be converted.
$symname          - Name of function/method being wrapped
</pre>
</div>
<p> This is probably the most commonly redefined typemap because it can
 be used to implement customized conversions.</p>
<p> In addition, the &quot;in&quot; typemap allows the number of converted
 arguments to be specified. The <tt>numinputs</tt> attributes
 facilitates this. For example:</p>
<div class="code">
<pre>
// Ignored argument.
%typemap(in, numinputs=0) int *out (int temp) {
  $1 = &amp;temp;
}
</pre>
</div>
<p> At this time, only zero or one arguments may be converted. When <tt>
numinputs</tt> is set to 0, the argument is effectively ignored and
 cannot be supplied from the target language. The argument is still
 required when making the C/C++ call and the above typemap shows the
 value used is instead obtained from a locally declared variable called <tt>
temp</tt>. Usually <tt>numinputs</tt> is not specified, whereupon the
 default value is 1, that is, there is a one to one mapping of the
 number of arguments when used from the target language to the C/C++
 call. <a href="#Typemaps_multi_argument_typemaps">Multi-argument
 typemaps</a> provide a similar concept where the number of arguments
 mapped from the target language to C/C++ can be changed for multiple
 adjacent C/C++ arguments.</p>
<p><b> Compatibility note:</b> Specifying <tt>numinputs=0</tt> is the
 same as the old &quot;ignore&quot; typemap.</p>
<h3><a name="Typemaps_nn27">13.5.2 &quot;typecheck&quot; typemap</a></h3>
<p> The &quot;typecheck&quot; typemap is used to support overloaded functions and
 methods. It merely checks an argument to see whether or not it matches
 a specific type. For example:</p>
<div class="code">
<pre>
%typemap(typecheck, precedence=SWIG_TYPECHECK_INTEGER) int {
  $1 = PyInt_Check($input) ? 1 : 0;
}
</pre>
</div>
<p> For typechecking, the $1 variable is always a simple integer that is
 set to 1 or 0 depending on whether or not the input argument is the
 correct type. Set to 1 if the input argument is the correct type
 otherwise set to 0.</p>
<p> If you define new &quot;in&quot; typemaps<em> and</em> your program uses
 overloaded methods, you should also define a collection of &quot;typecheck&quot;
 typemaps. More details about this follow in the <a href="#Typemaps_overloading">
Typemaps and overloading</a> section.</p>
<h3><a name="Typemaps_nn28">13.5.3 &quot;out&quot; typemap</a></h3>
<p> The &quot;out&quot; typemap is used to convert function/method return values
 from C into the target language. For example:</p>
<div class="code">
<pre>
%typemap(out) int {
  $result = PyInt_FromLong($1);
}
</pre>
</div>
<p> The following special variables are available.</p>
<div class="code">
<pre>
$result           - Result object returned to target language.
$symname          - Name of function/method being wrapped
</pre>
</div>
<p> The &quot;out&quot; typemap supports an optional attribute flag called
 &quot;optimal&quot;. This is for code optimisation and is detailed in the <a href="#Typemaps_optimal">
Optimal code generation when returning by value</a> section.</p>
<h3><a name="Typemaps_nn29">13.5.4 &quot;arginit&quot; typemap</a></h3>
<p> The &quot;arginit&quot; typemap is used to set the initial value of a function
 argument--before any conversion has occurred. This is not normally
 necessary, but might be useful in highly specialized applications. For
 example:</p>
<div class="code">
<pre>
// Set argument to NULL before any conversion occurs
%typemap(arginit) int *data {
  $1 = NULL;
}
</pre>
</div>
<h3><a name="Typemaps_nn30">13.5.5 &quot;default&quot; typemap</a></h3>
<p> The &quot;default&quot; typemap is used to turn an argument into a default
 argument. For example:</p>
<div class="code">
<pre>
%typemap(default) int flags {
  $1 = DEFAULT_FLAGS;
}
...
int foo(int x, int y, int flags);
</pre>
</div>
<p> The primary use of this typemap is to either change the wrapping of
 default arguments or specify a default argument in a language where
 they aren't supported (like C). Target languages that do not support
 optional arguments, such as Java and C#, effectively ignore the value
 specified by this typemap as all arguments must be given.</p>
<p> Once a default typemap has been applied to an argument, all
 arguments that follow must have default values. See the <a href="#SWIG_default_args">
Default/optional arguments</a> section for further information on
 default argument wrapping.</p>
<h3><a name="Typemaps_nn31">13.5.6 &quot;check&quot; typemap</a></h3>
<p> The &quot;check&quot; typemap is used to supply value checking code during
 argument conversion. The typemap is applied<em> after</em> arguments
 have been converted. For example:</p>
<div class="code">
<pre>
%typemap(check) int positive {
  if ($1 &lt;= 0) {
    SWIG_exception(SWIG_ValueError, &quot;Expected positive value.&quot;);
  }
}
</pre>
</div>
<h3><a name="Typemaps_nn32">13.5.7 &quot;argout&quot; typemap</a></h3>
<p> The &quot;argout&quot; typemap is used to return values from arguments. This
 is most commonly used to write wrappers for C/C++ functions that need
 to return multiple values. The &quot;argout&quot; typemap is almost always
 combined with an &quot;in&quot; typemap---possibly to ignore the input value. For
 example:</p>
<div class="code">
<pre>
/* Set the input argument to point to a temporary variable */
%typemap(in, numinputs=0) int *out (int temp) {
  $1 = &amp;temp;
}

%typemap(argout) int *out {
  // Append output value $1 to $result
  ...
}
</pre>
</div>
<p> The following special variables are available.</p>
<div class="diagram">
<pre>
$result           - Result object returned to target language.
$input            - The original input object passed.
$symname          - Name of function/method being wrapped
</pre>
</div>
<p> The code supplied to the &quot;argout&quot; typemap is always placed after the
 &quot;out&quot; typemap. If multiple return values are used, the extra return
 values are often appended to return value of the function.</p>
<p> See the <tt>typemaps.i</tt> library file for examples.</p>
<h3><a name="Typemaps_nn33">13.5.8 &quot;freearg&quot; typemap</a></h3>
<p> The &quot;freearg&quot; typemap is used to cleanup argument data. It is only
 used when an argument might have allocated resources that need to be
 cleaned up when the wrapper function exits. The &quot;freearg&quot; typemap
 usually cleans up argument resources allocated by the &quot;in&quot; typemap. For
 example:</p>
<div class="code">
<pre>
// Get a list of integers
%typemap(in) int *items {
  int nitems = Length($input);
  $1 = (int *) malloc(sizeof(int)*nitems);
}
// Free the list 
%typemap(freearg) int *items {
  free($1);
}
</pre>
</div>
<p> The &quot;freearg&quot; typemap inserted at the end of the wrapper function,
 just before control is returned back to the target language. This code
 is also placed into a special variable <tt>$cleanup</tt> that may be
 used in other typemaps whenever a wrapper function needs to abort
 prematurely.</p>
<h3><a name="Typemaps_nn34">13.5.9 &quot;newfree&quot; typemap</a></h3>
<p> The &quot;newfree&quot; typemap is used in conjunction with the <tt>%newobject</tt>
 directive and is used to deallocate memory used by the return result of
 a function. For example:</p>
<div class="code">
<pre>
%typemap(newfree) string * {
  delete $1;
}
%typemap(out) string * {
  $result = PyString_FromString($1-&gt;c_str());
}
...

%newobject foo;
...
string *foo();
</pre>
</div>
<p> See <a href="#Customization_ownership">Object ownership and
 %newobject</a> for further details.</p>
<h3><a name="Typemaps_ret">13.5.10 &quot;ret&quot; typemap</a></h3>
<p> The &quot;ret&quot; typemap is not used very often, but can be useful for
 anything associated with the return type, such as resource management,
 return value error checking, etc. Usually this can all be done in the
 &quot;out&quot; typemap, but sometimes it is handy to use the &quot;out&quot; typemap code
 untouched and add to the generated code using the code in the &quot;ret&quot;
 typemap. One such case is memory clean up. For example, a <tt>
stringheap_t</tt> type is defined indicating that the returned memory
 must be deleted and a <tt>string_t</tt> type is defined indicating that
 the returned memory must not be deleted.</p>
<div class="code">
<pre>
%typemap(ret) stringheap_t %{
  free($1);
%}

typedef char * string_t;
typedef char * stringheap_t;

string_t MakeString1();
stringheap_t MakeString2();
</pre>
</div>
<p> The &quot;ret&quot; typemap above will only be used for <tt>MakeString2</tt>,
 but both functions will use the default &quot;out&quot; typemap for <tt>char *</tt>
 provided by SWIG. The code above would ensure the appropriate memory is
 freed in all target languages as the need to provide custom &quot;out&quot;
 typemaps (which involve target language specific code) is not
 necessary.</p>
<p> This approach is an alternative to using the &quot;newfree&quot; typemap and <tt>
%newobject</tt> as there is no need to list all the functions that
 require the memory cleanup, it is purely done on types.</p>
<h3><a name="Typemaps_nn35">13.5.11 &quot;memberin&quot; typemap</a></h3>
<p> The &quot;memberin&quot; typemap is used to copy data from<em> an already
 converted input value</em> into a structure member. It is typically
 used to handle array members and other special cases. For example:</p>
<div class="code">
<pre>
%typemap(memberin) int [4] {
  memmove($1, $input, 4*sizeof(int));
}
</pre>
</div>
<p> It is rarely necessary to write &quot;memberin&quot; typemaps---SWIG already
 provides a default implementation for arrays, strings, and other
 objects.</p>
<h3><a name="Typemaps_nn36">13.5.12 &quot;varin&quot; typemap</a></h3>
<p> The &quot;varin&quot; typemap is used to convert objects in the target
 language to C for the purposes of assigning to a C/C++ global variable.
 This is implementation specific.</p>
<h3><a name="Typemaps_nn37">13.5.13 &quot;varout&quot; typemap</a></h3>
<p> The &quot;varout&quot; typemap is used to convert a C/C++ object to an object
 in the target language when reading a C/C++ global variable. This is
 implementation specific.</p>
<h3><a name="Typemaps_throws_typemap">13.5.14 &quot;throws&quot; typemap</a></h3>
<p> The &quot;throws&quot; typemap is only used when SWIG parses a C++ method with
 an exception specification or has the <tt>%catches</tt> feature
 attached to the method (see <a href="#SWIGPlus_catches">Exception
 handling with %catches</a>). It provides a default mechanism for
 handling C++ methods that have declared the exceptions they will throw.
 The purpose of this typemap is to convert a C++ exception into an error
 or exception in the target language. It is slightly different to the
 other typemaps as it is based around the exception type rather than the
 type of a parameter or variable. For example:</p>
<div class="code">
<pre>
%typemap(throws) const char * %{
  PyErr_SetString(PyExc_RuntimeError, $1);
  SWIG_fail;
%}

// Either an exception specification on the method
  void bar() throw (const char *);

// Or a %catches feature attached to the method
  %catches(const char *) bar();
  void bar();
</pre>
</div>
<p> As can be seen from the resulting generated code below, SWIG
 generates an exception handler when wrapping the <tt>bar</tt> function
 with the catch block comprising the &quot;throws&quot; typemap content.</p>
<div class="code">
<pre>
...
try {
  bar();
} catch(char const *_e) {
  PyErr_SetString(PyExc_RuntimeError, _e);
  SWIG_fail;
}
...
</pre>
</div>
<p> Note that if your methods do not have an exception specification but
 they do throw exceptions and you are not using <tt>%catches</tt>, SWIG
 cannot know how to deal with them. Please also see the <a href="#Customization_exception">
Exception handling with %exception</a> section for another way to handle
 exceptions.</p>
<h2><a name="Typemaps_nn39">13.6 Some typemap examples</a></h2>
<p> This section contains a few examples. Consult language module
 documentation for more examples.</p>
<h3><a name="Typemaps_nn40">13.6.1 Typemaps for arrays</a></h3>
<p> A common use of typemaps is to provide support for C arrays
 appearing both as arguments to functions and as structure members.</p>
<p> For example, suppose you had a function like this:</p>
<div class="code">
<pre>
void set_vector(int type, float value[4]);
</pre>
</div>
<p> If you wanted to handle <tt>float value[4]</tt> as a list of floats,
 you might write a typemap similar to this:</p>
<div class="code">
<pre>

%typemap(in) float value[4] (float temp[4]) {
  int i;
  if (!PySequence_Check($input)) {
    PyErr_SetString(PyExc_ValueError, &quot;Expected a sequence&quot;);
    SWIG_fail;
  }
  if (PySequence_Length($input) != 4) {
    PyErr_SetString(PyExc_ValueError, &quot;Size mismatch. Expected 4 elements&quot;);
    SWIG_fail;
  }
  for (i = 0; i &lt; 4; i++) {
    PyObject *o = PySequence_GetItem($input, i);
    if (PyNumber_Check(o)) {
      temp[i] = (float) PyFloat_AsDouble(o);
    } else {
      PyErr_SetString(PyExc_ValueError, &quot;Sequence elements must be numbers&quot;);      
      SWIG_fail;
    }
  }
  $1 = temp;
}
</pre>
</div>
<p> In this example, the variable <tt>temp</tt> allocates a small array
 on the C stack. The typemap then populates this array and passes it to
 the underlying C function.</p>
<p> When used from Python, the typemap allows the following type of
 function call:</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; set_vector(type, [ 1, 2.5, 5, 20 ])
</pre>
</div>
<p> If you wanted to generalize the typemap to apply to arrays of all
 dimensions you might write this:</p>
<div class="code">
<pre>
%typemap(in) float value[ANY] (float temp[$1_dim0]) {
  int i;
  if (!PySequence_Check($input)) {
    PyErr_SetString(PyExc_ValueError, &quot;Expected a sequence&quot;);
    SWIG_fail;
  }
  if (PySequence_Length($input) != $1_dim0) {
    PyErr_SetString(PyExc_ValueError, &quot;Size mismatch. Expected $1_dim0 elements&quot;);
    SWIG_fail;
  }
  for (i = 0; i &lt; $1_dim0; i++) {
    PyObject *o = PySequence_GetItem($input, i);
    if (PyNumber_Check(o)) {
      temp[i] = (float) PyFloat_AsDouble(o);
    } else {
      PyErr_SetString(PyExc_ValueError, &quot;Sequence elements must be numbers&quot;);      
      SWIG_fail;
    }
  }
  $1 = temp;
}
</pre>
</div>
<p> In this example, the special variable <tt>$1_dim0</tt> is expanded
 with the actual array dimensions. Multidimensional arrays can be
 matched in a similar manner. For example:</p>
<div class="code">
<pre>
%typemap(in) float matrix[ANY][ANY] (float temp[$1_dim0][$1_dim1]) {
  ... convert a 2d array ...
}
</pre>
</div>
<p> For large arrays, it may be impractical to allocate storage on the
 stack using a temporary variable as shown. To work with heap allocated
 data, the following technique can be used.</p>
<div class="code">
<pre>
%typemap(in) float value[ANY] {
  int i;
  if (!PySequence_Check($input)) {
    PyErr_SetString(PyExc_ValueError, &quot;Expected a sequence&quot;);
    SWIG_fail;
  }
  if (PySequence_Length($input) != $1_dim0) {
    PyErr_SetString(PyExc_ValueError, &quot;Size mismatch. Expected $1_dim0 elements&quot;);
    SWIG_fail;
  }
  $1 = (float *) malloc($1_dim0*sizeof(float));
  for (i = 0; i &lt; $1_dim0; i++) {
    PyObject *o = PySequence_GetItem($input, i);
    if (PyNumber_Check(o)) {
      $1[i] = (float) PyFloat_AsDouble(o);
    } else {
      free($1);
      PyErr_SetString(PyExc_ValueError, &quot;Sequence elements must be numbers&quot;);
      SWIG_fail;
    }
  }
}
%typemap(freearg) float value[ANY] {
  if ($1) free($1);
}
</pre>
</div>
<p> In this case, an array is allocated using <tt>malloc</tt>. The <tt>
freearg</tt> typemap is then used to release the argument after the
 function has been called.</p>
<p> Another common use of array typemaps is to provide support for array
 structure members. Due to subtle differences between pointers and
 arrays in C, you can't just &quot;assign&quot; to a array structure member.
 Instead, you have to explicitly copy elements into the array. For
 example, suppose you had a structure like this:</p>
<div class="code">
<pre>
struct SomeObject {
  float  value[4];
  ...
};
</pre>
</div>
<p> When SWIG runs, it won't produce any code to set the <tt>vec</tt>
 member. You may even get a warning message like this:</p>
<div class="shell">
<pre>
$ swig -python  example.i
example.i:10: Warning 462: Unable to set variable of type float [4].
</pre>
</div>
<p> These warning messages indicate that SWIG does not know how you want
 to set the <tt>vec</tt> field.</p>
<p> To fix this, you can supply a special &quot;memberin&quot; typemap like this:</p>
<div class="code">
<pre>
%typemap(memberin) float [ANY] {
  int i;
  for (i = 0; i &lt; $1_dim0; i++) {
      $1[i] = $input[i];
  }
}
</pre>
</div>
<p> The memberin typemap is used to set a structure member from data
 that has already been converted from the target language to C. In this
 case, <tt>$input</tt> is the local variable in which converted input
 data is stored. This typemap then copies this data into the structure.</p>
<p> When combined with the earlier typemaps for arrays, the combination
 of the &quot;in&quot; and &quot;memberin&quot; typemap allows the following usage:</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; s = SomeObject()
&gt;&gt;&gt; s.x = [1, 2.5, 5, 10]
</pre>
</div>
<p> Related to structure member input, it may be desirable to return
 structure members as a new kind of object. For example, in this
 example, you will get very odd program behavior where the structure
 member can be set nicely, but reading the member simply returns a
 pointer:</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; s = SomeObject()
&gt;&gt;&gt; s.x = [1, 2.5, 5, 10]
&gt;&gt;&gt; print s.x
_1008fea8_p_float
&gt;&gt;&gt; 
</pre>
</div>
<p> To fix this, you can write an &quot;out&quot; typemap. For example:</p>
<div class="code">
<pre>
%typemap(out) float [ANY] {
  int i;
  $result = PyList_New($1_dim0);
  for (i = 0; i &lt; $1_dim0; i++) {
    PyObject *o = PyFloat_FromDouble((double) $1[i]);
    PyList_SetItem($result, i, o);
  }
}
</pre>
</div>
<p> Now, you will find that member access is quite nice:</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; s = SomeObject()
&gt;&gt;&gt; s.x = [1, 2.5, 5, 10]
&gt;&gt;&gt; print s.x
[ 1, 2.5, 5, 10]
</pre>
</div>
<p><b> Compatibility Note:</b> SWIG1.1 used to provide a special
 &quot;memberout&quot; typemap. However, it was mostly useless and has since been
 eliminated. To return structure members, simply use the &quot;out&quot; typemap.</p>
<h3><a name="Typemaps_nn41">13.6.2 Implementing constraints with
 typemaps</a></h3>
<p> One particularly interesting application of typemaps is the
 implementation of argument constraints. This can be done with the
 &quot;check&quot; typemap. When used, this allows you to provide code for
 checking the values of function arguments. For example:</p>
<div class="code">
<pre>
%module math

%typemap(check) double posdouble {
  if ($1 &lt; 0) {
    croak(&quot;Expecting a positive number&quot;);
  }
}

...
double sqrt(double posdouble);

</pre>
</div>
<p> This provides a sanity check to your wrapper function. If a negative
 number is passed to this function, a Perl exception will be raised and
 your program terminated with an error message.</p>
<p> This kind of checking can be particularly useful when working with
 pointers. For example:</p>
<div class="code">
<pre>
%typemap(check) Vector * {
  if ($1 == 0) {
    PyErr_SetString(PyExc_TypeError, &quot;NULL Pointer not allowed&quot;);
    SWIG_fail;
  }
}

</pre>
</div>
<p> will prevent any function involving a <tt>Vector *</tt> from
 accepting a NULL pointer. As a result, SWIG can often prevent a
 potential segmentation faults or other run-time problems by raising an
 exception rather than blindly passing values to the underlying C/C++
 program.</p>
<h2><a name="Typemaps_nn43">13.7 Typemaps for multiple target languages</a>
</h2>
<p> The code within typemaps is usually language dependent, however,
 many target languages support the same typemaps. In order to
 distinguish typemaps across different languages, the preprocessor
 should be used. For example, the &quot;in&quot; typemap for Perl and Ruby could
 be written as:</p>
<div class="code">
<pre>
#if defined(SWIGPERL)
  %typemap(in) int &quot;$1 = ($1_ltype) SvIV($input);&quot;
#elif defined(SWIGRUBY)
  %typemap(in) int &quot;$1 = NUM2INT($input);&quot;
#else
  #warning no &quot;in&quot; typemap defined
#endif
</pre>
</div>
<p> The full set of language specific macros is defined in the <a href="#Preprocessor_condition_compilation">
Conditional Compilation</a> section. The example above also shows a
 common approach of issuing a warning for an as yet unsupported
 language.</p>
<p><b> Compatibility note:</b> In SWIG-1.1 different languages could be
 distinguished with the language name being put within the <tt>%typemap</tt>
 directive, for example,
<br> <tt>%typemap(ruby, in) int &quot;$1 = NUM2INT($input);&quot;</tt>.</p>
<h2><a name="Typemaps_optimal">13.8 Optimal code generation when
 returning by value</a></h2>
<p> The &quot;out&quot; typemap is the main typemap for return types. This typemap
 supports an optional attribute flag called &quot;optimal&quot;, which is for
 reducing the number of temporary variables and the amount of generated
 code, thereby giving the compiler the opportunity to use<i> return
 value optimization</i> for generating faster executing code. It only
 really makes a difference when returning objects by value and has some
 limitations on usage, as explained later on.</p>
<p> When a function returns an object by value, SWIG generates code that
 instantiates the default type on the stack then assigns the value
 returned by the function call to it. A copy of this object is then made
 on the heap and this is what is ultimately stored and used from the
 target language. This will be clearer considering an example. Consider
 running the following code through SWIG:</p>
<div class="code">
<pre>
%typemap(out) SWIGTYPE %{
  $result = new $1_ltype((const $1_ltype &amp;)$1);
%}

%inline %{
#include &lt;iostream&gt;
using namespace std;

struct XX {
  XX() { cout &lt;&lt; &quot;XX()&quot; &lt;&lt; endl; }
  XX(int i) { cout &lt;&lt; &quot;XX(&quot; &lt;&lt; i &lt;&lt; &quot;)&quot; &lt;&lt; endl; }
  XX(const XX &amp;other) { cout &lt;&lt; &quot;XX(const XX &amp;)&quot; &lt;&lt; endl; }
  XX &amp; operator =(const XX &amp;other) { cout &lt;&lt; &quot;operator=(const XX &amp;)&quot; &lt;&lt; endl; return *this; }
  ~XX() { cout &lt;&lt; &quot;~XX()&quot; &lt;&lt; endl; }
  static XX create() { 
    return XX(0);
  }
};
%}
</pre>
</div>
<p> The &quot;out&quot; typemap shown is the default typemap for C# when returning
 objects by value. When making a call to <tt>XX::create()</tt> from C#,
 the output is as follows:</p>
<div class="targetlang">
<pre>
XX()
XX(0)
operator=(const XX &amp;)
~XX()
XX(const XX &amp;)
~XX()
~XX()
</pre>
</div>
<p> Note that three objects are being created as well as an assignment.
 Wouldn't it be great if the <tt>XX::create()</tt> method was the only
 time a constructor was called? As the method returns by value, this is
 asking a lot and the code that SWIG generates by default makes it
 impossible for the compiler to use<i> return value optimisation (RVO)</i>
. However, this is where the &quot;optimal&quot; attribute in the &quot;out&quot; typemap
 can help out. If the typemap code is kept the same and just the
 &quot;optimal&quot; attribute specified like this:</p>
<div class="code">
<pre>
%typemap(out, optimal=&quot;1&quot;) SWIGTYPE %{
  $result = new $1_ltype((const $1_ltype &amp;)$1);
%}
</pre>
</div>
<p> then when the code is run again, the output is simply:</p>
<div class="targetlang">
<pre>
XX(0)
~XX()
</pre>
</div>
<p> How the &quot;optimal&quot; attribute works is best explained using the
 generated code. Without &quot;optimal&quot;, the generated code is:</p>
<div class="code">
<pre>
SWIGEXPORT void * SWIGSTDCALL CSharp_XX_create() {
  void * jresult ;
  XX result;
  result = XX::create();
  jresult = new XX((const XX &amp;)result);
  return jresult;
}

</pre>
</div>
<p> With the &quot;optimal&quot; attribute, the code is:</p>
<div class="code">
<pre>
SWIGEXPORT void * SWIGSTDCALL CSharp_XX_create() {
  void * jresult ;
  jresult = new XX((const XX &amp;)XX::create());
  return jresult;
}
</pre>
</div>
<p> The major difference is the <tt>result</tt> temporary variable
 holding the value returned from <tt>XX::create()</tt> is no longer
 generated and instead the copy constructor call is made directly from
 the value returned by <tt>XX::create()</tt>. With modern compilers
 implementing RVO, the copy is not actually done, in fact the object is
 never created on the stack in <tt>XX::create()</tt> at all, it is
 simply created directly on the heap. In the first instance, the <tt>$1</tt>
 special variable in the typemap is expanded into <tt>result</tt>. In
 the second instance, <tt>$1</tt> is expanded into <tt>XX::create()</tt>
 and this is essentially what the &quot;optimal&quot; attribute is telling SWIG to
 do.</p>
<p> The &quot;optimal&quot; attribute optimisation is not turned on by default as
 it has a number of restrictions. Firstly, some code cannot be condensed
 into a simple call for passing into the copy constructor. One common
 occurrence is when <a href="#Customization_exception">%exception</a> is
 used. Consider adding the following <tt>%exception</tt> to the example:</p>
<div class="code">
<pre>
%exception XX::create() %{
try {
  $action
} catch(const std::exception &amp;e) {
  cout &lt;&lt; e.what() &lt;&lt; endl;
}
%}
</pre>
</div>
<p> SWIG can detect when the &quot;optimal&quot; attribute cannot be used and will
 ignore it and in this case will issue the following warning:</p>
<div class="targetlang">
<pre>
example.i:28: Warning 474: Method XX::create() usage of the optimal attribute ignored
example.i:14: Warning 474: in the out typemap as the following cannot be used to generate
optimal code: 
try {
  result = XX::create();
} catch(const std::exception &amp;e) {
  cout &lt;&lt; e.what() &lt;&lt; endl;
}
</pre>
</div>
<p> It should be clear that the above code cannot be used as the
 argument to the copy constructor call, that is, for the <tt>$1</tt>
 substitution.</p>
<p> Secondly, if the typemaps uses <tt>$1</tt> more than once, then
 multiple calls to the wrapped function will be made. Obviously that is
 not very optimal. In fact SWIG attempts to detect this and will issue a
 warning something like:</p>
<div class="targetlang">
<pre>
example.i:21: Warning 475: Multiple calls to XX::create() might be generated due to
example.i:7: Warning 475: optimal attribute usage in the out typemap.
</pre>
</div>
<p> However, it doesn't always get it right, for example when <tt>$1</tt>
 is within some commented out code.</p>
<h2><a name="Typemaps_multi_argument_typemaps">13.9 Multi-argument
 typemaps</a></h2>
<p> So far, the typemaps presented have focused on the problem of
 dealing with single values. For example, converting a single input
 object to a single argument in a function call. However, certain
 conversion problems are difficult to handle in this manner. As an
 example, consider the example at the very beginning of this chapter:</p>
<div class="code">
<pre>
int foo(int argc, char *argv[]);
</pre>
</div>
<p> Suppose that you wanted to wrap this function so that it accepted a
 single list of strings like this:</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; foo([&quot;ale&quot;, &quot;lager&quot;, &quot;stout&quot;])
</pre>
</div>
<p> To do this, you not only need to map a list of strings to <tt>char
 *argv[]</tt>, but the value of <tt>int argc</tt> is implicitly
 determined by the length of the list. Using only simple typemaps, this
 type of conversion is possible, but extremely painful. Multi-argument
 typemaps help in this situation.</p>
<p> A multi-argument typemap is a conversion rule that specifies how to
 convert a<em> single</em> object in the target language to a set of
 consecutive function arguments in C/C++. For example, the following
 multi-argument maps perform the conversion described for the above
 example:</p>
<div class="code">
<pre>
%typemap(in) (int argc, char *argv[]) {
  int i;
  if (!PyList_Check($input)) {
    PyErr_SetString(PyExc_ValueError, &quot;Expecting a list&quot;);
    SWIG_fail;
  }
  $1 = PyList_Size($input);
  $2 = (char **) malloc(($1+1)*sizeof(char *));
  for (i = 0; i &lt; $1; i++) {
    PyObject *s = PyList_GetItem($input, i);
    if (!PyString_Check(s)) {
      free($2);
      PyErr_SetString(PyExc_ValueError, &quot;List items must be strings&quot;);
      SWIG_fail;
    }
    $2[i] = PyString_AsString(s);
  }
  $2[i] = 0;
}

%typemap(freearg) (int argc, char *argv[]) {
  if ($2) free($2);
}

/* Required for C++ method overloading */
%typecheck(SWIG_TYPECHECK_STRING_ARRAY) (int argc, char *argv[]) {
  $1 = PyList_Check($input) ? 1 : 0;
}
</pre>
</div>
<p> A multi-argument map is always specified by surrounding the
 arguments with parentheses as shown. For example:</p>
<div class="code">
<pre>
%typemap(in) (int argc, char *argv[]) { ... }
</pre>
</div>
<p> Within the typemap code, the variables <tt>$1</tt>, <tt>$2</tt>, and
 so forth refer to each type in the map. All of the usual substitutions
 apply--just use the appropriate <tt>$1</tt> or <tt>$2</tt> prefix on
 the variable name (e.g., <tt>$2_type</tt>, <tt>$1_ltype</tt>, etc.)</p>
<p> Multi-argument typemaps always have precedence over simple typemaps
 and SWIG always performs longest-match searching. Therefore, you will
 get the following behavior:</p>
<div class="code">
<pre>
%typemap(in) int argc                              { ... typemap 1 ... }
%typemap(in) (int argc, char *argv[])              { ... typemap 2 ... }
%typemap(in) (int argc, char *argv[], char *env[]) { ... typemap 3 ... }

int foo(int argc, char *argv[]);                   // Uses typemap 2
int bar(int argc, int x);                          // Uses typemap 1
int spam(int argc, char *argv[], char *env[]);     // Uses typemap 3
</pre>
</div>
<p> It should be stressed that multi-argument typemaps can appear
 anywhere in a function declaration and can appear more than once. For
 example, you could write this:</p>
<div class="code">
<pre>
%typemap(in) (int scount, char *swords[]) { ... }
%typemap(in) (int wcount, char *words[]) { ... }

void search_words(int scount, char *swords[], int wcount, char *words[], int maxcount);
</pre>
</div>
<p> Other directives such as <tt>%apply</tt> and <tt>%clear</tt> also
 work with multi-argument maps. For example:</p>
<div class="code">
<pre>
%apply (int argc, char *argv[]) {
    (int scount, char *swords[]),
    (int wcount, char *words[])
};
...
%clear (int scount, char *swords[]), (int wcount, char *words[]);
...
</pre>
</div>
<p> Don't forget to also provide a suitable <a href="#Typemaps_overloading">
typemap for overloaded functions</a>, such as <tt>%typecheck</tt> shown
 for foo above. This is only required if the function is overloaded in
 C++.</p>
<p> Although multi-argument typemaps may seem like an exotic, little
 used feature, there are several situations where they make sense.
 First, suppose you wanted to wrap functions similar to the low-level <tt>
read()</tt> and <tt>write()</tt> system calls. For example:</p>
<div class="code">
<pre>
typedef unsigned int size_t;

int read(int fd, void *rbuffer, size_t len);
int write(int fd, void *wbuffer, size_t len);
</pre>
</div>
<p> As is, the only way to use the functions would be to allocate memory
 and pass some kind of pointer as the second argument---a process that
 might require the use of a helper function. However, using
 multi-argument maps, the functions can be transformed into something
 more natural. For example, you might write typemaps like this:</p>
<div class="code">
<pre>
// typemap for an outgoing buffer
%typemap(in) (void *wbuffer, size_t len) {
  if (!PyString_Check($input)) {
    PyErr_SetString(PyExc_ValueError, &quot;Expecting a string&quot;);
    SWIG_fail;
  }
  $1 = (void *) PyString_AsString($input);
  $2 = PyString_Size($input);
}

// typemap for an incoming buffer
%typemap(in) (void *rbuffer, size_t len) {
  if (!PyInt_Check($input)) {
    PyErr_SetString(PyExc_ValueError, &quot;Expecting an integer&quot;);
    SWIG_fail;
  }
  $2 = PyInt_AsLong($input);
  if ($2 &lt; 0) {
    PyErr_SetString(PyExc_ValueError, &quot;Positive integer expected&quot;);
    SWIG_fail;
  }
  $1 = (void *) malloc($2);
}

// Return the buffer.  Discarding any previous return result
%typemap(argout) (void *rbuffer, size_t len) {
  Py_XDECREF($result);   /* Blow away any previous result */
  if (result &lt; 0) {      /* Check for I/O error */
    free($1);
    PyErr_SetFromErrno(PyExc_IOError);
    return NULL;
  }
  $result = PyString_FromStringAndSize($1, result);
  free($1);
}
</pre>
</div>
<p> (note: In the above example, <tt>$result</tt> and <tt>result</tt>
 are two different variables. <tt>result</tt> is the real C datatype
 that was returned by the function. <tt>$result</tt> is the scripting
 language object being returned to the interpreter.).</p>
<p> Now, in a script, you can write code that simply passes buffers as
 strings like this:</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; f = example.open(&quot;Makefile&quot;)
&gt;&gt;&gt; example.read(f, 40)
'TOP        = ../..\nSWIG       = $(TOP)/.'
&gt;&gt;&gt; example.read(f, 40)
'./swig\nSRCS       = example.c\nTARGET    '
&gt;&gt;&gt; example.close(f)
0
&gt;&gt;&gt; g = example.open(&quot;foo&quot;, example.O_WRONLY | example.O_CREAT, 0644)
&gt;&gt;&gt; example.write(g, &quot;Hello world\n&quot;)
12
&gt;&gt;&gt; example.write(g, &quot;This is a test\n&quot;)
15
&gt;&gt;&gt; example.close(g)
0
&gt;&gt;&gt;
</pre>
</div>
<p> A number of multi-argument typemap problems also arise in libraries
 that perform matrix-calculations--especially if they are mapped onto
 low-level Fortran or C code. For example, you might have a function
 like this:</p>
<div class="code">
<pre>
int is_symmetric(double *mat, int rows, int columns);
</pre>
</div>
<p> In this case, you might want to pass some kind of higher-level
 object as an matrix. To do this, you could write a multi-argument
 typemap like this:</p>
<div class="code">
<pre>
%typemap(in) (double *mat, int rows, int columns) {
  MatrixObject *a;
  a = GetMatrixFromObject($input);     /* Get matrix somehow */

  /* Get matrix properties */
  $1 = GetPointer(a);
  $2 = GetRows(a);
  $3 = GetColumns(a);
}
</pre>
</div>
<p> This kind of technique can be used to hook into scripting-language
 matrix packages such as Numeric Python. However, it should also be
 stressed that some care is in order. For example, when crossing
 languages you may need to worry about issues such as row-major vs.
 column-major ordering (and perform conversions if needed). Note that
 multi-argument typemaps cannot deal with non-consecutive C/C++
 arguments; a workaround such as a helper function re-ordering the
 arguments to make them consecutive will need to be written.</p>
<h2><a name="Typemaps_warnings">13.10 Typemap warnings</a></h2>
<p> Warnings can be added to typemaps so that SWIG generates a warning
 message whenever the typemap is used. See the information in the <a href="#Warnings_nn5">
issuing warnings</a> section.</p>
<h2><a name="Typemaps_fragments">13.11 Typemap fragments</a></h2>
<p> The primary purpose of fragments is to reduce code bloat that
 repeated use of typemap code can lead to. Fragments are snippets of
 code that can be thought of as code dependencies of a typemap. If a
 fragment is used by more than one typemap, then the snippet of code
 within the fragment is only generated once. Code bloat is typically
 reduced by moving typemap code into a support function and then placing
 the support function into a fragment.</p>
<p> For example, if you have a very long typemap</p>
<div class="code">
<pre>
%typemap(in) MyClass * {
  MyClass *value = 0;

  ... many lines of marshalling code  ...

  $result = value;
}
</pre>
</div>
<p> the same marshalling code is often repeated in several typemaps,
 such as &quot;in&quot;, &quot;varin&quot;, &quot;directorout&quot;, etc. SWIG copies the code for
 each argument that requires the typemap code, easily leading to code
 bloat in the generated code. To eliminate this, define a fragment that
 includes the common marshalling code:</p>
<div class="code">
<pre>
%fragment(&quot;AsMyClass&quot;, &quot;header&quot;) {
  MyClass *AsMyClass(PyObject *obj) {
    MyClass *value = 0;

    ... many lines of marshalling code  ...

    return value;
  }
}

%typemap(in, fragment=&quot;AsMyClass&quot;) MyClass * {
  $result = AsMyClass($input);
}

%typemap(varin, fragment=&quot;AsMyClass&quot;) MyClass * {
  $result = AsMyClass($input);
}
</pre>
</div>
<p> When the &quot;in&quot; or &quot;varin&quot; typemaps for MyClass are required, the
 contents of the fragment called &quot;AsMyClass&quot; is added to the &quot;header&quot;
 section within the generated code, and then the typemap code is
 emitted. Hence, the method <tt>AsMyClass</tt> will be generated into
 the wrapper code before any typemap code that calls it.</p>
<p> To define a fragment you need a fragment name, a section name for
 generating the fragment code into, and the code itself. See <a href="#SWIG_nn42">
Code insertion blocks</a> for a full list of section names. Usually the
 section name used is &quot;header&quot;. Different delimiters can be used:</p>
<div class="code">
<pre>
%fragment(&quot;my_name&quot;, &quot;header&quot;) %{ ... %}
%fragment(&quot;my_name&quot;, &quot;header&quot;) { ... }
%fragment(&quot;my_name&quot;, &quot;header&quot;) &quot; ... &quot;
</pre>
</div>
<p> and these follow the usual preprocessing rules mentioned in the <a href="#Preprocessor_delimiters">
Preprocessing delimiters</a> section. The following are some rules and
 guidelines for using fragments:</p>
<ol>
<li>
<p> A fragment is added to the wrapping code only once. When using the <tt>
MyClass *</tt> typemaps above and wrapping the method:</p>
<div class="code">
<pre>
void foo(MyClass *a, MyClass *b);
</pre>
</div>
<p> the generated code will look something like:</p>
<div class="code">
<pre>
MyClass *AsMyClass(PyObject *obj) {
  ...
}

void _wrap_foo(...) {
  ....
  arg1 = AsMyClass(obj1);
  arg2 = AsMyClass(obj2);
  ...
  foo(arg1, arg2);
}
</pre>
</div>
<p> even as there is duplicated typemap code to process both <tt>a</tt>
 and <tt>b</tt>, the <tt>AsMyClass</tt> method will be defined only
 once.</p>
</li>
<li>
<p> A fragment should only be defined once. If there is more than one
 definition, the first definition is the one used. All other definitions
 are silently ignored. For example, if you have</p>
<div class="code">
<pre>
%fragment(&quot;AsMyClass&quot;, &quot;header&quot;) { ...definition 1... }
....
%fragment(&quot;AsMyClass&quot;, &quot;header&quot;) { ...definition 2... }
</pre>
</div>
<p> only the first definition is used. In this way you can override the
 default fragments in a SWIG library by defining your fragment before
 the library <tt>%include</tt>. Note that this behavior is the opposite
 to typemaps, where the last typemap defined/applied prevails. Fragments
 follow the first-in-first-out convention since they are intended to be
 global, while typemaps are intended to be locally specialized.</p>
</li>
<li>
<p> Fragment names cannot contain commas.</p>
</li>
<li>
<p> A fragment can use one or more additional fragments, for example:</p>
<div class="code">
<pre>
%fragment(&quot;&lt;limits.h&gt;&quot;, &quot;header&quot;) %{
  #include &lt;limits.h&gt;
%}


%fragment(&quot;AsMyClass&quot;, &quot;header&quot;, fragment=&quot;&lt;limits.h&gt;&quot;) {
  MyClass *AsMyClass(PyObject *obj) {
    MyClass *value = 0;

    ... some marshalling code  ...

    if  (ival &lt; CHAR_MIN /*defined in &lt;limits.h&gt;*/) {
      ...
    } else {
      ...
    }
    ...
    return value;
  }
}
</pre>
</div>
<p> in this case, when the &quot;AsMyClass&quot; fragment is emitted, it also
 triggers the inclusion of the &quot;&lt;limits.h&gt;&quot; fragment.</p>
</li>
<li>
<p> A fragment can have dependencies on a number of other fragments, for
 example:</p>
<div class="code">
<pre>
%fragment(&quot;bigfragment&quot;, &quot;header&quot;, fragment=&quot;frag1&quot;, fragment=&quot;frag2&quot;, fragment=&quot;frag3&quot;) &quot;&quot;;
</pre>
</div>
<p> When the &quot;bigfragment&quot; is used, the three dependent fragments
 &quot;frag1&quot;, &quot;frag2&quot; and &quot;frag3&quot; are also pulled in. Note that as
 &quot;bigframent&quot; is empty (the empty string - &quot;&quot;), it does not add any code
 itself, but merely triggers the inclusion of the other fragments.</p>
</li>
<li>
<p> A typemap can also use more than one fragment, but since the syntax
 is different, you need to specify the dependent fragments in a comma
 separated list. Consider:</p>
<div class="code">
<pre>
%typemap(in, fragment=&quot;frag1, frag2, frag3&quot;) {...}
</pre>
</div>
<p> which is equivalent to:</p>
<div class="code">
<pre>
%typemap(in, fragment=&quot;bigfragment&quot;) {...}
</pre>
</div>
<p> when used with the &quot;bigfragment&quot; defined above.</p>
</li>
<li>
<p> Finally, you can force the inclusion of a fragment at any point in
 the generated code as follows:</p>
<div class="code">
<pre>
%fragment(&quot;bigfragment&quot;);
</pre>
</div>
<p> which, for example, is very useful inside a template class. Another
 useful case is when using <tt>%extend</tt> inside a class where the
 additional code in the <tt>%extend</tt> block depends on the contents
 of the fragment.</p>
<div class="code">
<pre>
%fragment(&quot;&lt;limits.h&gt;&quot;, &quot;header&quot;) %{
  #include &lt;limits.h&gt;
%}

struct X {
  ...
  %extend {
    %fragment(&quot;&lt;limits.h&gt;&quot;);
    bool check(short val) {
      if (val &lt; SHRT_MIN /*defined in &lt;limits.h&gt;*/) {
        return true;
      } else {
        return false;
      }
    }
  }
};
</pre>
</div>
<p> Forced inclusion of fragments can be used as a replacement for <a href="#SWIG_nn42">
code insertion block</a>, ensuring the code block is only generated
 once. Consider the contents of FileA.i below which first uses a code
 insertion block and then a forced fragment inclusion to generate code:</p>
<div class="code">
<pre>
// FileA.i
%{
  #include &lt;stdio.h&gt;
%}
%fragment(&quot;&lt;limits.h&gt;&quot;);
</pre>
</div>
<p> and another file including the above:</p>
<div class="code">
<pre>
// FileB.i
%include &quot;FileA.i&quot;
</pre>
</div>
<p> The resulting code in the wrappers for FileB.i is:</p>
<div class="code">
<pre>
  #include &lt;stdio.h&gt;

  #include &lt;limits.h&gt;
</pre>
</div>
<p> A note of caution must be mentioned when using <tt>%fragment</tt>
 forced inclusion or code insertion blocks with <tt>%import</tt>. If <tt>
%import</tt> is used instead:</p>
<div class="code">
<pre>
// FileC.i
%import &quot;FileA.i&quot;
</pre>
</div>
<p> then nothing is generated in the resulting code in the wrappers for
 FileC.i. This is because <tt>%import</tt> is for collecting type
 information and does not result in any code being generated, see <a href="#Preprocessor_nn3">
File Imports</a>.</p>
</li>
</ol>
<p> Most readers will probably want to skip the next two sub-sections on
 advanced fragment usage unless a desire to really get to grips with
 some powerful but tricky macro and fragment usage that is used in parts
 of the SWIG typemap library.</p>
<h3><a name="Typemaps_fragment_type_specialization">13.11.1 Fragment
 type specialization</a></h3>
<p> Fragments can be<i> type specialized</i>. The syntax is as follows:</p>
<div class="code">
<pre>
%fragment(&quot;name&quot;, &quot;header&quot;) { ...a type independent fragment... }
%fragment(&quot;name&quot;{type}, &quot;header&quot;) { ...a type dependent fragment...  }
</pre>
</div>
<p> where <tt>type</tt> is a C/C++ type. Like typemaps, fragments can
 also be used inside templates, for example:</p>
<div class="code">
<pre>
template &lt;class T&gt;
struct A {
  %fragment(&quot;incode&quot;{A&lt;T&gt;}, &quot;header&quot;) {
    ... 'incode' specialized fragment ...
  }

  %typemap(in, fragment=&quot;incode&quot;{A&lt;T&gt;}) {
    ... here we use the 'type specialized' fragment &quot;incode&quot;{A&lt;T&gt;} ...
  }
};
</pre>
</div>
<h3><a name="Typemaps_automatic_specialization">13.11.2 Fragments and
 automatic typemap specialization</a></h3>
<p> Since fragments can be type specialized, they can be elegantly used
 to specialize typemaps. For example, if you have something like:</p>
<div class="code">
<pre>
%fragment(&quot;incode&quot;{float}, &quot;header&quot;) {
  float in_method_float(PyObject *obj) {
    ...
  }
}

%fragment(&quot;incode&quot;{long}, &quot;header&quot;) {
  float in_method_long(PyObject *obj) {
    ...
  }
}

// %my_typemaps macro definition
%define %my_typemaps(Type) 
%typemap(in, fragment=&quot;incode&quot;{Type}) Type {
  value = in_method_##Type(obj);
}
%enddef

%my_typemaps(float);
%my_typemaps(long);
</pre>
</div>
<p> then the proper <tt>&quot;incode&quot;{float}</tt> or <tt>&quot;incode&quot;{long}</tt>
 fragment will be used, and the <tt>in_method_float</tt> and <tt>
in_method_long</tt> methods will be called whenever the <tt>float</tt>
 or <tt>long</tt> types are used as input parameters.</p>
<p> This feature is used a lot in the typemaps shipped in the SWIG
 library for some scripting languages. The interested (or very brave)
 reader can take a look at the fragments.swg file shipped with SWIG to
 see this in action.</p>
<h2><a name="Typemaps_runtime_type_checker">13.12 The run-time type
 checker</a></h2>
<p> Most scripting languages need type information at run-time. This
 type information can include how to construct types, how to garbage
 collect types, and the inheritance relationships between types. If the
 language interface does not provide its own type information storage,
 the generated SWIG code needs to provide it.</p>
<p> Requirements for the type system:</p>
<ul>
<li>Store inheritance and type equivalence information and be able to
 correctly re-create the type pointer.</li>
<li>Share type information between modules.</li>
<li>Modules can be loaded in any order, regardless of actual type
 dependency.</li>
<li>Avoid the use of dynamically allocated memory, and library/system
 calls in general.</li>
<li>Provide a reasonably fast implementation, minimizing the lookup time
 for all language modules.</li>
<li>Custom, language specific information can be attached to types.</li>
<li>Modules can be unloaded from the type system.</li>
</ul>
<h3><a name="Typemaps_nn45">13.12.1 Implementation</a></h3>
<p> The run-time type checker is used by many, but not all, of SWIG's
 supported target languages. The run-time type checker features are not
 required and are thus not used for statically typed languages such as
 Java and C#. The scripting and scheme based languages rely on it and it
 forms a critical part of SWIG's operation for these languages.</p>
<p> When pointers, arrays, and objects are wrapped by SWIG, they are
 normally converted into typed pointer objects. For example, an instance
 of <tt>Foo *</tt> might be a string encoded like this:</p>
<div class="diagram">
<pre>
_108e688_p_Foo
</pre>
</div>
<p> At a basic level, the type checker simply restores some type-safety
 to extension modules. However, the type checker is also responsible for
 making sure that wrapped C++ classes are handled correctly---especially
 when inheritance is used. This is especially important when an
 extension module makes use of multiple inheritance. For example:</p>
<div class="code">
<pre>
class Foo {
public:
  int x;
};

class Bar {
public:
  int y;
};

class FooBar : public Foo, public Bar {
public:
  int z;
};
</pre>
</div>
<p> When the class <tt>FooBar</tt> is organized in memory, it contains
 the contents of the classes <tt>Foo</tt> and <tt>Bar</tt> as well as
 its own data members. For example:</p>
<div class="diagram">
<pre>
FooBar --&gt; | -----------|  &lt;-- Foo
           |   int x    |
           |------------|  &lt;-- Bar
           |   int y    |
           |------------|
           |   int z    |
           |------------|
</pre>
</div>
<p> Because of the way that base class data is stacked together, the
 casting of a <tt>Foobar *</tt> to either of the base classes may change
 the actual value of the pointer. This means that it is generally not
 safe to represent pointers using a simple integer or a bare <tt>void *</tt>
---type tags are needed to implement correct handling of pointer values
 (and to make adjustments when needed).</p>
<p> In the wrapper code generated for each language, pointers are
 handled through the use of special type descriptors and conversion
 functions. For example, if you look at the wrapper code for Python, you
 will see code similar to the following (simplified for brevity):</p>
<div class="code">
<pre>
if (!SWIG_IsOK(SWIG_ConvertPtr(obj0, (void **) &amp;arg1, SWIGTYPE_p_Foo, 0))) {
  SWIG_exception_fail(SWIG_TypeError, &quot;in method 'GrabVal', expecting type Foo&quot;);
}
</pre>
</div>
<p> In this code, <tt>SWIGTYPE_p_Foo</tt> is the type descriptor that
 describes <tt>Foo *</tt>. The type descriptor is actually a pointer to
 a structure that contains information about the type name to use in the
 target language, a list of equivalent typenames (via typedef or
 inheritance), and pointer value handling information (if applicable).
 The <tt>SWIG_ConvertPtr()</tt> function is simply a utility function
 that takes a pointer object in the target language and a
 type-descriptor object and uses this information to generate a C++
 pointer. The <tt>SWIG_IsOK</tt> macro checks the return value for
 errors and <tt>SWIG_exception_fail</tt> can be called to raise an
 exception in the target language. However, the exact name and calling
 conventions of the conversion function depends on the target language
 (see language specific chapters for details).</p>
<p> The actual type code is in swigrun.swg, and gets inserted near the
 top of the generated swig wrapper file. The phrase &quot;a type X that can
 cast into a type Y&quot; means that given a type X, it can be converted into
 a type Y. In other words, X is a derived class of Y or X is a typedef
 of Y. The structure to store type information looks like this:</p>
<div class="code">
<pre>
/* Structure to store information on one type */
typedef struct swig_type_info {
  const char *name;             /* mangled name of this type */
  const char *str;              /* human readable name for this type */
  swig_dycast_func dcast;       /* dynamic cast function down a hierarchy */
  struct swig_cast_info *cast;  /* Linked list of types that can cast into this type */
  void *clientdata;             /* Language specific type data */
} swig_type_info;

/* Structure to store a type and conversion function used for casting */
typedef struct swig_cast_info {
  swig_type_info *type;          /* pointer to type that is equivalent to this type */
  swig_converter_func converter; /* function to cast the void pointers */
  struct swig_cast_info *next;   /* pointer to next cast in linked list */
  struct swig_cast_info *prev;   /* pointer to the previous cast */
} swig_cast_info;
</pre>
</div>
<p> Each <tt>swig_type_info</tt> stores a linked list of types that it
 is equivalent to. Each entry in this doubly linked list stores a
 pointer back to another swig_type_info structure, along with a pointer
 to a conversion function. This conversion function is used to solve the
 above problem of the FooBar class, correctly returning a pointer to the
 type we want.</p>
<p> The basic problem we need to solve is verifying and building
 arguments passed to functions. So going back to the <tt>
SWIG_ConvertPtr()</tt> function example from above, we are expecting a <tt>
Foo *</tt> and need to check if <tt>obj0</tt> is in fact a <tt>Foo *</tt>
. From before, <tt>SWIGTYPE_p_Foo</tt> is just a pointer to the <tt>
swig_type_info</tt> structure describing <tt>Foo *</tt>. So we loop
 through the linked list of <tt>swig_cast_info</tt> structures attached
 to <tt>SWIGTYPE_p_Foo</tt>. If we see that the type of <tt>obj0</tt> is
 in the linked list, we pass the object through the associated
 conversion function and then return a positive. If we reach the end of
 the linked list without a match, then <tt>obj0</tt> can not be
 converted to a <tt>Foo *</tt> and an error is generated.</p>
<p> Another issue needing to be addressed is sharing type information
 between multiple modules. More explicitly, we need to have ONE <tt>
swig_type_info</tt> for each type. If two modules both use the type, the
 second module loaded must lookup and use the swig_type_info structure
 from the module already loaded. Because no dynamic memory is used and
 the circular dependencies of the casting information, loading the type
 information is somewhat tricky, and not explained here. A complete
 description is in the <tt>Lib/swiginit.swg</tt> file (and near the top
 of any generated file).</p>
<p> Each module has one swig_module_info structure which looks like
 this:</p>
<div class="code">
<pre>
/* Structure used to store module information
 * Each module generates one structure like this, and the runtime collects
 * all of these structures and stores them in a circularly linked list.*/
typedef struct swig_module_info {
  swig_type_info **types;         /* Array of pointers to swig_type_info structs in this module */
  int size;                       /* Number of types in this module */
  struct swig_module_info *next;  /* Pointer to next element in circularly linked list */
  swig_type_info **type_initial;  /* Array of initially generated type structures */
  swig_cast_info **cast_initial;  /* Array of initially generated casting structures */
  void *clientdata;               /* Language specific module data */
} swig_module_info;
</pre>
</div>
<p> Each module stores an array of pointers to <tt>swig_type_info</tt>
 structures and the number of types in this module. So when a second
 module is loaded, it finds the <tt>swig_module_info</tt> structure for
 the first module and searches the array of types. If any of its own
 types are in the first module and have already been loaded, it uses
 those <tt>swig_type_info</tt> structures rather than creating new ones.
 These <tt>swig_module_info</tt> structures are chained together in a
 circularly linked list.</p>
<h3><a name="Typemaps_runtime_type_checker_usage">13.12.2 Usage</a></h3>
<p>This section covers how to use these functions from typemaps. To
 learn how to call these functions from external files (not the
 generated _wrap.c file), see the <a href="#Modules_external_run_time">
External access to the run-time system</a> section.</p>
<p>When pointers are converted in a typemap, the typemap code often
 looks similar to this:</p>
<div class="code">
<pre>
%typemap(in) Foo * {
  if (!SWIG_IsOK(SWIG_ConvertPtr($input, (void **) &amp;$1, $1_descriptor, 0))) {
    SWIG_exception_fail(SWIG_TypeError, &quot;in method '$symname', expecting type Foo&quot;);
  }
}
</pre>
</div>
<p> The most critical part is the typemap is the use of the <tt>
$1_descriptor</tt> special variable. When placed in a typemap, this is
 expanded into the <tt>SWIGTYPE_*</tt> type descriptor object above. As
 a general rule, you should always use <tt>$1_descriptor</tt> instead of
 trying to hard-code the type descriptor name directly.</p>
<p> There is another reason why you should always use the <tt>
$1_descriptor</tt> variable. When this special variable is expanded,
 SWIG marks the corresponding type as &quot;in use.&quot; When type-tables and
 type information is emitted in the wrapper file, descriptor information
 is only generated for those datatypes that were actually used in the
 interface. This greatly reduces the size of the type tables and
 improves efficiency.</p>
<p> Occasionally, you might need to write a typemap that needs to
 convert pointers of other types. To handle this, the special variable
 macro <tt>$descriptor(type)</tt> covered earlier can be used to
 generate the SWIG type descriptor name for any C datatype. For example:</p>
<div class="code">
<pre>
%typemap(in) Foo * {
  if (!SWIG_IsOK(SWIG_ConvertPtr($input, (void **) &amp;$1, $1_descriptor, 0))) {
    Bar *temp;
    if (!SWIG_IsOK(SWIG_ConvertPtr($input, (void **) &amp;temp, $descriptor(Bar *), 0))) {
      SWIG_exception_fail(SWIG_TypeError, &quot;in method '$symname', expecting type Foo or Bar&quot;);
    }
    $1 = (Foo *)temp;
  }
}
</pre>
</div>
<p> The primary use of <tt>$descriptor(type)</tt> is when writing
 typemaps for container objects and other complex data structures. There
 are some restrictions on the argument---namely it must be a fully
 defined C datatype. It can not be any of the special typemap variables.</p>
<p> In certain cases, SWIG may not generate type-descriptors like you
 expect. For example, if you are converting pointers in some
 non-standard way or working with an unusual combination of interface
 files and modules, you may find that SWIG omits information for a
 specific type descriptor. To fix this, you may need to use the <tt>
%types</tt> directive. For example:</p>
<div class="code">
<pre>
%types(int *, short *, long *, float *, double *);
</pre>
</div>
<p> When <tt>%types</tt> is used, SWIG generates type-descriptor
 information even if those datatypes never appear elsewhere in the
 interface file.</p>
<p> Further details about the run-time type checking can be found in the
 documentation for individual language modules. Reading the source code
 may also help. The file <tt>Lib/swigrun.swg</tt> in the SWIG library
 contains all of the source of the generated code for type-checking.
 This code is also included in every generated wrapped file so you
 probably just look at the output of SWIG to get a better sense for how
 types are managed.</p>
<h2><a name="Typemaps_overloading">13.13 Typemaps and overloading</a></h2>
<p> This section does not apply to the statically typed languages like
 Java and C#, where overloading of the types is handled much like C++ by
 generating overloaded methods in the target language. In many of the
 other target languages, SWIG still fully supports C++ overloaded
 methods and functions. For example, if you have a collection of
 functions like this:</p>
<div class="code">
<pre>
int foo(int x);
int foo(double x);
int foo(char *s, int y);
</pre>
</div>
<p> You can access the functions in a normal way from the scripting
 interpreter:</p>
<div class="targetlang">
<pre>
# Python
foo(3)           # foo(int)
foo(3.5)         # foo(double)
foo(&quot;hello&quot;, 5)  # foo(char *, int)

# Tcl
foo 3            # foo(int)
foo 3.5          # foo(double)
foo hello 5      # foo(char *, int)
</pre>
</div>
<p> To implement overloading, SWIG generates a separate wrapper function
 for each overloaded method. For example, the above functions would
 produce something roughly like this:</p>
<div class="code">
<pre>
// wrapper pseudocode
_wrap_foo_0(argc, args[]) {       // foo(int)
  int arg1;
  int result;
  ...
  arg1 = FromInteger(args[0]);
  result = foo(arg1);
  return ToInteger(result);
}

_wrap_foo_1(argc, args[]) {       // foo(double)
  double arg1;
  int result;
  ...
  arg1 = FromDouble(args[0]);
  result = foo(arg1);
  return ToInteger(result);
}

_wrap_foo_2(argc, args[]) {       // foo(char *, int)
  char *arg1;
  int   arg2;
  int result;
  ...
  arg1 = FromString(args[0]);
  arg2 = FromInteger(args[1]);
  result = foo(arg1, arg2);
  return ToInteger(result);
}

</pre>
</div>
<p> Next, a dynamic dispatch function is generated:</p>
<div class="code">
<pre>
_wrap_foo(argc, args[]) {
  if (argc == 1) {
    if (IsInteger(args[0])) {
      return _wrap_foo_0(argc, args);
    }
    if (IsDouble(args[0])) {
      return _wrap_foo_1(argc, args);
    }
  }
  if (argc == 2) {
    if (IsString(args[0]) &amp;&amp; IsInteger(args[1])) {
      return _wrap_foo_2(argc, args);
    }
  }
  error(&quot;No matching function!\n&quot;);
}
</pre>
</div>
<p> The purpose of the dynamic dispatch function is to select the
 appropriate C++ function based on argument types---a task that must be
 performed at runtime in most of SWIG's target languages.</p>
<p> The generation of the dynamic dispatch function is a relatively
 tricky affair. Not only must input typemaps be taken into account
 (these typemaps can radically change the types of arguments accepted),
 but overloaded methods must also be sorted and checked in a very
 specific order to resolve potential ambiguity. A high-level overview of
 this ranking process is found in the &quot;<a href="#SWIGPlus">SWIG and C++</a>
&quot; chapter. What isn't mentioned in that chapter is the mechanism by
 which it is implemented---as a collection of typemaps.</p>
<p> To support dynamic dispatch, SWIG first defines a general purpose
 type hierarchy as follows:</p>
<div class="diagram">
<pre>
Symbolic Name                   Precedence Value
------------------------------  ------------------
SWIG_TYPECHECK_POINTER           0
SWIG_TYPECHECK_ITERATOR          5
SWIG_TYPECHECK_VOIDPTR           10
SWIG_TYPECHECK_BOOL              15
SWIG_TYPECHECK_UINT8             20
SWIG_TYPECHECK_INT8              25
SWIG_TYPECHECK_UINT16            30
SWIG_TYPECHECK_INT16             35
SWIG_TYPECHECK_UINT32            40
SWIG_TYPECHECK_INT32             45
SWIG_TYPECHECK_SIZE              47
SWIG_TYPECHECK_PTRDIFF           48
SWIG_TYPECHECK_UINT64            50
SWIG_TYPECHECK_INT64             55
SWIG_TYPECHECK_UINT128           60
SWIG_TYPECHECK_INT128            65
SWIG_TYPECHECK_INTEGER           70
SWIG_TYPECHECK_FLOAT             80
SWIG_TYPECHECK_DOUBLE            90
SWIG_TYPECHECK_CPLXFLT           95
SWIG_TYPECHECK_CPLXDBL           100
SWIG_TYPECHECK_COMPLEX           105
SWIG_TYPECHECK_UNICHAR           110
SWIG_TYPECHECK_STDUNISTRING      115
SWIG_TYPECHECK_UNISTRING         120
SWIG_TYPECHECK_CHAR              130
SWIG_TYPECHECK_STDSTRING         135
SWIG_TYPECHECK_STRING            140
SWIG_TYPECHECK_PAIR              150
SWIG_TYPECHECK_STDARRAY          155
SWIG_TYPECHECK_VECTOR            160
SWIG_TYPECHECK_DEQUE             170
SWIG_TYPECHECK_LIST              180
SWIG_TYPECHECK_SET               190
SWIG_TYPECHECK_MULTISET          200
SWIG_TYPECHECK_MAP               210
SWIG_TYPECHECK_MULTIMAP          220
SWIG_TYPECHECK_STACK             230
SWIG_TYPECHECK_QUEUE             240
SWIG_TYPECHECK_BOOL_ARRAY        1015
SWIG_TYPECHECK_INT8_ARRAY        1025
SWIG_TYPECHECK_INT16_ARRAY       1035
SWIG_TYPECHECK_INT32_ARRAY       1045
SWIG_TYPECHECK_INT64_ARRAY       1055
SWIG_TYPECHECK_INT128_ARRAY      1065
SWIG_TYPECHECK_FLOAT_ARRAY       1080
SWIG_TYPECHECK_DOUBLE_ARRAY      1090
SWIG_TYPECHECK_CHAR_ARRAY        1130
SWIG_TYPECHECK_STRING_ARRAY      1140
SWIG_TYPECHECK_OBJECT_ARRAY      1150
SWIG_TYPECHECK_BOOL_PTR          2015
SWIG_TYPECHECK_UINT8_PTR         2020
SWIG_TYPECHECK_INT8_PTR          2025
SWIG_TYPECHECK_UINT16_PTR        2030
SWIG_TYPECHECK_INT16_PTR         2035
SWIG_TYPECHECK_UINT32_PTR        2040
SWIG_TYPECHECK_INT32_PTR         2045
SWIG_TYPECHECK_UINT64_PTR        2050
SWIG_TYPECHECK_INT64_PTR         2055
SWIG_TYPECHECK_FLOAT_PTR         2080
SWIG_TYPECHECK_DOUBLE_PTR        2090
SWIG_TYPECHECK_CHAR_PTR          2130
SWIG_TYPECHECK_SWIGOBJECT        5000
</pre>
</div>
<p> (These precedence levels are defined in <tt>swig.swg</tt>, a library
 file that's included by all target language modules.)</p>
<p> In this table, the precedence-level determines the order in which
 types are going to be checked. Low values are always checked before
 higher values. For example, integers are checked before floats, single
 values are checked before arrays, and so forth.</p>
<p> Using the above table as a guide, each target language defines a
 collection of &quot;typecheck&quot; typemaps. The following excerpt from the
 Python module illustrates this:</p>
<div class="code">
<pre>
/* Python type checking rules */
/* Note:  %typecheck(X) is a macro for %typemap(typecheck, precedence=X) */

%typecheck(SWIG_TYPECHECK_INTEGER)
  int, short, long,
  unsigned int, unsigned short, unsigned long,
  signed char, unsigned char,
  long long, unsigned long long,
  const int &amp;, const short &amp;, const long &amp;,
  const unsigned int &amp;, const unsigned short &amp;, const unsigned long &amp;,
  const long long &amp;, const unsigned long long &amp;,
  enum SWIGTYPE,
  bool, const bool &amp;
{
  $1 = (PyInt_Check($input) || PyLong_Check($input)) ? 1 : 0;
}

%typecheck(SWIG_TYPECHECK_DOUBLE)
  float, double,
  const float &amp;, const double &amp;
{
  $1 = (PyFloat_Check($input) || PyInt_Check($input) || PyLong_Check($input)) ? 1 : 0;
}

%typecheck(SWIG_TYPECHECK_CHAR) char {
  $1 = (PyString_Check($input) &amp;&amp; (PyString_Size($input) == 1)) ? 1 : 0;
}

%typecheck(SWIG_TYPECHECK_STRING) char * {
  $1 = PyString_Check($input) ? 1 : 0;
}

%typemap(typecheck, precedence=SWIG_TYPECHECK_POINTER, noblock=1) SWIGTYPE * {
  void *vptr = 0;
  int res = SWIG_ConvertPtr($input, &amp;vptr, $1_descriptor, 0);
  $1 = SWIG_IsOK(res) ? 1 : 0;
}

%typecheck(SWIG_TYPECHECK_POINTER) PyObject * {
  $1 = ($input != 0);
}
</pre>
</div>
<p> It might take a bit of contemplation, but this code has merely
 organized all of the basic C++ types, provided some simple
 type-checking code, and assigned each type a precedence value.</p>
<p> Finally, to generate the dynamic dispatch function, SWIG uses the
 following algorithm:</p>
<ul>
<li>Overloaded methods are first sorted by the number of required
 arguments.</li>
<li>Methods with the same number of arguments are then sorted by
 precedence values of argument types.</li>
<li>Typecheck typemaps are then emitted to produce a dispatch function
 that checks arguments in the correct order.</li>
</ul>
<p> If you haven't written any typemaps of your own, it is unnecessary
 to worry about the typechecking rules. However, if you have written new
 input typemaps, you might have to supply a typechecking rule as well.
 An easy way to do this is to simply copy one of the existing
 typechecking rules. Here is an example,</p>
<div class="code">
<pre>
// Typemap for a C++ string
%typemap(in) std::string {
  if (PyString_Check($input)) {
    $1 = std::string(PyString_AsString($input));
  } else {
    SWIG_exception(SWIG_TypeError, &quot;string expected&quot;);
  }
}
// Copy the typecheck code for &quot;char *&quot;.  
%typemap(typecheck) std::string = char *;
</pre>
</div>
<p> The bottom line: If you are writing new typemaps and you are using
 overloaded methods, you will probably have to write new typecheck code
 or copy and modify existing typecheck code.</p>
<p> If you write a typecheck typemap and omit the precedence level, for
 example commenting it out as shown below:</p>
<div class="code">
<pre>
%typemap(typecheck /*, precedence=SWIG_TYPECHECK_INTEGER*/) int {
  $1 = PyInt_Check($input) ? 1 : 0;
}
</pre>
</div>
<p> then the type is given a precedence higher than any other known
 precedence level and a <a href="#Warnings">warning</a> is issued:</p>
<div class="shell">
<pre>
example.i:18: Warning 467: Overloaded method foo(int) not supported (incomplete type
checking rule - no precedence level in typecheck typemap for 'int').
</pre>
</div>
<p><b> Notes:</b></p>
<ul>
<li>Typecheck typemaps are not used for non-overloaded methods. Because
 of this, it is still always necessary to check types in any &quot;in&quot;
 typemaps.</li>
<li>The dynamic dispatch process is only meant to be a heuristic. There
 are many corner cases where SWIG simply can't disambiguate types to the
 same degree as C++. The only way to resolve this ambiguity is to use
 the %rename directive to rename one of the overloaded methods
 (effectively eliminating overloading).</li>
<li> Typechecking may be partial. For example, if working with arrays,
 the typecheck code might simply check the type of the first array
 element and use that to dispatch to the correct function. Subsequent
 &quot;in&quot; typemaps would then perform more extensive type-checking.</li>
<li>Make sure you read the section on <a href="#SWIGPlus_overloaded_methods">
overloading</a> in the SWIG and C++ chapter.</li>
</ul>
<h3><a name="Typemaps_typecheck_pointer">13.13.1 SWIG_TYPECHECK_POINTER
 precedence level and the typecheck typemap</a></h3>
<p> When it comes to overloading of a particular type passed by value,
 pointer or reference (const and non-const), a C++ compiler can
 disambiguate which overloaded function to call. However, SWIG
 effectively treats these as pointers in the target language and thus as
 equivalent types. For example, consider:</p>
<div class="code">
<pre>
class X { ... };
void m(X const &amp;c); // equivalent: void m(X *c);
void m(X &amp;r);       // equivalent: void m(X *r);
void m(X *p);       // equivalent: void m(X *p);
</pre>
</div>
<p> These cannot be disambiguated in the target languages and so SWIG
 will choose the first method and ignore the subsequent two methods. The
 scripting languages do this by using the overload dispatch mechanism
 described earlier and warnings indicate this:</p>
<div class="shell">
<pre>
example.i:6: Warning 509: Overloaded method m(X &amp;) effectively ignored,
example.i:5: Warning 509: as it is shadowed by m(X const &amp;).
example.i:7: Warning 509: Overloaded method m(X *) effectively ignored,
example.i:5: Warning 509: as it is shadowed by m(X const &amp;).
</pre>
</div>
<p> The statically typed languages like Java and C# automatically ignore
 all but the first equivalent overloaded methods with warnings:</p>
<div class="shell">
<pre>
example.i:6: Warning 516: Overloaded method m(X &amp;) ignored,
example.i:5: Warning 516: using m(X const &amp;) instead.
example.i:7: Warning 516: Overloaded method m(X *) ignored,
example.i:5: Warning 516: using m(X const &amp;) instead.
</pre>
</div>
<p> You can select the overloaded method you would like to wrap by
 ignoring the other two with <tt>%ignore</tt> or rename two of them with
 <tt>%rename</tt> and this will of course remove the warnings too. The
 problem of ambiguity is also discussed in the C++ chapter on <a href="#SWIGPlus_overloaded_methods">
overloading</a>.</p>
<p> So how does this work with respect to typemaps? The typemaps SWIG
 provides to handle overloading for these three methods are from the
 SWIGTYPE family. As discussed earlier, in <a href="#Typemaps_nn19">
Default typemap matching rules</a>, the <tt>SWIGTYPE &amp;</tt> typemaps are
 used for references and <tt>SWIGTYPE *</tt> typemaps are used for
 pointers. SWIG uses the special <tt>SWIG_TYPECHECK_POINTER</tt> (0)
 precedence level to handle these types in the &quot;typecheck&quot; typemap:</p>
<div class="code">
<pre>
%typemap(typecheck, precedence=SWIG_TYPECHECK_POINTER) SWIGTYPE &amp; &quot;...&quot;
%typemap(typecheck, precedence=SWIG_TYPECHECK_POINTER) SWIGTYPE * &quot;...&quot;
</pre>
</div>
<p> When the SWIGTYPE &quot;typecheck&quot; typemaps use the <tt>
SWIG_TYPECHECK_POINTER</tt> precedence level, SWIG converts the type to
 a pointer equivalent type and then uses the equivalent type to detect
 if it can be disambiguated in an overloaded method in the target
 language. In our example above, the equivalent types for <tt>X const &amp;</tt>
, <tt>X &amp;</tt> and <tt>X *</tt> are all <tt>X *</tt>. As they are the
 same, they cannot be disambiguated and so just the first overloaded
 method is chosen.</p>
<p> The automatic conversion to equivalent types and subsequent type
 comparison is triggered via the use of the special <tt>
SWIG_TYPECHECK_POINTER</tt> precedence level and works for types passed
 by value, pointer and reference. Alas, there are more ways to overload
 a method that also need handling. C++ smart pointers are such a type
 which can be disambiguated by a C++ compiler but not automatically by
 SWIG. SWIG does not automatically know that a smart pointer has an
 equivalent type, but it can be told manually. Just specify the
 'equivalent' attribute in the &quot;typecheck&quot; typemap with a pointer to the
 underlying type.</p>
<div class="code">
<pre>
%typemap(typecheck, precedence=SWIG_TYPECHECK_POINTER, equivalent=&quot;X *&quot;) MySmartPtr&lt;X&gt; &quot; ... &quot;

void m(X &amp;r);            // equivalent: void m(X *r);
void m(MySmartPtr&lt;X&gt; s); // equivalent: void m(X *s);
</pre>
</div>
<p> Now SWIG will detect the two types are equivalent and generate valid
 code by wrapping just the first overloaded method. You can of course
 choose which method to wrap by ignoring one of them with <tt>%ignore</tt>
. Otherwise both can be wrapped by removing the overloading name
 ambiguity by renaming one of them with <tt>%rename</tt>.</p>
<p> The 'equivalent' attribute is used in the implementation for the <a href="#Library_std_shared_ptr">
shared_ptr smart pointer</a> library.</p>
<h2><a name="Typemaps_nn48">13.14 More about %apply and %clear</a></h2>
<p> In order to implement certain kinds of program behavior, it is
 sometimes necessary to write a family of typemap methods. For example,
 to support output arguments, one often writes a family of typemaps like
 this:</p>
<div class="code">
<pre>
%typemap(in, numinputs=0) int *OUTPUT (int temp) {
  $1 = &amp;temp;
}
%typemap(argout) int *OUTPUT {
  // return value somehow
}
</pre>
</div>
<p> To make it easier to apply the typemap to different argument types
 and names, the <tt>%apply</tt> directive performs a copy of all
 typemaps from a source type to one or more set of target types. For
 example, if you specify this,</p>
<div class="code">
<pre>
%apply int *OUTPUT { int *retvalue, int32 *output };
</pre>
</div>
<p> then all of the <tt>int *OUTPUT</tt> (source) typemap methods are
 copied to <tt>int *retvalue</tt> and <tt>int32 *output</tt> (the
 targets).</p>
<p> However, there is a subtle aspect of <tt>%apply</tt> that needs
 clarification. Namely, if a target contains a typemap method that the
 source does not, the target typemap method remains in place and
 unchanged. This behavior allows you to do two things:</p>
<ul>
<li>You can specialize parts of a complex typemap rule by first defining
 a few typemaps and then using <tt>%apply</tt> to incorporate the
 remaining pieces.</li>
<li>Different typemaps can be applied to the same datatype using
 repeated <tt>%apply</tt> directives.</li>
</ul>
<p> For example:</p>
<div class="code">
<pre>
%typemap(in) int *INPUT (int temp) {
  temp = ... get value from $input ...;
  $1 = &amp;temp;
}

%typemap(check) int *POSITIVE {
  if (*$1 &lt;= 0) {
    SWIG_exception(SWIG_ValueError, &quot;Expected a positive number!\n&quot;);
    return NULL;
  }
}

%typemap(arginit) int *invalue %{
  $1 = NULL;
%}

...
%apply int *INPUT     { int *invalue };
%apply int *POSITIVE  { int *invalue };
</pre>
</div>
<p> In this example, neither of the two <tt>%apply</tt> directives will
 overwrite / delete the &quot;arginit&quot; typemap as neither has an &quot;arginit&quot;
 typemap. The result is a family of three relevant typemaps for <tt>int
 *invalue</tt>. Since <tt>%apply</tt> does not overwrite / delete any
 existing rules, the only way to reset behavior is to delete them, such
 as with the <tt>%clear</tt> directive. For example:</p>
<div class="code">
<pre>
%clear int *invalue;
</pre>
</div>
<p> will delete the typemaps for all the typemap methods; namely &quot;in&quot;,
 &quot;check&quot; and &quot;arginit&quot;. Alternatively delete each one individually:</p>
<div class="code">
<pre>
%typemap(in) int *invalue;
%typemap(check) int *invalue;
%typemap(arginit) int *invalue;
</pre>
</div>
<h2><a name="Typemaps_nn47">13.15 Passing data between typemaps</a></h2>
<p> It is also important to note that the primary use of local variables
 is to create stack-allocated objects for temporary use inside a wrapper
 function (this is faster and less-prone to error than allocating data
 on the heap). In general, the variables are not intended to pass
 information between different types of typemaps. However, this can be
 done if you realize that local names have the argument number appended
 to them. For example, you could do this:</p>
<div class="code">
<pre>
%typemap(in) int *(int temp) {
  temp = (int) PyInt_AsLong($input);
  $1 = &amp;temp;
}

%typemap(argout) int * {
  PyObject *o = PyInt_FromLong(temp$argnum);
  ...
}
</pre>
</div>
<p> In this case, the <tt>$argnum</tt> variable is expanded into the
 argument number. Therefore, the code will reference the appropriate
 local such as <tt>temp1</tt> and <tt>temp2</tt>. It should be noted
 that there are plenty of opportunities to break the universe here and
 that accessing locals in this manner should probably be avoided. At the
 very least, you should make sure that the typemaps sharing information
 have exactly the same types and names.</p>
<h2><a name="Typemaps_nn52">13.16 C++ &quot;this&quot; pointer</a></h2>
<p> All the rules discussed for typemaps apply to C++ as well as C.
 However in addition C++ passes an extra parameter into every non-static
 class method -- the <tt>this</tt> pointer. Occasionally it can be
 useful to apply a typemap to this pointer (for example to check and
 make sure <tt>this</tt> is non-null before deferencing). Actually, C
 also has an the equivalent of the <tt>this</tt> pointer which is used
 when accessing variables in a C struct.</p>
<p> In order to customise the <tt>this</tt> pointer handling, target a
 variable named <tt>self</tt> in your typemaps. <tt>self</tt> is the
 name SWIG uses to refer to the extra parameter in wrapped functions.</p>
<p> For example, if wrapping for Java generation:</p>
<div class="code">
<pre>
%typemap(check) SWIGTYPE *self %{
if (!$1) {
  SWIG_JavaThrowException(jenv, SWIG_JavaNullPointerException,
    &quot;invalid native object; delete() likely already called&quot;);
  return $null;
}
%}
</pre>
</div>
<p> In the above case, the <tt>$1</tt> variable is expanded into the
 argument name that SWIG is using as the <tt>this</tt> pointer. SWIG
 will then insert the check code before the actual C++ class method is
 called, and will raise an exception rather than crash the Java virtual
 machine. The generated code will look something like:</p>
<div class="code">
<pre>
  if (!arg1) {
    SWIG_JavaThrowException(jenv, SWIG_JavaNullPointerException,
      &quot;invalid native object; delete() likely already called&quot;);
    return ;
  }
  (arg1)-&gt;wrappedFunction(...);
</pre>
</div>
<p> Note that if you have a parameter named <tt>self</tt> then it will
 also match the typemap. One work around is to create an interface file
 that wraps the method, but gives the argument a name other than <tt>
self</tt>.</p>
<h2><a name="Typemaps_nn51">13.17 Where to go for more information?</a></h2>
<p> The best place to find out more information about writing typemaps
 is to look in the SWIG library. Most language modules define all of
 their default behavior using typemaps. These are found in files such as
 <tt>python.swg</tt>, <tt>perl5.swg</tt>, <tt>tcl8.swg</tt> and so
 forth. The <tt>typemaps.i</tt> file in the library also contains
 numerous examples. You should look at these files to get a feel for how
 to define typemaps of your own. Some of the language modules support
 additional typemaps and further information is available in the
 individual chapters for each target language. There you may also find
 more hands-on practical examples.</p>
<HR NOSHADE>
<h1><a name="Customization">14 Customization Features</a></h1>

<!-- INDEX -->
<div class="sectiontoc">
<ul>
<li><a href="#Customization_exception">Exception handling with
 %exception</a>
<ul>
<li><a href="#Customization_nn3">Handling exceptions in C code</a></li>
<li><a href="#Customization_nn4">Exception handling with longjmp()</a></li>
<li><a href="#Customization_nn5">Handling C++ exceptions</a></li>
<li><a href="#Customization_allowexcept">Exception handlers for
 variables</a></li>
<li><a href="#Customization_nn6">Defining different exception handlers</a>
</li>
<li><a href="#Customization_exception_special_variables">Special
 variables for %exception</a></li>
<li><a href="#Customization_nn7">Using The SWIG exception library</a></li>
</ul>
</li>
<li><a href="#Customization_ownership">Object ownership and %newobject</a>
</li>
<li><a href="#Customization_features">Features and the %feature
 directive</a>
<ul>
<li><a href="#Customization_feature_attributes">Feature attributes</a></li>
<li><a href="#Customization_feature_flags">Feature flags</a></li>
<li><a href="#Customization_clearing_features">Clearing features</a></li>
<li><a href="#Customization_features_default_args">Features and default
 arguments</a></li>
<li><a href="#Customization_features_example">Feature example</a></li>
</ul>
</li>
</ul>
</div>
<!-- INDEX -->
<p> In many cases, it is desirable to change the default wrapping of
 particular declarations in an interface. For example, you might want to
 provide hooks for catching C++ exceptions, add assertions, or provide
 hints to the underlying code generator. This chapter describes some of
 these customization techniques. First, a discussion of exception
 handling is presented. Then, a more general-purpose customization
 mechanism known as &quot;features&quot; is described.</p>
<h2><a name="Customization_exception">14.1 Exception handling with
 %exception</a></h2>
<p> The <tt>%exception</tt> directive allows you to define a general
 purpose exception handler. For example, you can specify the following:</p>
<div class="code">
<pre>
%exception {
  try {
    $action
  }
  catch (RangeError) {
    ... handle error ...
  }
}
</pre>
</div>
<p> How the exception is handled depends on the target language, for
 example, Python:</p>
<div class="code">
<pre>
%exception {
  try {
    $action
  }
  catch (RangeError) {
    PyErr_SetString(PyExc_IndexError, &quot;index out-of-bounds&quot;);
    SWIG_fail;
  }
}
</pre>
</div>
<p> When defined, the code enclosed in braces is inserted directly into
 the low-level wrapper functions. The special variable <tt>$action</tt>
 is one of a few <a href="#Customization_exception_special_variables">
%exception special variables</a> supported and gets replaced with the
 actual operation to be performed (a function call, method invocation,
 attribute access, etc.). An exception handler remains in effect until
 it is explicitly deleted. This is done by using either <tt>%exception</tt>
 or <tt>%noexception</tt> with no code. For example:</p>
<div class="code">
<pre>
%exception;   // Deletes any previously defined handler
</pre>
</div>
<p><b> Compatibility note:</b> Previous versions of SWIG used a special
 directive <tt>%except</tt> for exception handling. That directive is
 deprecated--<tt>%exception</tt> provides the same functionality, but is
 substantially more flexible.</p>
<h3><a name="Customization_nn3">14.1.1 Handling exceptions in C code</a></h3>
<p> C has no formal exception handling mechanism so there are several
 approaches that might be used. A somewhat common technique is to simply
 set a special error code. For example:</p>
<div class="code">
<pre>
/* File : except.c */

static char error_message[256];
static int error_status = 0;

void throw_exception(char *msg) {
  strncpy(error_message, msg, 256);
  error_status = 1;
}

void clear_exception() {
  error_status = 0;
}
char *check_exception() {
  if (error_status)
    return error_message;
  else
    return NULL;
}

</pre>
</div>
<p> To use these functions, functions simply call <tt>throw_exception()</tt>
 to indicate an error occurred. For example :</p>
<div class="code">
<pre>
double inv(double x) {
  if (x != 0)
    return 1.0/x;
  else {
    throw_exception(&quot;Division by zero&quot;);
    return 0;
  }
}
</pre>
</div>
<p> To catch the exception, you can write a simple exception handler
 such as the following (shown for Perl5) :</p>
<div class="code">
<pre>
%exception {
  char *err;
  clear_exception();
  $action
  if ((err = check_exception())) {
    croak(err);
  }
}
</pre>
</div>
<p> In this case, when an error occurs, it is translated into a Perl
 error. Each target language has its own approach to creating a runtime
 error/exception in and for Perl it is the <tt>croak</tt> method shown
 above.</p>
<h3><a name="Customization_nn4">14.1.2 Exception handling with longjmp()</a>
</h3>
<p> Exception handling can also be added to C code using the <tt>
&lt;setjmp.h&gt;</tt> library. Here is a minimalistic implementation that
 relies on the C preprocessor :</p>
<div class="code">
<pre>
/* File : except.c
   Just the declaration of a few global variables we're going to use */

#include &lt;setjmp.h&gt;
jmp_buf exception_buffer;
int exception_status;

/* File : except.h */
#include &lt;setjmp.h&gt;
extern jmp_buf exception_buffer;
extern int exception_status;

#define try if ((exception_status = setjmp(exception_buffer)) == 0)
#define catch(val) else if (exception_status == val)
#define throw(val) longjmp(exception_buffer, val)
#define finally else

/* Exception codes */

#define RangeError     1
#define DivisionByZero 2
#define OutOfMemory    3

</pre>
</div>
<p> Now, within a C program, you can do the following :</p>
<div class="code">
<pre>
double inv(double x) {
  if (x)
    return 1.0/x;
  else
    throw(DivisionByZero);
}

</pre>
</div>
<p> Finally, to create a SWIG exception handler, write the following :</p>
<div class="code">
<pre>
%{
#include &quot;except.h&quot;
%}

%exception {
  try {
    $action
  } catch(RangeError) {
    croak(&quot;Range Error&quot;);
  } catch(DivisionByZero) {
    croak(&quot;Division by zero&quot;);
  } catch(OutOfMemory) {
    croak(&quot;Out of memory&quot;);
  } finally {
    croak(&quot;Unknown exception&quot;);
  }
}
</pre>
</div>
<p> Note: This implementation is only intended to illustrate the general
 idea. To make it work better, you'll need to modify it to handle nested
 <tt>try</tt> declarations.</p>
<h3><a name="Customization_nn5">14.1.3 Handling C++ exceptions</a></h3>
<p> Handling C++ exceptions is also straightforward. For example:</p>
<div class="code">
<pre>
%exception {
  try {
    $action
  } catch(RangeError) {
    croak(&quot;Range Error&quot;);
  } catch(DivisionByZero) {
    croak(&quot;Division by zero&quot;);
  } catch(OutOfMemory) {
    croak(&quot;Out of memory&quot;);
  } catch(...) {
    croak(&quot;Unknown exception&quot;);
  }
}

</pre>
</div>
<p> The exception types need to be declared as classes elsewhere,
 possibly in a header file :</p>
<div class="code">
<pre>
class RangeError {};
class DivisionByZero {};
class OutOfMemory {};
</pre>
</div>
<h3><a name="Customization_allowexcept">14.1.4 Exception handlers for
 variables</a></h3>
<p> By default all variables will ignore <tt>%exception</tt>, so it is
 effectively turned off for all variables wrappers. This applies to
 global variables, member variables and static member variables. The
 approach is certainly a logical one when wrapping variables in C.
 However, in C++, it is quite possible for an exception to be thrown
 while the variable is being assigned. To ensure <tt>%exception</tt> is
 used when wrapping variables, it needs to be 'turned on' using the <tt>
%allowexception</tt> feature. Note that <tt>%allowexception</tt> is just
 a macro for <tt>%feature(&quot;allowexcept&quot;)</tt>, that is, it is a feature
 called &quot;allowexcept&quot;. Any variable which has this feature attached to
 it, will then use the <tt>%exception</tt> feature, but of course, only
 if there is a <tt>%exception</tt> attached to the variable in the first
 place. The <tt>%allowexception</tt> feature works like any other
 feature and so can be used globally or for selective variables.</p>
<div class="code">
<pre>
%allowexception;                // turn on globally
%allowexception Klass::MyVar;   // turn on for a specific variable

%noallowexception Klass::MyVar; // turn off for a specific variable
%noallowexception;              // turn off globally
</pre>
</div>
<h3><a name="Customization_nn6">14.1.5 Defining different exception
 handlers</a></h3>
<p> By default, the <tt>%exception</tt> directive creates an exception
 handler that is used for all wrapper functions that follow it. Unless
 there is a well-defined (and simple) error handling mechanism in place,
 defining one universal exception handler may be unwieldy and result in
 excessive code bloat since the handler is inlined into each wrapper
 function.</p>
<p> To fix this, you can be more selective about how you use the <tt>
%exception</tt> directive. One approach is to only place it around
 critical pieces of code. For example:</p>
<div class="code">
<pre>
%exception {
  ... your exception handler ...
}
/* Define critical operations that can throw exceptions here */

%exception;

/* Define non-critical operations that don't throw exceptions */
</pre>
</div>
<p> More precise control over exception handling can be obtained by
 attaching an exception handler to specific declaration name. For
 example:</p>
<div class="code">
<pre>
%exception allocate {
  try {
    $action
  }
  catch (MemoryError) {
    croak(&quot;Out of memory&quot;);
  }
}
</pre>
</div>
<p> In this case, the exception handler is only attached to declarations
 named &quot;allocate&quot;. This would include both global and member functions.
 The names supplied to <tt>%exception</tt> follow the same rules as for <tt>
%rename</tt> described in the section on <a href="#SWIGPlus_ambiguity_resolution_renaming">
Renaming and ambiguity resolution</a>. For example, if you wanted to
 define an exception handler for a specific class, you might write this:</p>
<div class="code">
<pre>
%exception Object::allocate {
  try {
    $action
  }
  catch (MemoryError) {
    croak(&quot;Out of memory&quot;);
  }
}
</pre>
</div>
<p> When a class prefix is supplied, the exception handler is applied to
 the corresponding declaration in the specified class as well as for
 identically named functions appearing in derived classes.</p>
<p> <tt>%exception</tt> can even be used to pinpoint a precise
 declaration when overloading is used. For example:</p>
<div class="code">
<pre>
%exception Object::allocate(int) {
  try {
    $action
  }
  catch (MemoryError) {
    croak(&quot;Out of memory&quot;);
  }
}
</pre>
</div>
<p> Attaching exceptions to specific declarations is a good way to
 reduce code bloat. It can also be a useful way to attach exceptions to
 specific parts of a header file. For example:</p>
<div class="code">
<pre>
%module example
%{
#include &quot;someheader.h&quot;
%}

// Define a few exception handlers for specific declarations
%exception Object::allocate(int) {
  try {
    $action
  }
  catch (MemoryError) {
    croak(&quot;Out of memory&quot;);
  }
}

%exception Object::getitem {
  try {
    $action
  }
  catch (RangeError) {
    croak(&quot;Index out of range&quot;);
  }
}
...
// Read a raw header file
%include &quot;someheader.h&quot;
</pre>
</div>
<p><b> Compatibility note:</b> The <tt>%exception</tt> directive
 replaces the functionality provided by the deprecated &quot;except&quot; typemap.
 The typemap would allow exceptions to be thrown in the target language
 based on the return type of a function and was intended to be a
 mechanism for pinpointing specific declarations. However, it never
 really worked that well and the new %exception directive is much
 better.</p>
<h3><a name="Customization_exception_special_variables">14.1.6 Special
 variables for %exception</a></h3>
<p> The %exception directive supports a few special variables which are
 placeholders for code substitution. The following table shows the
 available special variables and details what the special variables are
 replaced with.</p>
<table summary="Special variables for %exception">
<tr><td>$action</td><td>The actual operation to be performed (a function
 call, method invocation, variable access, etc.)</td></tr>
<tr><td>$name</td><td>The C/C++ symbol name for the function.</td></tr>
<tr><td>$symname</td><td>The symbol name used internally by SWIG</td></tr>
<tr><td>$overname</td><td>The extra mangling used in the symbol name for
 overloaded method. Expands to nothing if the wrapped method is not
 overloaded.</td></tr>
<tr><td>$wrapname</td><td>The language specific wrapper name (usually a
 C function name exported from the shared object/dll)</td></tr>
<tr><td>$decl</td><td>The fully qualified C/C++ declaration of the
 method being wrapped without the return type</td></tr>
<tr><td>$fulldecl</td><td>The fully qualified C/C++ declaration of the
 method being wrapped including the return type</td></tr>
<tr><td>$parentclassname</td><td>The parent class name (if any) for a
 method.</td></tr>
<tr><td>$parentclasssymname</td><td>The target language parent class
 name (if any) for a method.</td></tr>
</table>
<p> The special variables are often used in situations where method
 calls are logged. Exactly which form of the method call needs logging
 is up to individual requirements, but the example code below shows all
 the possible expansions, plus how an exception message could be
 tailored to show the C++ method declaration:</p>
<div class="code">
<pre>
%exception Special::something {
  log(&quot;symname: $symname&quot;);
  log(&quot;overname: $overname&quot;);
  log(&quot;wrapname: $wrapname&quot;);
  log(&quot;decl: $decl&quot;);
  log(&quot;fulldecl: $fulldecl&quot;);
  try {
    $action
  } 
  catch (MemoryError) {
    croak(&quot;Out of memory in $decl&quot;);
  }
}
void log(const char *message);
struct Special {
  void something(const char *c);
  void something(int i);
};
</pre>
</div>
<p> Below shows the expansions for the 1st of the overloaded <tt>
something</tt> wrapper methods for Perl:</p>
<div class="code">
<pre>
  log(&quot;symname: Special_something&quot;);
  log(&quot;overname: __SWIG_0&quot;);
  log(&quot;wrapname: _wrap_Special_something__SWIG_0&quot;);
  log(&quot;decl: Special::something(char const *)&quot;);
  log(&quot;fulldecl: void Special::something(char const *)&quot;);
  try {
    (arg1)-&gt;something((char const *)arg2);
  } 
  catch (MemoryError) {
    croak(&quot;Out of memory in Special::something(char const *)&quot;);
  }
</pre>
</div>
<h3><a name="Customization_nn7">14.1.7 Using The SWIG exception library</a>
</h3>
<p> The <tt>exception.i</tt> library file provides support for creating
 language independent exceptions in your interfaces. To use it, simply
 put an &quot;<tt>%include exception.i</tt>&quot; in your interface file. This
 provides a function <tt>SWIG_exception()</tt> that can be used to raise
 common scripting language exceptions in a portable manner. For example
 :</p>
<div class="code">
<pre>
// Language independent exception handler
%include exception.i       

%exception {
  try {
    $action
  } catch(RangeError) {
    SWIG_exception(SWIG_ValueError, &quot;Range Error&quot;);
  } catch(DivisionByZero) {
    SWIG_exception(SWIG_DivisionByZero, &quot;Division by zero&quot;);
  } catch(OutOfMemory) {
    SWIG_exception(SWIG_MemoryError, &quot;Out of memory&quot;);
  } catch(...) {
    SWIG_exception(SWIG_RuntimeError, &quot;Unknown exception&quot;);
  }
}

</pre>
</div>
<p> As arguments, <tt>SWIG_exception()</tt> takes an error type code (an
 integer) and an error message string. The currently supported error
 types are :</p>
<div class="diagram">
<pre>
SWIG_UnknownError
SWIG_IOError
SWIG_RuntimeError
SWIG_IndexError
SWIG_TypeError
SWIG_DivisionByZero
SWIG_OverflowError
SWIG_SyntaxError
SWIG_ValueError
SWIG_SystemError
SWIG_AttributeError
SWIG_MemoryError
SWIG_NullReferenceError
</pre>
</div>
<p> The <tt>SWIG_exception()</tt> function can also be used in typemaps.</p>
<h2><a name="Customization_ownership">14.2 Object ownership and
 %newobject</a></h2>
<p> A common problem in some applications is managing proper ownership
 of objects. For example, consider a function like this:</p>
<div class="code">
<pre>
Foo *blah() {
  Foo *f = new Foo();
  return f;
}
</pre>
</div>
<p> If you wrap the function <tt>blah()</tt>, SWIG has no idea that the
 return value is a newly allocated object. As a result, the resulting
 extension module may produce a memory leak (SWIG is conservative and
 will never delete objects unless it knows for certain that the returned
 object was newly created).</p>
<p> To fix this, you can provide an extra hint to the code generator
 using the <tt>%newobject</tt> directive. For example:</p>
<div class="code">
<pre>
%newobject blah;
Foo *blah();
</pre>
</div>
<p> <tt>%newobject</tt> works exactly like <tt>%rename</tt> and <tt>
%exception</tt>. In other words, you can attach it to class members and
 parameterized declarations as before. For example:</p>
<div class="code">
<pre>
%newobject ::blah();                   // Only applies to global blah
%newobject Object::blah(int, double);  // Only blah(int, double) in Object
%newobject *::copy;                    // Copy method in all classes
...
</pre>
</div>
<p> When <tt>%newobject</tt> is supplied, many language modules will
 arrange to take ownership of the return value. This allows the value to
 be automatically garbage-collected when it is no longer in use.
 However, this depends entirely on the target language (a language
 module may also choose to ignore the <tt>%newobject</tt> directive).</p>
<p> Closely related to <tt>%newobject</tt> is a special typemap. The
 &quot;newfree&quot; typemap can be used to deallocate a newly allocated return
 value. It is only available on methods for which <tt>%newobject</tt>
 has been applied and is commonly used to clean-up string results. For
 example:</p>
<div class="code">
<pre>
%typemap(newfree) char * &quot;free($1);&quot;;
...
%newobject strdup;
...
char *strdup(const char *s);
</pre>
</div>
<p> In this case, the result of the function is a string in the target
 language. Since this string is a copy of the original result, the data
 returned by <tt>strdup()</tt> is no longer needed. The &quot;newfree&quot;
 typemap in the example simply releases this memory.</p>
<p> As a complement to the <tt>%newobject</tt>, from SWIG 1.3.28, you
 can use the <tt>%delobject</tt> directive. For example, if you have two
 methods, one to create objects and one to destroy them, you can use:</p>
<div class="code">
<pre>
%newobject create_foo;
%delobject destroy_foo;
...
Foo *create_foo();
void destroy_foo(Foo *foo);
</pre>
</div>
<p> or in a member method as:</p>
<div class="code">
<pre>
%delobject Foo::destroy;

class Foo {
public:
  void destroy() { delete this;}

private:
  ~Foo();
};
</pre>
</div>
<p> <tt>%delobject</tt> instructs SWIG that the first argument passed to
 the method will be destroyed, and therefore, the target language should
 not attempt to deallocate it twice. This is similar to use the DISOWN
 typemap in the first method argument, and in fact, it also depends on
 the target language on implementing the 'disown' mechanism properly.</p>
<p> The use of <tt>%newobject</tt> is also integrated with reference
 counting and is covered in the <a href="#SWIGPlus_ref_unref">C++
 reference counted objects</a> section.</p>
<p><b> Compatibility note:</b> Previous versions of SWIG had a special <tt>
%new</tt> directive. However, unlike <tt>%newobject</tt>, it only
 applied to the next declaration. For example:</p>
<div class="code">
<pre>
%new char *strdup(const char *s);
</pre>
</div>
<p> For now this is still supported but is deprecated.</p>
<p><b> How to shoot yourself in the foot:</b> The <tt>%newobject</tt>
 directive is not a declaration modifier like the old <tt>%new</tt>
 directive. Don't write code like this:</p>
<div class="code">
<pre>
%newobject
char *strdup(const char *s);
</pre>
</div>
<p> The results might not be what you expect.</p>
<h2><a name="Customization_features">14.3 Features and the %feature
 directive</a></h2>
<p> Both <tt>%exception</tt> and <tt>%newobject</tt> are examples of a
 more general purpose customization mechanism known as &quot;features.&quot; A
 feature is simply a user-definable property that is attached to
 specific declarations. Features are attached using the <tt>%feature</tt>
 directive. For example:</p>
<div class="code">
<pre>
%feature(&quot;except&quot;) Object::allocate {
  try {
    $action
  }
  catch (MemoryError) {
    croak(&quot;Out of memory&quot;);
  }
}

%feature(&quot;new&quot;, &quot;1&quot;) *::copy;
</pre>
</div>
<p> In fact, the <tt>%exception</tt> and <tt>%newobject</tt> directives
 are really nothing more than macros involving <tt>%feature</tt>:</p>
<div class="code">
<pre>
#define %exception %feature(&quot;except&quot;)
#define %newobject %feature(&quot;new&quot;, &quot;1&quot;)
</pre>
</div>
<p> The name matching rules outlined in the <a href="#SWIGPlus_ambiguity_resolution_renaming">
Renaming and ambiguity resolution</a> section applies to all <tt>
%feature</tt> directives. In fact the <tt>%rename</tt> directive is just
 a special form of <tt>%feature</tt>. The matching rules mean that
 features are very flexible and can be applied with pinpoint accuracy to
 specific declarations if needed. Additionally, if no declaration name
 is given, a global feature is said to be defined. This feature is then
 attached to<em> every</em> declaration that follows. This is how global
 exception handlers are defined. For example:</p>
<div class="code">
<pre>
/* Define a global exception handler */
%feature(&quot;except&quot;) {
  try {
    $action
  }
  ...
}

... bunch of declarations ...
</pre>
</div>
<p> The <tt>%feature</tt> directive can be used with different syntax.
 The following are all equivalent:</p>
<div class="code">
<pre>
%feature(&quot;except&quot;) Object::method { $action };
%feature(&quot;except&quot;) Object::method %{ $action %};
%feature(&quot;except&quot;) Object::method &quot; $action &quot;;
%feature(&quot;except&quot;, &quot;$action&quot;) Object::method;
</pre>
</div>
<p> The syntax in the first variation will generate the <tt>{ }</tt>
 delimiters used whereas the other variations will not.</p>
<h3><a name="Customization_feature_attributes">14.3.1 Feature attributes</a>
</h3>
<p> The <tt>%feature</tt> directive also accepts XML style attributes in
 the same way that typemaps do. Any number of attributes can be
 specified. The following is the generic syntax for features:</p>
<div class="code">
<pre>
%feature(&quot;name&quot;, &quot;value&quot;, attribute1=&quot;AttributeValue1&quot;) symbol;
%feature(&quot;name&quot;, attribute1=&quot;AttributeValue1&quot;) symbol {value};
%feature(&quot;name&quot;, attribute1=&quot;AttributeValue1&quot;) symbol %{value%};
%feature(&quot;name&quot;, attribute1=&quot;AttributeValue1&quot;) symbol &quot;value&quot;;
</pre>
</div>
<p> More than one attribute can be specified using a comma separated
 list. The Java module is an example that uses attributes in <tt>
%feature(&quot;except&quot;)</tt>. The <tt>throws</tt> attribute specifies the
 name of a Java class to add to a proxy method's throws clause. In the
 following example, <tt>MyExceptionClass</tt> is the name of the Java
 class for adding to the throws clause.</p>
<div class="code">
<pre>
%feature(&quot;except&quot;, throws=&quot;MyExceptionClass&quot;) Object::method { 
  try {
    $action
  } catch (...) {
    ... code to throw a MyExceptionClass Java exception ...
  }
};
</pre>
</div>
<p> Further details can be obtained from the <a href="#Java_exception_handling">
Java exception handling</a> section.</p>
<h3><a name="Customization_feature_flags">14.3.2 Feature flags</a></h3>
<p> Feature flags are used to enable or disable a particular feature.
 Feature flags are a common but simple usage of <tt>%feature</tt> and
 the feature value should be either <tt>1</tt> to enable or <tt>0</tt>
 to disable the feature.</p>
<div class="code">
<pre>
%feature(&quot;featurename&quot;)          // enables feature
%feature(&quot;featurename&quot;, &quot;1&quot;)     // enables feature
%feature(&quot;featurename&quot;, &quot;x&quot;)     // enables feature
%feature(&quot;featurename&quot;, &quot;0&quot;)     // disables feature
%feature(&quot;featurename&quot;, &quot;&quot;)      // clears feature
</pre>
</div>
<p> Actually any value other than zero will enable the feature. Note
 that if the value is omitted completely, the default value becomes <tt>
1</tt>, thereby enabling the feature. A feature is cleared by specifying
 no value, see <a href="#Customization_clearing_features">Clearing
 features</a>. The <tt>%immutable</tt> directive described in the <a href="#SWIG_readonly_variables">
Creating read-only variables</a> section, is just a macro for <tt>
%feature(&quot;immutable&quot;)</tt>, and can be used to demonstrates feature
 flags:</p>
<div class="code">
<pre>
                                // features are disabled by default
int red;                        // mutable

%feature(&quot;immutable&quot;);          // global enable
int orange;                     // immutable

%feature(&quot;immutable&quot;, &quot;0&quot;);     // global disable
int yellow;                     // mutable

%feature(&quot;immutable&quot;, &quot;1&quot;);     // another form of global enable
int green;                      // immutable

%feature(&quot;immutable&quot;, &quot;&quot;);      // clears the global feature
int blue;                       // mutable
</pre>
</div>
<p> Note that features are disabled by default and must be explicitly
 enabled either globally or by specifying a targeted declaration. The
 above intersperses SWIG directives with C code. Of course you can
 target features explicitly, so the above could also be rewritten as:</p>
<div class="code">
<pre>
%feature(&quot;immutable&quot;, &quot;1&quot;) orange;
%feature(&quot;immutable&quot;, &quot;1&quot;) green;
int red;                        // mutable
int orange;                     // immutable
int yellow;                     // mutable
int green;                      // immutable
int blue;                       // mutable
</pre>
</div>
<p> The above approach allows for the C declarations to be separated
 from the SWIG directives for when the C declarations are parsed from a
 C header file. The logic above can of course be inverted and rewritten
 as:</p>
<div class="code">
<pre>
%feature(&quot;immutable&quot;, &quot;1&quot;);
%feature(&quot;immutable&quot;, &quot;0&quot;) red;
%feature(&quot;immutable&quot;, &quot;0&quot;) yellow;
%feature(&quot;immutable&quot;, &quot;0&quot;) blue;
int red;                        // mutable
int orange;                     // immutable
int yellow;                     // mutable
int green;                      // immutable
int blue;                       // mutable
</pre>
</div>
<p> As hinted above for <tt>%immutable</tt>, most feature flags can also
 be specified via alternative syntax. The alternative syntax is just a
 macro in the <tt>swig.swg</tt> Library file. The following shows the
 alternative syntax for the imaginary <tt>featurename</tt> feature:</p>
<div class="code">
<pre>
%featurename       // equivalent to %feature(&quot;featurename&quot;, &quot;1&quot;) ie enables feature
%nofeaturename     // equivalent to %feature(&quot;featurename&quot;, &quot;0&quot;) ie disables feature
%clearfeaturename  // equivalent to %feature(&quot;featurename&quot;, &quot;&quot;)  ie clears feature
</pre>
</div>
<p> The concept of clearing features is discussed next.</p>
<h3><a name="Customization_clearing_features">14.3.3 Clearing features</a>
</h3>
<p> A feature stays in effect until it is explicitly cleared. A feature
 is cleared by supplying a <tt>%feature</tt> directive with no value.
 For example <tt>%feature(&quot;name&quot;, &quot;&quot;)</tt>. A cleared feature means that
 any feature exactly matching any previously defined feature is no
 longer used in the name matching rules. So if a feature is cleared, it
 might mean that another name matching rule will apply. To clarify,
 let's consider the <tt>except</tt> feature again (<tt>%exception</tt>):</p>
<div class="code">
<pre>
// Define global exception handler
%feature(&quot;except&quot;) {
  try {
    $action
  } catch (...) {
    croak(&quot;Unknown C++ exception&quot;);
  }
}

// Define exception handler for all clone methods to log the method calls
%feature(&quot;except&quot;) *::clone() {
  try {
    logger.info(&quot;$action&quot;);
    $action
  } catch (...) {
    croak(&quot;Unknown C++ exception&quot;);
  }
}

... initial set of class declarations with clone methods ...

// clear the previously defined feature
%feature(&quot;except&quot;, &quot;&quot;) *::clone();

... final set of class declarations with clone methods ...
</pre>
</div>
<p> In the above scenario, the initial set of clone methods will log all
 method invocations from the target language. This specific feature is
 cleared for the final set of clone methods. However, these clone
 methods will still have an exception handler (without logging) as the
 next best feature match for them is the global exception handler.</p>
<p> Note that clearing a feature is not always the same as disabling it.
 Clearing the feature above with <tt>%feature(&quot;except&quot;, &quot;&quot;) *::clone()</tt>
 is not the same as specifying <tt>%feature(&quot;except&quot;, &quot;0&quot;) *::clone()</tt>
. The former will disable the feature for clone methods - the feature is
 still a better match than the global feature. If on the other hand, no
 global exception handler had been defined at all, then clearing the
 feature would be the same as disabling it as no other feature would
 have matched.</p>
<p> Note that the feature must match exactly for it to be cleared by any
 previously defined feature. For example the following attempt to clear
 the initial feature will not work:</p>
<div class="code">
<pre>
%feature(&quot;except&quot;) clone() { logger.info(&quot;$action&quot;); $action }
%feature(&quot;except&quot;, &quot;&quot;) *::clone();
</pre>
</div>
<p> but this will:</p>
<div class="code">
<pre>
%feature(&quot;except&quot;) clone() { logger.info(&quot;$action&quot;); $action }
%feature(&quot;except&quot;, &quot;&quot;) clone();
</pre>
</div>
<p> SWIG provides macros for disabling and clearing features. Many of
 these can be found in the <tt>swig.swg</tt> library file. The typical
 pattern is to define three macros; one to define the feature itself,
 one to disable the feature and one to clear the feature. The three
 macros below show this for the &quot;except&quot; feature:</p>
<div class="code">
<pre>
#define %exception      %feature(&quot;except&quot;)
#define %noexception    %feature(&quot;except&quot;, &quot;0&quot;)
#define %clearexception %feature(&quot;except&quot;, &quot;&quot;)
</pre>
</div>
<h3><a name="Customization_features_default_args">14.3.4 Features and
 default arguments</a></h3>
<p> SWIG treats methods with default arguments as separate overloaded
 methods as detailed in the <a href="#SWIGPlus_default_args">default
 arguments</a> section. Any <tt>%feature</tt> targeting a method with
 default arguments will apply to all the extra overloaded methods that
 SWIG generates if the default arguments are specified in the feature.
 If the default arguments are not specified in the feature, then the
 feature will match that exact wrapper method only and not the extra
 overloaded methods that SWIG generates. For example:</p>
<div class="code">
<pre>
%feature(&quot;except&quot;) hello(int i=0, double d=0.0) { ... }
void hello(int i=0, double d=0.0);
</pre>
</div>
<p> will apply the feature to all three wrapper methods, that is:</p>
<div class="code">
<pre>
void hello(int i, double d);
void hello(int i);
void hello();
</pre>
</div>
<p> If the default arguments are not specified in the feature:</p>
<div class="code">
<pre>
%feature(&quot;except&quot;) hello(int i, double d) { ... }
void hello(int i=0, double d=0.0);
</pre>
</div>
<p> then the feature will only apply to this wrapper method:</p>
<div class="code">
<pre>
void hello(int i, double d);
</pre>
</div>
<p> and not these wrapper methods:</p>
<div class="code">
<pre>
void hello(int i);
void hello();
</pre>
</div>
<p> If <a href="#SWIGPlus_default_args">compactdefaultargs</a> are being
 used, then the difference between specifying or not specifying default
 arguments in a feature is not applicable as just one wrapper is
 generated.</p>
<p><b> Compatibility note:</b> The different behaviour of features
 specified with or without default arguments was introduced in
 SWIG-1.3.23 when the approach to wrapping methods with default
 arguments was changed.</p>
<h3><a name="Customization_features_example">14.3.5 Feature example</a></h3>
<p> As has been shown earlier, the intended use for the <tt>%feature</tt>
 directive is as a highly flexible customization mechanism that can be
 used to annotate declarations with additional information for use by
 specific target language modules. Another example is in the Python
 module. You might use <tt>%feature</tt> to rewrite proxy/shadow class
 code as follows:</p>
<div class="code">
<pre>
%module example
%rename(bar_id) bar(int, double);

// Rewrite bar() to allow some nice overloading

%feature(&quot;shadow&quot;) Foo::bar(int) %{
def bar(*args):
    if len(args) == 3:
        return apply(examplec.Foo_bar_id, args)
    return apply(examplec.Foo_bar, args)
%}
    
class Foo {
public:
  int bar(int x);
  int bar(int x, double y);
}
</pre>
</div>
<p> Further details of <tt>%feature</tt> usage is described in the
 documentation for specific language modules.</p>
<HR NOSHADE>
<h1><a name="Contract">15 Contracts</a></h1>

<!-- INDEX -->
<div class="sectiontoc">
<ul>
<li><a href="#Contract_nn2">The %contract directive</a></li>
<li><a href="#Contract_nn3">%contract and classes</a></li>
<li><a href="#Contract_nn4">Constant aggregation and %aggregate_check</a>
</li>
<li><a href="#Contract_nn5">Notes</a></li>
</ul>
</div>
<!-- INDEX -->
<p> A common problem that arises when wrapping C libraries is that of
 maintaining reliability and checking for errors. The fact of the matter
 is that many C programs are notorious for not providing error checks.
 Not only that, when you expose the internals of an application as a
 library, it often becomes possible to crash it simply by providing bad
 inputs or using it in a way that wasn't intended.</p>
<p> This chapter describes SWIG's support for software contracts. In the
 context of SWIG, a contract can be viewed as a runtime constraint that
 is attached to a declaration. For example, you can easily attach
 argument checking rules, check the output values of a function and
 more. When one of the rules is violated by a script, a runtime
 exception is generated rather than having the program continue to
 execute.</p>
<h2><a name="Contract_nn2">15.1 The %contract directive</a></h2>
<p> Contracts are added to a declaration using the %contract directive.
 Here is a simple example:</p>
<div class="code">
<pre>
%contract sqrt(double x) {
require:
  x &gt;= 0;
ensure:
  sqrt &gt;= 0;
}

...
double sqrt(double);
</pre>
</div>
<p> In this case, a contract is being added to the <tt>sqrt()</tt>
 function. The <tt>%contract</tt> directive must always appear before
 the declaration in question. Within the contract there are two
 sections, both of which are optional. The <tt>require:</tt> section
 specifies conditions that must hold before the function is called.
 Typically, this is used to check argument values. The <tt>ensure:</tt>
 section specifies conditions that must hold after the function is
 called. This is often used to check return values or the state of the
 program. In both cases, the conditions that must hold must be specified
 as boolean expressions.</p>
<p> In the above example, we're simply making sure that sqrt() returns a
 non-negative number (if it didn't, then it would be broken in some
 way).</p>
<p> Once a contract has been specified, it modifies the behavior of the
 resulting module. For example:</p>
<div class="shell">
<pre>
&gt;&gt;&gt; example.sqrt(2)
1.4142135623730951
&gt;&gt;&gt; example.sqrt(-2)
Traceback (most recent call last):
  File &quot;&lt;stdin&gt;&quot;, line 1, in ?
RuntimeError: Contract violation: require: (arg1&gt;=0)
&gt;&gt;&gt;
</pre>
</div>
<h2><a name="Contract_nn3">15.2 %contract and classes</a></h2>
<p> The <tt>%contract</tt> directive can also be applied to class
 methods and constructors. For example:</p>
<div class="code">
<pre>
%contract Foo::bar(int x, int y) {
require:
  x &gt; 0;
ensure:
  bar &gt; 0;
}

%contract Foo::Foo(int a) {
require:
  a &gt; 0;
}

class Foo {
public:
  Foo(int);
  int bar(int, int);
};
</pre>
</div>
<p> The way in which <tt>%contract</tt> is applied is exactly the same
 as the <tt>%feature</tt> directive. Thus, any contract that you
 specified for a base class will also be attached to inherited methods.
 For example:</p>
<div class="code">
<pre>
class Spam : public Foo {
public:
  int bar(int, int);    // Gets contract defined for Foo::bar(int, int)
};
</pre>
</div>
<p> In addition to this, separate contracts can be applied to both the
 base class and a derived class. For example:</p>
<div class="code">
<pre>
%contract Foo::bar(int x, int) {
require:
  x &gt; 0;
}

%contract Spam::bar(int, int y) {
require:
  y &gt; 0;
}

class Foo {
public:
  int bar(int, int);   // Gets Foo::bar contract.
};

class Spam : public Foo {
public:
  int bar(int, int);   // Gets Foo::bar and Spam::bar contract
};
</pre>
</div>
<p> When more than one contract is applied, the conditions specified in
 a &quot;require:&quot; section are combined together using a logical-AND
 operation. In other words conditions specified for the base class and
 conditions specified for the derived class all must hold. In the above
 example, this means that both the arguments to <tt>Spam::bar</tt> must
 be positive.</p>
<h2><a name="Contract_nn4">15.3 Constant aggregation and
 %aggregate_check</a></h2>
<p> Consider an interface file that contains the following code:</p>
<div class="code">
<pre>
#define  UP     1
#define  DOWN   2
#define  RIGHT  3
#define  LEFT   4

void move(SomeObject *, int direction, int distance);
</pre>
</div>
<p> One thing you might want to do is impose a constraint on the
 direction parameter to make sure it's one of a few accepted values. To
 do that, SWIG provides an easy to use macro %aggregate_check() that
 works like this:</p>
<div class="code">
<pre>
%aggregate_check(int, check_direction, UP, DOWN, LEFT, RIGHT);
</pre>
</div>
<p> This merely defines a utility function of the form</p>
<div class="code">
<pre>
int check_direction(int x);
</pre>
</div>
<p> That checks the argument x to see if it is one of the values listed.
 This utility function can be used in contracts. For example:</p>
<div class="code">
<pre>
%aggregate_check(int, check_direction, UP, DOWN, RIGHT, LEFT);

%contract move(SomeObject *, int direction, in) {
require:
  check_direction(direction);
}

#define  UP     1
#define  DOWN   2
#define  RIGHT  3
#define  LEFT   4

void move(SomeObject *, int direction, int distance);
</pre>
</div>
<p> Alternatively, it can be used in typemaps and other directives. For
 example:</p>
<div class="code">
<pre>
%aggregate_check(int, check_direction, UP, DOWN, RIGHT, LEFT);

%typemap(check) int direction {
  if (!check_direction($1)) SWIG_exception(SWIG_ValueError, &quot;Bad direction&quot;);
}

#define  UP     1
#define  DOWN   2
#define  RIGHT  3
#define  LEFT   4

void move(SomeObject *, int direction, int distance);
</pre>
</div>
<p> Regrettably, there is no automatic way to perform similar checks
 with enums values. Maybe in a future release.</p>
<h2><a name="Contract_nn5">15.4 Notes</a></h2>
<p> Contract support was implemented by Songyan (Tiger) Feng and first
 appeared in SWIG-1.3.20.</p>
<HR NOSHADE>
<h1><a name="Varargs">16 Variable Length Arguments</a></h1>

<!-- INDEX -->
<div class="sectiontoc">
<ul>
<li><a href="#Varargs_nn2">Introduction</a></li>
<li><a href="#Varargs_nn3">The Problem</a></li>
<li><a href="#Varargs_nn4">Default varargs support</a></li>
<li><a href="#Varargs_nn5">Argument replacement using %varargs</a></li>
<li><a href="#Varargs_nn6">Varargs and typemaps</a></li>
<li><a href="#Varargs_nn7">Varargs wrapping with libffi</a></li>
<li><a href="#Varargs_nn8">Wrapping of va_list</a></li>
<li><a href="#Varargs_nn9">C++ Issues</a></li>
<li><a href="#Varargs_nn10">Discussion</a></li>
</ul>
</div>
<!-- INDEX -->
<p><b> (a.k.a, &quot;The horror. The horror.&quot;)</b></p>
<p> This chapter describes the problem of wrapping functions that take a
 variable number of arguments. For instance, generating wrappers for the
 C <tt>printf()</tt> family of functions.</p>
<p> This topic is sufficiently advanced to merit its own chapter. In
 fact, support for varargs is an often requested feature that was first
 added in SWIG-1.3.12. Most other wrapper generation tools have wisely
 chosen to avoid this issue.</p>
<h2><a name="Varargs_nn2">16.1 Introduction</a></h2>
<p> Some C and C++ programs may include functions that accept a variable
 number of arguments. For example, most programmers are familiar with
 functions from the C library such as the following:</p>
<div class="code">
<pre>
int printf(const char *fmt, ...)
int fprintf(FILE *, const char *fmt, ...);
int sprintf(char *s, const char *fmt, ...);
</pre>
</div>
<p> Although there is probably little practical purpose in wrapping
 these specific C library functions in a scripting language (what would
 be the point?), a library may include its own set of special functions
 based on a similar API. For example:</p>
<div class="code">
<pre>
int  traceprintf(const char *fmt, ...);
</pre>
</div>
<p> In this case, you may want to have some kind of access from the
 target language.</p>
<p> Before describing the SWIG implementation, it is important to
 discuss the common uses of varargs that you are likely to encounter in
 real programs. Obviously, there are the <tt>printf()</tt> style output
 functions as shown. Closely related to this would be <tt>scanf()</tt>
 style input functions that accept a format string and a list of
 pointers into which return values are placed. However, variable length
 arguments are also sometimes used to write functions that accept a
 NULL-terminated list of pointers. A good example of this would be a
 function like this:</p>
<div class="code">
<pre>
int execlp(const char *path, const char *arg1, ...);
...

/* Example */
execlp(&quot;ls&quot;, &quot;ls&quot;, &quot;-l&quot;, NULL);
</pre>
</div>
<p> In addition, varargs is sometimes used to fake default arguments in
 older C libraries. For instance, the low level <tt>open()</tt> system
 call is often declared as a varargs function so that it will accept two
 or three arguments:</p>
<div class="code">
<pre>
int open(const char *path, int oflag, ...);
...

/* Examples */
f = open(&quot;foo&quot;, O_RDONLY);
g = open(&quot;bar&quot;, O_WRONLY | O_CREAT, 0644);
</pre>
</div>
<p> Finally, to implement a varargs function, recall that you have to
 use the C library functions defined in <tt>&lt;stdarg.h&gt;</tt>. For
 example:</p>
<div class="code">
<pre>
List make_list(const char *s, ...) {
  va_list ap;
  List    x;
  ...
  va_start(ap, s);
  while (s) {
    x.append(s);
    s = va_arg(ap, const char *);
  }
  va_end(ap);
  return x;
}
</pre>
</div>
<h2><a name="Varargs_nn3">16.2 The Problem</a></h2>
<p> Generating wrappers for a variable length argument function presents
 a number of special challenges. Although C provides support for
 implementing functions that receive variable length arguments, there
 are no functions that can go in the other direction. Specifically, you
 can't write a function that dynamically creates a list of arguments and
 which invokes a varargs function on your behalf.</p>
<p> Although it is possible to write functions that accept the special
 type <tt>va_list</tt>, this is something entirely different. You can't
 take a <tt>va_list</tt> structure and pass it in place of the variable
 length arguments to another varargs function. It just doesn't work.</p>
<p> The reason this doesn't work has to do with the way that function
 calls get compiled. For example, suppose that your program has a
 function call like this:</p>
<div class="code">
<pre>
printf(&quot;Hello %s. Your number is %d\n&quot;, name, num);
</pre>
</div>
<p> When the compiler looks at this, it knows that you are calling <tt>
printf()</tt> with exactly three arguments. Furthermore, it knows that
 the number of arguments as well are their types and sizes is<em> never</em>
 going to change during program execution. Therefore, this gets turned
 to machine code that sets up a three-argument stack frame followed by a
 call to <tt>printf()</tt>.</p>
<p> In contrast, suppose you attempted to make some kind of wrapper
 around <tt>printf()</tt> using code like this:</p>
<div class="code">
<pre>
int wrap_printf(const char *fmt, ...) {
  va_list ap;
  va_start(ap, fmt);
  ...
  printf(fmt, ap);
  ...
  va_end(ap);
};
</pre>
</div>
<p> Although this code might compile, it won't do what you expect. This
 is because the call to <tt>printf()</tt> is compiled as a procedure
 call involving only two arguments. However, clearly a two-argument
 configuration of the call stack is completely wrong if your intent is
 to pass an arbitrary number of arguments to the real <tt>printf()</tt>.
 Needless to say, it won't work.</p>
<p> Unfortunately, the situation just described is exactly the problem
 faced by wrapper generation tools. In general, the number of passed
 arguments will not be known until run-time. To make matters even worse,
 you won't know the types and sizes of arguments until run-time as well.
 Needless to say, there is no obvious way to make the C compiler
 generate code for a function call involving an unknown number of
 arguments of unknown types.</p>
<p> In theory, it<em> is</em> possible to write a wrapper that does the
 right thing. However, this involves knowing the underlying ABI for the
 target platform and language as well as writing special purpose code
 that manually constructed the call stack before making a procedure
 call. Unfortunately, both of these tasks require the use of inline
 assembly code. Clearly, that's the kind of solution you would much
 rather avoid.</p>
<p> With this nastiness in mind, SWIG provides a number of solutions to
 the varargs wrapping problem. Most of these solutions are compromises
 that provide limited varargs support without having to resort to
 assembly language. However, SWIG can also support real varargs wrapping
 (with stack-frame manipulation) if you are willing to get hands dirty.
 Keep reading.</p>
<h2><a name="Varargs_nn4">16.3 Default varargs support</a></h2>
<p> When variable length arguments appear in an interface, the default
 behavior is to drop the variable argument list entirely, replacing them
 with a single NULL pointer. For example, if you had this function,</p>
<div class="code">
<pre>
void traceprintf(const char *fmt, ...);
</pre>
</div>
<p> it would be wrapped as if it had been declared as follows:</p>
<div class="code">
<pre>
void traceprintf(const char *fmt);
</pre>
</div>
<p> When the function is called inside the wrappers, it is called as
 follows:</p>
<div class="code">
<pre>
traceprintf(arg1, NULL);
</pre>
</div>
<p> Arguably, this approach seems to defeat the whole point of variable
 length arguments. However, this actually provides enough support for
 many simple kinds of varargs functions to still be useful, however it
 does come with a caveat. For instance, you could make function calls
 like this (in Python):</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; traceprintf(&quot;Hello World&quot;)
&gt;&gt;&gt; traceprintf(&quot;Hello %s. Your number is %d\n&quot; % (name, num))
&gt;&gt;&gt; traceprintf(&quot;Your result is 90%%.&quot;)
</pre>
</div>
<p> Notice how string formatting is being done in Python instead of C.
 The caveat is the strings passed must be safe to use in C though. For
 example if name was to contain a &quot;%&quot; it should be double escaped in
 order to avoid unpredictable behaviour:</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; traceprintf(&quot;Your result is 90%.\n&quot;)  # unpredictable behaviour
&gt;&gt;&gt; traceprintf(&quot;Your result is 90%%.\n&quot;) # good
</pre>
</div>
<p> Read on for further solutions.</p>
<h2><a name="Varargs_nn5">16.4 Argument replacement using %varargs</a></h2>
<p> Instead of dropping the variable length arguments, an alternative
 approach is to replace <tt>(...)</tt> with a set of suitable arguments.
 SWIG provides a special <tt>%varargs</tt> directive that can be used to
 do this. For example,</p>
<div class="code">
<pre>
%varargs(int mode = 0) open;
...
int open(const char *path, int oflags, ...);
</pre>
</div>
<p> is equivalent to this:</p>
<div class="code">
<pre>
int open(const char *path, int oflags, int mode = 0);
</pre>
</div>
<p> In this case, <tt>%varargs</tt> is simply providing more specific
 information about the extra arguments that might be passed to a
 function. If the arguments to a varargs function are of uniform type, <tt>
%varargs</tt> can also accept a numerical argument count as follows:</p>
<div class="code">
<pre>
%varargs(3, char *str = NULL) execlp;
...
int execlp(const char *path, const char *arg, ...);
</pre>
</div>
<p> and is effectively seen as:</p>
<div class="code">
<pre>
int execlp(const char *path, const char *arg, 
           char *str1 = NULL, 
           char *str2 = NULL, 
           char *str3 = NULL);
</pre>
</div>
<p> This would wrap <tt>execlp()</tt> as a function that accepted up to
 3 optional arguments. Depending on the application, this may be more
 than enough for practical purposes.</p>
<p> The handling of <a href="#SWIGPlus_default_args">default arguments</a>
 can be changed via the <tt>compactdefaultargs</tt> feature. If this
 feature is used, for example</p>
<div class="code">
<pre>
%feature(&quot;compactdefaultargs&quot;) execlp;
%varargs(3, char *str = NULL) execlp;
...
int execlp(const char *path, const char *arg, ...);
</pre>
</div>
<p> a call from the target language which does not provide the maximum
 number of arguments, such as, <tt>execlp(&quot;a&quot;, &quot;b&quot;, &quot;c&quot;)</tt> will
 generate C code which includes the missing default values, that is, <tt>
execlp(&quot;a&quot;, &quot;b&quot;, &quot;c&quot;, NULL, NULL)</tt>. If <tt>compactdefaultargs</tt>
 is not used, then the generated code will be <tt>execlp(&quot;a&quot;, &quot;b&quot;, &quot;c&quot;)</tt>
. The former is useful for helping providing a sentinel to terminate the
 argument list. However, this is not guaranteed, for example when a user
 passes a non-NULL value for all the parameters. When using <tt>
compactdefaultargs</tt> it is possible to guarantee the NULL sentinel is
 passed through the, <tt>numinputs=0</tt> <a href="#Typemaps_nn26">'in'
 typemap attribute</a>, naming the<b> last parameter</b>. For example,</p>
<div class="code">
<pre>
%feature(&quot;compactdefaultargs&quot;) execlp;
%varargs(3, char *str = NULL) execlp;
%typemap(in, numinputs=0) char *str3 &quot;&quot;
...
int execlp(const char *path, const char *arg, ...);
</pre>
</div>
<p> Note that <tt>str3</tt> is the name of the last argument, as we have
 used <tt>%varargs</tt> with 3. Now <tt>execlp(&quot;a&quot;, &quot;b&quot;, &quot;c&quot;, &quot;d&quot;, &quot;e&quot;)</tt>
 will result in an error as one too many arguments has been passed, as
 now only 2 additional 'str' arguments can be passed with the 3rd one
 always using the specified default <tt>NULL</tt>.</p>
<p> Argument replacement is most appropriate in cases where the types of
 the extra arguments are uniform and the maximum number of arguments are
 known. Argument replacement is not as useful when working with
 functions that accept mixed argument types such as <tt>printf()</tt>.
 Providing general purpose wrappers to such functions presents special
 problems (covered shortly).</p>
<h2><a name="Varargs_nn6">16.5 Varargs and typemaps</a></h2>
<p> Variable length arguments may be used in typemap specifications. For
 example:</p>
<div class="code">
<pre>
%typemap(in) (...) {
  // Get variable length arguments (somehow)
  ...
}

%typemap(in) (const char *fmt, ...) {
    // Multi-argument typemap
}
</pre>
</div>
<p> However, this immediately raises the question of what &quot;type&quot; is
 actually used to represent <tt>(...)</tt>. For lack of a better
 alternative, the type of <tt>(...)</tt> is set to <tt>void *</tt>.
 Since there is no way to dynamically pass arguments to a varargs
 function (as previously described), the <tt>void *</tt> argument value
 is intended to serve as a place holder for storing some kind of
 information about the extra arguments (if any). In addition, the
 default behavior of SWIG is to pass the <tt>void *</tt> value as an
 argument to the function. Therefore, you could use the pointer to hold
 a valid argument value if you wanted.</p>
<p> To illustrate, here is a safer version of wrapping <tt>printf()</tt>
 in Python:</p>
<div class="code">
<pre>
%typemap(in) (const char *fmt, ...) {
    $1 = &quot;%s&quot;;                                /* Fix format string to %s */
    $2 = (void *) PyString_AsString($input);  /* Get string argument */
};
...
int printf(const char *fmt, ...);
</pre>
</div>
<p> In this example, the format string is implicitly set to <tt>&quot;%s&quot;</tt>
. This prevents a program from passing a bogus format string to the
 extension. Then, the passed input object is decoded and placed in the <tt>
void *</tt> argument defined for the <tt>(...)</tt> argument. When the
 actual function call is made, the underlying wrapper code will look
 roughly like this:</p>
<div class="code">
<pre>
wrap_printf() {
  char *arg1;
  void *arg2;
  int   result;

  arg1 = &quot;%s&quot;;
  arg2 = (void *) PyString_AsString(arg2obj);
  ...
  result = printf(arg1, arg2);
  ...
}
</pre>
</div>
<p> Notice how both arguments are passed to the function and it does
 what you would expect.</p>
<p> The next example illustrates a more advanced kind of varargs
 typemap. Disclaimer: this requires special support in the target
 language module and is not guaranteed to work with all SWIG modules at
 this time. It also starts to illustrate some of the more fundamental
 problems with supporting varargs in more generality.</p>
<p> If a typemap is defined for any form of <tt>(...)</tt>, many SWIG
 modules will generate wrappers that accept a variable number of
 arguments as input and will make these arguments available in some
 form. The precise details of this depends on the language module being
 used (consult the appropriate chapter for more details). However,
 suppose that you wanted to create a Python wrapper for the <tt>execlp()</tt>
 function shown earlier. To do this using a typemap instead of using <tt>
%varargs</tt>, you might first write a typemap like this:</p>
<div class="code">
<pre>
%typemap(in) (...)(char *vargs[10]) {
  int i;
  int argc;
  for (i = 0; i &lt; 10; i++) vargs[i] = 0;
  argc = PyTuple_Size(varargs);
  if (argc &gt; 10) {
    PyErr_SetString(PyExc_ValueError, &quot;Too many arguments&quot;);
    SWIG_fail;
  }
  for (i = 0; i &lt; argc; i++) {
    PyObject *pyobj = PyTuple_GetItem(varargs, i);
    char *str = 0;
%#if PY_VERSION_HEX&gt;=0x03000000
    PyObject *pystr;
    if (!PyUnicode_Check(pyobj)) {
      PyErr_SetString(PyExc_ValueError, &quot;Expected a string&quot;);
      SWIG_fail;
    }
    pystr = PyUnicode_AsUTF8String(pyobj);
    if (!pystr) {
      SWIG_fail;
    }
    str = strdup(PyBytes_AsString(pystr));
    Py_DECREF(pystr);
%#else  
    if (!PyString_Check(pyobj)) {
      PyErr_SetString(PyExc_ValueError, &quot;Expected a string&quot;);
      SWIG_fail;
    }
    str = PyString_AsString(pyobj);
%#endif
    vargs[i] = str;
  }
  $1 = (void *)vargs;
}

%typemap(freearg) (...) {
%#if PY_VERSION_HEX&gt;=0x03000000
  int i;
  for (i = 0; i &lt; 10; i++) {
    free(vargs$argnum[i]);
  }
%#endif
}
</pre>
</div>
<p> In the 'in' typemap, the special variable <tt>varargs</tt> is a
 tuple holding all of the extra arguments passed (this is specific to
 the Python module). The typemap then pulls this apart and sticks the
 values into the array of strings <tt>args</tt>. Then, the array is
 assigned to <tt>$1</tt> (recall that this is the <tt>void *</tt>
 variable corresponding to <tt>(...)</tt>). However, this assignment is
 only half of the picture----clearly this alone is not enough to make
 the function work. The 'freearg' typemap cleans up memory allocated in
 the 'in' typemap; this code is generated to be called after the <tt>
execlp</tt> function is called. To patch everything up, you have to
 rewrite the underlying action code using the <tt>%feature</tt>
 directive like this:</p>
<div class="code">
<pre>
%feature(&quot;action&quot;) execlp {
  char **vargs = (char **) arg3;
  result = execlp(arg1, arg2, vargs[0], vargs[1], vargs[2], vargs[3], vargs[4],
                  vargs[5], vargs[6], vargs[7], vargs[8], vargs[9], NULL);
}

int execlp(const char *path, const char *arg, ...);
</pre>
</div>
<p> This patches everything up and creates a function that more or less
 works. However, don't try explaining this to your coworkers unless you
 know for certain that they've had several cups of coffee. If you really
 want to elevate your guru status and increase your job security,
 continue to the next section.</p>
<h2><a name="Varargs_nn7">16.6 Varargs wrapping with libffi</a></h2>
<p> All of the previous examples have relied on features of SWIG that
 are portable and which don't rely upon any low-level machine-level
 details. In many ways, they have all dodged the real issue of variable
 length arguments by recasting a varargs function into some weaker
 variation with a fixed number of arguments of known types. In many
 cases, this works perfectly fine. However, if you want more generality
 than this, you need to bring out some bigger guns.</p>
<p> One way to do this is to use a special purpose library such as
 libffi (<a href="http://www.sourceware.org/libffi/">
http://www.sourceware.org/libffi/</a>). libffi is a library that allows
 you to dynamically construct call-stacks and invoke procedures in a
 relatively platform independent manner. Details about the library can
 be found in the libffi distribution and are not repeated here.</p>
<p> To illustrate the use of libffi, suppose that you<em> really</em>
 wanted to create a wrapper for <tt>execlp()</tt> that accepted<em> any</em>
 number of arguments. To do this, you might make a few adjustments to
 the previous example. For example:</p>
<div class="code">
<pre>
/* Take an arbitrary number of extra arguments and place into an array
   of strings */

%typemap(in) (...) {
  char **argv;
  int    argc;
  int    i;

  argc = PyTuple_Size(varargs);
  argv = (char **) malloc(sizeof(char *)*(argc+1));
  for (i = 0; i &lt; argc; i++) {
    PyObject *o = PyTuple_GetItem(varargs, i);
    if (!PyString_Check(o)) {
      free(argv);
      PyErr_SetString(PyExc_ValueError, &quot;Expected a string&quot;);
      SWIG_fail;
    }
    argv[i] = PyString_AsString(o);
  }
  argv[i] = NULL;
  $1 = (void *) argv;
}

/* Rewrite the function call, using libffi */    

%feature(&quot;action&quot;) execlp {
  int       i, vc;
  ffi_cif   cif;
  ffi_type  **types;
  void      **values;
  char      **args;

  vc = PyTuple_Size(varargs);
  types  = (ffi_type **) malloc((vc+3)*sizeof(ffi_type *));
  values = (void **) malloc((vc+3)*sizeof(void *));
  args   = (char **) arg3;

  /* Set up path parameter */
  types[0] = &amp;ffi_type_pointer;
  values[0] = &amp;arg1;
  
  /* Set up first argument */
  types[1] = &amp;ffi_type_pointer;
  values[1] = &amp;arg2;

  /* Set up rest of parameters */
  for (i = 0; i &lt;= vc; i++) {
    types[2+i] = &amp;ffi_type_pointer;
    values[2+i] = &amp;args[i];
  }
  if (ffi_prep_cif(&amp;cif, FFI_DEFAULT_ABI, vc+3,
                   &amp;ffi_type_uint, types) == FFI_OK) {
    ffi_call(&amp;cif, (void (*)()) execlp, &amp;result, values);
  } else {
    free(types);
    free(values);
    free(arg3);
    PyErr_SetString(PyExc_RuntimeError, &quot;Whoa!!!!!&quot;);
    SWIG_fail;
  }
  free(types);
  free(values);
  free(arg3);
}

/* Declare the function. Whew! */
int execlp(const char *path, const char *arg1, ...);
</pre>
</div>
<p> Looking at this example, you may start to wonder if SWIG is making
 life any easier. Given the amount of code involved, you might also
 wonder why you didn't just write a hand-crafted wrapper! Either that or
 you're wondering &quot;why in the hell am I trying to wrap this varargs
 function in the first place?!?&quot; Obviously, those are questions you'll
 have to answer for yourself.</p>
<p> As a more extreme example of libffi, here is some code that attempts
 to wrap <tt>printf()</tt>,</p>
<div class="code">
<pre>
/* A wrapper for printf() using libffi */

%{
/* Structure for holding passed arguments after conversion */
  typedef struct {
    int type;
    union {
      int    ivalue;
      double dvalue;
      void   *pvalue;
    } val;
  } vtype;
  enum { VT_INT, VT_DOUBLE, VT_POINTER };
%}

%typemap(in) (const char *fmt, ...) {
  vtype *argv;
  int    argc;
  int    i;

  /* Format string */
  $1 = PyString_AsString($input);

  /* Variable length arguments */
  argc = PyTuple_Size(varargs);
  argv = (vtype *) malloc(argc*sizeof(vtype));
  for (i = 0; i &lt; argc; i++) {
    PyObject *o = PyTuple_GetItem(varargs, i);
    if (PyInt_Check(o)) {
      argv[i].type = VT_INT;
      argv[i].val.ivalue = PyInt_AsLong(o);
    } else if (PyFloat_Check(o)) {
      argv[i].type = VT_DOUBLE;
      argv[i].val.dvalue = PyFloat_AsDouble(o);
    } else if (PyString_Check(o)) {
      argv[i].type = VT_POINTER;
      argv[i].val.pvalue = (void *) PyString_AsString(o);
    } else {
      free(argv);
      PyErr_SetString(PyExc_ValueError, &quot;Unsupported argument type&quot;);
      return NULL;
    }
  }
  $2 = (void *) argv;
}

/* Rewrite the function call using libffi */    
%feature(&quot;action&quot;) printf {
  int       i, vc;
  ffi_cif   cif;
  ffi_type  **types;
  void      **values;
  vtype     *args;

  vc = PyTuple_Size(varargs);
  types  = (ffi_type **) malloc((vc+1)*sizeof(ffi_type *));
  values = (void **) malloc((vc+1)*sizeof(void *));
  args   = (vtype *) arg2;

  /* Set up fmt parameter */
  types[0] = &amp;ffi_type_pointer;
  values[0] = &amp;arg1;

  /* Set up rest of parameters */
  for (i = 0; i &lt; vc; i++) {
    switch(args[i].type) {
    case VT_INT:
      types[1+i] = &amp;ffi_type_uint;
      values[1+i] = &amp;args[i].val.ivalue;
      break;
    case VT_DOUBLE:
      types[1+i] = &amp;ffi_type_double;
      values[1+i] = &amp;args[i].val.dvalue;
      break;
    case VT_POINTER:
      types[1+i] = &amp;ffi_type_pointer;
      values[1+i] = &amp;args[i].val.pvalue;
      break;
    default:
      abort();    /* Whoa! We're seriously hosed */
      break;   
    }
  }
  if (ffi_prep_cif(&amp;cif, FFI_DEFAULT_ABI, vc+1,
                   &amp;ffi_type_uint, types) == FFI_OK) {
    ffi_call(&amp;cif, (void (*)()) printf, &amp;result, values);
  } else {
    free(types);
    free(values);
    free(args);
    PyErr_SetString(PyExc_RuntimeError, &quot;Whoa!!!!!&quot;);
    SWIG_fail;
  }
  free(types);
  free(values);
  free(args);
}

/* The function */
int printf(const char *fmt, ...);
</pre>
</div>
<p> Much to your amazement, it even seems to work if you try it:</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; import example
&gt;&gt;&gt; example.printf(&quot;Grade: %s   %d/60 = %0.2f%%\n&quot;, &quot;Dave&quot;, 47, 47.0*100/60)
Grade: Dave   47/60 = 78.33%
&gt;&gt;&gt;
</pre>
</div>
<p> Of course, there are still some limitations to consider:</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; example.printf(&quot;la de da de da %s&quot;, 42)
Segmentation fault (core dumped)
</pre>
</div>
<p> And, on this note, we leave further exploration of libffi to the
 reader as an exercise. Although Python has been used as an example,
 most of the techniques in this section can be extrapolated to other
 language modules with a bit of work. The only details you need to know
 is how the extra arguments are accessed in each target language. For
 example, in the Python module, we used the special <tt>varargs</tt>
 variable to get these arguments. Modules such as Tcl8 and Perl5 simply
 provide an argument number for the first extra argument. This can be
 used to index into an array of passed arguments to get values. Please
 consult the chapter on each language module for more details.</p>
<h2><a name="Varargs_nn8">16.7 Wrapping of va_list</a></h2>
<p> Closely related to variable length argument wrapping, you may
 encounter functions that accept a parameter of type <tt>va_list</tt>.
 For example:</p>
<div class="code">
<pre>
int vprintf(const char *fmt, va_list ap);
</pre>
</div>
<p> As far as we know, there is no obvious way to wrap these functions
 with SWIG. This is because there is no documented way to assemble the
 proper va_list structure (there are no C library functions to do it and
 the contents of va_list are opaque). Not only that, the contents of a <tt>
va_list</tt> structure are closely tied to the underlying call-stack.
 It's not clear that exporting a <tt>va_list</tt> would have any use or
 that it would work at all.</p>
<p> A workaround can be implemented by writing a simple varargs C
 wrapper and then using the techniques discussed earlier in this chapter
 for varargs. Below is a simple wrapper for <tt>vprintf</tt> renamed so
 that it can still be called as <tt>vprintf</tt> from your target
 language. The <tt>%varargs</tt> used in the example restricts the
 function to taking one string argument.</p>
<div class="code">
<pre>
%{
int vprintf(const char *fmt, va_list ap);
%}

%varargs(const char *) my_vprintf;
%rename(vprintf) my_vprintf;

%inline %{
int my_vprintf(const char *fmt, ...) {
  va_list ap;
  int result;

  va_start(ap, fmt);
  result = vprintf(fmt, ap);
  va_end(ap);
  return result;
}
%}
</pre>
</div>
<h2><a name="Varargs_nn9">16.8 C++ Issues</a></h2>
<p> Wrapping of C++ member functions that accept a variable number of
 arguments presents a number of challenges. By far, the easiest way to
 handle this is to use the <tt>%varargs</tt> directive. This is portable
 and it fully supports classes much like the <tt>%rename</tt> directive.
 For example:</p>
<div class="code">
<pre>
%varargs (10, char * = NULL) Foo::bar;

class Foo {
public:
  virtual void bar(char *arg, ...);   // gets varargs above
};

class Spam: public Foo {
public:
  virtual void bar(char *arg, ...);   // gets varargs above
};
</pre>
</div>
<p> <tt>%varargs</tt> also works with constructors, operators, and any
 other C++ programming construct that accepts variable arguments.</p>
<p> Doing anything more advanced than this is likely to involve a
 serious world of pain. In order to use a library like libffi, you will
 need to know the underlying calling conventions and details of the C++
 ABI. For instance, the details of how <tt>this</tt> is passed to member
 functions as well as any hidden arguments that might be used to pass
 additional information. These details are implementation specific and
 may differ between compilers and even different versions of the same
 compiler. Also, be aware that invoking a member function is further
 complicated if it is a virtual method. In this case, invocation might
 require a table lookup to obtain the proper function address (although
 you might be able to obtain an address by casting a bound pointer to a
 pointer to function as described in the C++ ARM section 18.3.4).</p>
<p> If you do decide to change the underlying action code, be aware that
 SWIG always places the <tt>this</tt> pointer in <tt>arg1</tt>. Other
 arguments are placed in <tt>arg2</tt>, <tt>arg3</tt>, and so forth. For
 example:</p>
<div class="code">
<pre>
%feature(&quot;action&quot;) Foo::bar {
  ...
  result = arg1-&gt;bar(arg2, arg3, etc.);
  ...
}
</pre>
</div>
<p> Given the potential to shoot yourself in the foot, it is probably
 easier to reconsider your design or to provide an alternative interface
 using a helper function than it is to create a fully general wrapper to
 a varargs C++ member function.</p>
<h2><a name="Varargs_nn10">16.9 Discussion</a></h2>
<p> This chapter has provided a number of techniques that can be used to
 address the problem of variable length argument wrapping. If you care
 about portability and ease of use, the <tt>%varargs</tt> directive is
 probably the easiest way to tackle the problem. However, using
 typemaps, it is possible to do some very advanced kinds of wrapping.</p>
<p> One point of discussion concerns the structure of the libffi
 examples in the previous section. Looking at that code, it is not at
 all clear that this is the easiest way to solve the problem. However,
 there are a number of subtle aspects of the solution to
 consider--mostly concerning the way in which the problem has been
 decomposed. First, the example is structured in a way that tries to
 maintain separation between wrapper-specific information and the
 declaration of the function itself. The idea here is that you might
 structure your interface like this:</p>
<div class="code">
<pre>
%typemap(const char *fmt, ...) {
  ...
}
%feature(&quot;action&quot;) traceprintf {
  ...
}

/* Include some header file with traceprintf in it */
%include &quot;someheader.h&quot;
</pre>
</div>
<p> Second, careful scrutiny will reveal that the typemaps involving <tt>
(...)</tt> have nothing whatsoever to do with the libffi library. In
 fact, they are generic with respect to the way in which the function is
 actually called. This decoupling means that it will be much easier to
 consider other library alternatives for making the function call. For
 instance, if libffi wasn't supported on a certain platform, you might
 be able to use something else instead. You could use conditional
 compilation to control this:</p>
<div class="code">
<pre>
#ifdef USE_LIBFFI
%feature(&quot;action&quot;) printf {
  ...
}
#endif
#ifdef USE_OTHERFFI
%feature(&quot;action&quot;) printf {
...
}
#endif
</pre>
</div>
<p> Finally, even though you might be inclined to just write a
 hand-written wrapper for varargs functions, the techniques used in the
 previous section have the advantage of being compatible with all other
 features of SWIG such as exception handling.</p>
<p> As a final word, some C programmers seem to have the assumption that
 the wrapping of variable length argument functions is an easily solved
 problem. However, this section has hopefully dispelled some of these
 myths. All things being equal, you are better off avoiding variable
 length arguments if you can. If you can't avoid them, please consider
 some of the simple solutions first. If you can't live with a simple
 solution, proceed with caution. At the very least, make sure you
 carefully read the section &quot;A7.3.2 Function Calls&quot; in Kernighan and
 Ritchie and make sure you fully understand the parameter passing
 conventions used for varargs. Also, be aware of the platform
 dependencies and reliability issues that this will introduce. Good
 luck.</p>
<HR NOSHADE>
<h1><a name="Doxygen">17 SWIG and Doxygen Translation</a></h1>

<!-- INDEX -->
<div class="sectiontoc">
<ul>
<li><a href="#Doxygen_translation_overview">Doxygen translation overview</a>
</li>
<li><a href="#Doxygen_file_preparation">Preparations</a>
<ul>
<li><a href="#Doxygen_running_swig">Enabling Doxygen translation</a></li>
<li><a href="#Doxygen_features">Doxygen-specific %feature directives</a>
<ul>
<li><a href="#Doxygen_notranslate">doxygen:notranslate</a></li>
<li><a href="#Doxygen_alias">doxygen:alias:&lt;command-name&gt;</a></li>
<li><a href="#Doxygen_ignore">doxygen:ignore:&lt;command-name&gt;</a></li>
<li><a href="#Doxygen_nolinktranslate">doxygen:nolinktranslate</a></li>
<li><a href="#Doxygen_nostripparams">doxygen:nostripparams</a></li>
</ul>
</li>
<li><a href="#Doxygen_additional_options">Additional command line
 options</a></li>
</ul>
</li>
<li><a href="#Doxygen_to_javadoc">Doxygen to Javadoc</a>
<ul>
<li><a href="#Doxygen_basic_example">Basic example</a></li>
<li><a href="#Doxygen_javadoc_tags">Javadoc tags</a></li>
<li><a href="#Doxygen_unsupported_tags">Unsupported tags</a></li>
<li><a href="#Doxygen_further_details">Further details</a></li>
</ul>
</li>
<li><a href="#Doxygen_to_pydoc">Doxygen to Pydoc</a>
<ul>
<li><a href="#Doxygen_python_basic_example">Basic example</a></li>
<li><a href="#Doxygen_pydoc_tags">Pydoc translator</a></li>
<li><a href="#Doxygen_python_unsupported_tags">Unsupported tags</a></li>
<li><a href="#Doxygen_python_further_details">Further details</a></li>
</ul>
</li>
<li><a href="#Doxygen_troubleshooting">Troubleshooting</a>
<ul>
<li><a href="#troubleshooting_ifndef">Problem with conditional
 compilation</a></li>
</ul>
</li>
<li><a href="#Doxygen_developer_details">Developer information</a>
<ul>
<li><a href="#Doxygen_translator_design">Doxygen translator design</a></li>
<li><a href="#Doxygen_debugging_commands">Debugging the Doxygen parser
 and translator</a></li>
<li><a href="#Doxygen_tests">Tests</a></li>
</ul>
</li>
<li><a href="#Doxygen_language_extension">Extending to other languages</a>
</li>
</ul>
</div>
<!-- INDEX -->
<p> This chapter describes SWIG's support for translating Doxygen
 comments found in interface and header files into a target language's
 normal documentation language. Currently only Javadoc and Pydoc is
 supported.</p>
<h2><a name="Doxygen_translation_overview">17.1 Doxygen translation
 overview</a></h2>
<p> The Doxygen Translation module of SWIG adds an extra layer of
 functionality to SWIG, allowing automated translation of <a href="http://www.doxygen.nl/manual/">
Doxygen</a> formatted comments from input files into a documentation
 language more suited for the target language. Currently this module
 only translates into Javadoc and Pydoc for the SWIG Java and Python
 modules. Other extensions could be added at a later date. The Doxygen
 Translation module originally started as a <a href="https://developers.google.com/open-source/gsoc/2008/">
Google Summer of Code</a> proposal from Summer 2008.</p>
<h2><a name="Doxygen_file_preparation">17.2 Preparations</a></h2>
<p> To make use of the comment translation system, your documentation
 comments must be in properly formatted <a href="http://www.doxygen.nl/manual/">
Doxygen.</a> Doxygen comments can be present in your main SWIG interface
 file or any header file that it imports. You are advised to be validate
 that your comments compile properly with Doxygen before you try to
 translate them. Doxygen itself is a more comprehensive tool and can
 provide you better feedback for correcting any syntax errors that may
 be present. Please look at Doxygen's <a href="http://www.doxygen.nl/manual/docblocks.html">
 Documenting the code</a> for the full comment format specifications.
 However, SWIG's Doxygen parser will still report many errors and
 warnings found in comments (like unterminated strings or missing ending
 tags).</p>
<p> Currently, the whole subset of Doxygen comment styles is supported
 (See <a href="http://www.doxygen.nl/manual/docblocks.html"> Documenting
 the code</a>). Here they are:</p>
<div class="code">
<pre>
/**
 * Javadoc style comment, multiline
 */
/*!
 * QT-style comment, multiline
 */
/**
 Any of the above, but without intermediate *'s
 */
/// Single-line comment
//! Another single-line comment
</pre>
</div>
<p> Also any of the above with '<tt>&lt;</tt>' added after comment-starting
 symbol, like <tt>/**&lt;, /*!&lt;, ///&lt;,</tt> or <tt>//!&lt;</tt> will be
 treated as a post-comment and will be assigned to the code before the
 comment. Any number of '<tt>*</tt>' or '<tt>/</tt>' within a Doxygen
 comment is considered to be a separator and is not included in the
 final comment, so you may safely use comments like <tt>/*********/</tt>
 or <tt>//////////</tt>.</p>
<p> Please note, as SWIG parses the input file by itself with strict
 grammar, there is only a limited support for various cases of comment
 placement in the file.</p>
<p> Comments can be placed before C/C++ expressions on separate lines:</p>
<div class="code">
<pre>
/**
 * Some comment
 */
void someOtherFunction();
/**
 * Some comment
 */
void someFunction();

class Shape {
  /*
   * Calculate the area in cm^2
   */
  int getArea();
}
</pre>
</div>
<p> After C/C++ expressions at the end of the line:</p>
<div class="code">
<pre>
int someVariable = 9; ///&lt; This is a var holding magic number 9
void doNothing(); ///&lt; This does nothing, nop
</pre>
</div>
<p> and in some special cases, like function parameter comments:</p>
<div class="code">
<pre>
void someFunction(
         int a ///&lt; Some parameter 
     );
</pre>
</div>
<p> or enum element comments:</p>
<div class="code">
<pre>
enum E_NUMBERS
{
    EN_ZERO, ///&lt; The first enum item, gets zero as it's value
    EN_ONE, ///&lt; The second, EN_ONE=1
    EN_THREE
};
</pre>
</div>
<p> Currently only comments directly before or after the code items are
 supported. Doxygen also supports comments containing structural
 commands, where the comments for a code item are not put directly
 before or after the code item. These structural commands are stripped
 out by SWIG and are not assigned to anything.</p>
<h3><a name="Doxygen_running_swig">17.2.1 Enabling Doxygen translation</a>
</h3>
<p> Doxygen comments translation is disabled by default and needs to be
 explicitly enabled using the command line <tt>-doxygen</tt> option for
 the languages that do support it (currently Java and Python).</p>
<h3><a name="Doxygen_features">17.2.2 Doxygen-specific %feature
 directives</a></h3>
<p> Translation of Doxygen comments is influenced by the following <a href="#Customization_features">
%feature directives</a>:</p>
<h4><a name="Doxygen_notranslate">17.2.2.1 doxygen:notranslate</a></h4>
<p> Turns off translation of Doxygen comments to the target language
 syntax: the original comment will be copied to the output unchanged.
 This is useful if you want to use Doxygen itself to generate
 documentation for the target language instead of the corresponding
 language tool (<tt>javadoc</tt>, <tt>sphinx</tt>, ...).</p>
<h4><a name="Doxygen_alias">17.2.2.2 doxygen:alias:&lt;command-name&gt;</a></h4>
<p> Specify an alias for a Doxygen command with the given name. This can
 be useful for custom Doxygen commands which can be defined using <tt>
ALIASES</tt> option for Doxygen itself but which are unknown to SWIG. <tt>
&quot;command-name&quot;</tt> is the name of the command in the Doxyfile, e.g. if
 it contains</p>
<div class="code">
<pre>
ALIASES = &quot;sideeffect=\par Side Effects:\n&quot;
</pre>
</div>
<p> Then you could also specify the same expansion for SWIG with:</p>
<div class="code">
<pre>
%feature(&quot;doxygen:alias:sideeffect&quot;) &quot;\par Side Effects:\n&quot;
</pre>
</div>
<p> Please note that command arguments are not currently supported with
 this feature.</p>
<p> Notice that it is perfectly possible and potentially useful to
 define the alias expansion differently depending on the target
 language, e.g. with</p>
<div class="code">
<pre>
#ifdef SWIGJAVA
%feature(&quot;doxygen:alias:not_for_java&quot;) &quot;This functionality is not available for Java&quot;
#else
%feature(&quot;doxygen:alias:not_for_java&quot;) &quot;&quot;
#endif
</pre>
</div>
<p> you could use <tt>@not_for_java</tt> in the documentation comments
 of all functions which can't, for whatever reason, be currently exposed
 in Java wrappers of the C++ API.</p>
<h4><a name="Doxygen_ignore">17.2.2.3 doxygen:ignore:&lt;command-name&gt;</a></h4>
<p> This feature makes it possible to just ignore an unknown Doxygen
 command, instead of replacing it with the predefined text that <tt>
doxygen:alias</tt> does. For example, you could use</p>
<div class="code">
<pre>
%feature(&quot;doxygen:ignore:transferfull&quot;) Fantastic();
/**
    A fantastic function.

    @transferfull Command ignored, but anything here is still included.
 */
int * Fantastic();
</pre>
</div>
<p> if you use a custom Doxygen <tt>transferfull</tt> command to
 indicate that the return value ownership is transferred to the caller,
 as this information doesn't make much sense for the other languages
 without explicit ownership management.</p>
<p> Doxygen syntax is rather rich and, in addition to simple commands
 such as <tt>@transferfull</tt>, it is also possible to define commands
 with arguments. As explained in <a href="http://www.doxygen.nl/manual/commands.html">
Doxygen documentation</a>, the arguments can have a range of a single
 word, everything until the end of line or everything until the end of
 the next paragraph. Currently, only the &quot;end of line&quot; case is supported
 using the <tt>range=&quot;line&quot;</tt> argument of the feature directive:</p>
<div class="code">
<pre>
// Ignore occurrences of
//
//    @compileroptions Some special C++ compiler options.
//
// in Doxygen comments as C++ options are not interesting for the target language
// developers.
%feature(&quot;doxygen:ignore:compileroptions&quot;, range=&quot;line&quot;) Amazing();

/**
    An amazing function.

    @compileroptions This function must be compiled with /EHa when using MSVC.
 */
void Amazing();

</pre>
</div>
<p> In addition, it is also possible to have custom pairs of begin/end
 tags, similarly to the standard Doxygen <tt>@code/@endcode</tt>, for
 example. Such tags can also be ignored using the special value of <tt>
range</tt> starting with <tt>end</tt> to indicate that the range is an
 interval, for example:</p>
<div class="code">
<pre>
%feature(&quot;doxygen:ignore:forcpponly&quot;, range=&quot;end&quot;); // same as &quot;end:endforcpponly&quot;
/**
    An incredible function.

    @forcpponly
    This is C++-specific.
    @endforcpponly
 */
void Incredible();
</pre>
</div>
<p> would ignore everything between <tt>@forcpponly</tt> and <tt>
@endforcpponly</tt> commands in Doxygen comments. By default, the name
 of the end command is the same as of the start one with &quot;end&quot; prefix,
 following Doxygen conventions, but this can be overridden by providing
 the end command name after the colon.</p>
<p> This example shows how custom tags can be used to bracket anything
 specific to C++ and prevent it from appearing in the target language
 documentation. Conversely, another pair of custom tags could be used to
 put target language specific information in the C++ comments. In this
 case, only the custom tags themselves should be ignored, but their
 contents should be parsed as usual and <tt>contents=&quot;parse&quot;</tt> can be
 used for this:</p>
<div class="code">
<pre>
%feature(&quot;doxygen:ignore:beginPythonOnly&quot;, range=&quot;end:endPythonOnly&quot;, contents=&quot;parse&quot;);
/**
    A splendid function.

    @beginPythonOnly
    This is specific to @b Python.
    @endPythonOnly
 */
void Splendid();

</pre>
</div>
<p> Putting everything together, if these directives are in effect:</p>
<div class="code">
<pre>
%feature(&quot;doxygen:ignore:transferfull&quot;);
%feature(&quot;doxygen:ignore:compileroptions&quot;, range=&quot;line&quot;);
%feature(&quot;doxygen:ignore:forcpponly&quot;, range=&quot;end&quot;);
%feature(&quot;doxygen:ignore:beginPythonOnly&quot;, range=&quot;end:endPythonOnly&quot;, contents=&quot;parse&quot;);
</pre>
</div>
<p> then the following C++ Doxygen comment:</p>
<div class="code">
<pre>
/**
    A contrived example of ignoring too many commands in one comment.

    @forcpponly
    This is C++-specific.
    @endforcpponly

    @beginPythonOnly
    This is specific to @b Python.
    @endPythonOnly

    @transferfull Command ignored, but anything here is still included.

    @compileroptions This function must be compiled with /EHa when using MSVC.
 */
int * Contrived();
</pre>
</div>
<p> would be translated to this comment in Python:</p>
<div class="code">
<pre>
def func():
    r&quot;&quot;&quot;
    A contrived example of ignoring too many commands in one comment.

    This is specific to **Python**.

    Command ignored, but anything here is still included.
    &quot;&quot;&quot;
    ...
</pre>
</div>
<h4><a name="Doxygen_nolinktranslate">17.2.2.4 doxygen:nolinktranslate</a>
</h4>
<p> Turn off automatic link-objects translation. This is only applicable
 to Java at the moment.</p>
<h4><a name="Doxygen_nostripparams">17.2.2.5 doxygen:nostripparams</a></h4>
<p> Turn off stripping of <tt>@param</tt> and <tt>@tparam</tt> Doxygen
 commands if the parameter is not found in the function signature. This
 is only applicable to Java at the moment.</p>
<h3><a name="Doxygen_additional_options">17.2.3 Additional command line
 options</a></h3>
<p> ALSO TO BE ADDED (Javadoc auto brief?)</p>
<h2><a name="Doxygen_to_javadoc">17.3 Doxygen to Javadoc</a></h2>
<p> If translation is enabled, Javadoc formatted comments should be
 automatically placed in the correct locations in the resulting module
 and proxy files.</p>
<h3><a name="Doxygen_basic_example">17.3.1 Basic example</a></h3>
<p> Here is an example segment from an included header file</p>
<div class="code">
<pre>
/*! This is describing class Shape
 \author Bob
 */

class Shape {
public:
  Shape() {
    nshapes++;
  }
  virtual ~Shape() {
    nshapes--;
  };
  double  x, y; /*!&lt; Important Variables */
  void    move(double dx, double dy); /*!&lt; Moves the Shape */
  virtual double area(void) = 0; /*!&lt; \return the area */
  virtual double perimeter(void) = 0; /*!&lt; \return the perimeter */
  static  int nshapes;
};
</pre>
</div>
<p> Simply running SWIG should result in the following code being
 present in Shapes.java</p>
<div class="targetlang">
<pre>

/**
 * This is describing class Shape 
 * @author Bob 
 * 
 */

public class Shape {

...

/**
 * Important Variables 
 */
  public void setX(double value) {
    ShapesJNI.Shape_x_set(swigCPtr, this, value);
  }

/**
 * Important Variables 
 */
  public double getX() {
    return ShapesJNI.Shape_x_get(swigCPtr, this);
  }

/**
 * Moves the Shape 
 */
  public void move(double dx, double dy) {
    ShapesJNI.Shape_move(swigCPtr, this, dx, dy);
  }

/**
 * @return the area 
 */
  public double area() {
    return ShapesJNI.Shape_area(swigCPtr, this);
  }

/**
 * @return the perimeter 
 */
  public double perimeter() {
    return ShapesJNI.Shape_perimeter(swigCPtr, this);
  }
}

</pre>
</div>
<p> The code Java-wise should be identical to what would have been
 generated without the doxygen functionality enabled. When the Doxygen
 Translator module encounters a comment that contains nothing useful or
 a doxygen comment that it cannot parse, it will not affect the
 functionality of the SWIG generated code.</p>
<p> The Javadoc translator will handle most of the tags conversions (see
 the table below). It will also automatically translate link-objects
 params, in \see and \link...\endlink commands. For example,
 'someFunction(std::string)' will be converted to
 'someFunction(String)'. If you don't want such behaviour, you could
 turn this off by using the 'doxygen:nolinktranslate' feature. Also all
 '\param' and '\tparam' commands are stripped out, if the specified
 parameter is not present in the function. Use 'doxygen:nostripparams'
 to avoid.</p>
<p> Javadoc translator features summary (see <a href="#Customization_features">
%feature directives</a>):</p>
<h3><a name="Doxygen_javadoc_tags">17.3.2 Javadoc tags</a></h3>
<p> Here is the list of all Doxygen tags and the description of how they
 are translated to Javadoc</p>
<div class="diagram">
<table border="0" summary="Java Doxygen tags">
<tr><th align="left">Doxygen tags</th></tr>
<tr><td>\a</td><td>wrapped with &lt;i&gt; html tag</td></tr>
<tr><td>\arg</td><td>wrapped with &lt;li&gt; html tag</td></tr>
<tr><td>\author</td><td>translated to @author</td></tr>
<tr><td>\authors</td><td>translated to @author</td></tr>
<tr><td>\b</td><td>wrapped with &lt;b&gt; html tag</td></tr>
<tr><td>\c</td><td>wrapped with &lt;code&gt; html tag</td></tr>
<tr><td>\cite</td><td>wrapped with &lt;i&gt; html tag</td></tr>
<tr><td>\code</td><td>translated to {@code ...}</td></tr>
<tr><td>\code{&lt;ext&gt;}</td><td>translated to {@code ...}; code language
 extension is ignored</td></tr>
<tr><td>\cond</td><td>translated to 'Conditional comment: &lt;condition&gt;'</td>
</tr>
<tr><td>\copyright</td><td>replaced with 'Copyright:'</td></tr>
<tr><td>\deprecated</td><td>translated to @deprecated</td></tr>
<tr><td>\e</td><td>wrapped with &lt;i&gt; html tag</td></tr>
<tr><td>\else</td><td>replaced with '}Else:{'</td></tr>
<tr><td>\elseif</td><td>replaced with '}Else if: &lt;condition&gt;{'</td></tr>
<tr><td>\em</td><td>wrapped with &lt;i&gt; html tag</td></tr>
<tr><td>\endcode</td><td>see note for \code</td></tr>
<tr><td>\endcond</td><td>replaced with 'End of conditional comment.'</td>
</tr>
<tr><td>\endif</td><td>replaced with '}'</td></tr>
<tr><td>\endlink</td><td>see note for \link</td></tr>
<tr><td>\endverbatim</td><td>see note for \verbatim</td></tr>
<tr><td>\exception</td><td>translated to @exception</td></tr>
<tr><td>\f$, \f[, \f], \f{, \f}</td><td>LateX formulas are left
 unchanged</td></tr>
<tr><td>\if</td><td>replaced with 'If: &lt;condition&gt; {'</td></tr>
<tr><td>\ifnot</td><td>replaced with 'If not: &lt;condition&gt; {'</td></tr>
<tr><td>\image</td><td>translated to &lt;img/&gt; html tag only if target=HTML</td>
</tr>
<tr><td>\li</td><td>wrapped with &lt;li&gt; html tag</td></tr>
<tr><td>\link</td><td>translated to {@link ...}</td></tr>
<tr><td>\n</td><td>replaced with newline char</td></tr>
<tr><td>\note</td><td>replaced with 'Note:'</td></tr>
<tr><td>\overload</td><td>prints 'This is an overloaded ...' according
 to Doxygen docs</td></tr>
<tr><td>\p</td><td>wrapped with &lt;code&gt; html tag</td></tr>
<tr><td>\par</td><td>replaced with &lt;p alt='title'&gt;...&lt;/p&gt;</td></tr>
<tr><td>\param</td><td>translated to @param</td></tr>
<tr><td>\param[&lt;dir&gt;]</td><td>translated to @param; parameter direction
 ('in'; 'out'; or 'in,out') is ignored</td></tr>
<tr><td>\remark</td><td>replaced with 'Remarks:'</td></tr>
<tr><td>\remarks</td><td>replaced with 'Remarks:'</td></tr>
<tr><td>\result</td><td>translated to @return</td></tr>
<tr><td>\return</td><td>translated to @return</td></tr>
<tr><td>\returns</td><td>translated to @return</td></tr>
<tr><td>\sa</td><td>translated to @see</td></tr>
<tr><td>\see</td><td>translated to @see</td></tr>
<tr><td>\since</td><td>translated to @since</td></tr>
<tr><td>\throw</td><td>translated to @throws</td></tr>
<tr><td>\throws</td><td>translated to @throws</td></tr>
<tr><td>\todo</td><td>replaced with 'TODO:'</td></tr>
<tr><td>\tparam</td><td>translated to @param</td></tr>
<tr><td>\verbatim</td><td>translated to {@literal ...}</td></tr>
<tr><td>\version</td><td>translated to @version</td></tr>
<tr><td>\warning</td><td>translated to 'Warning:'</td></tr>
<tr><td>\$</td><td>prints $ char</td></tr>
<tr><td>\@</td><td>prints @ char</td></tr>
<tr><td>\\</td><td>prints \ char</td></tr>
<tr><td>\&amp;</td><td>prints &amp; char</td></tr>
<tr><td>\~</td><td>prints ~ char</td></tr>
<tr><td>\&lt;</td><td>prints &lt; char</td></tr>
<tr><td>\&gt;</td><td>prints &gt; char</td></tr>
<tr><td>\#</td><td>prints # char</td></tr>
<tr><td>\%</td><td>prints % char</td></tr>
<tr><td>\&quot;</td><td>prints &quot; char</td></tr>
<tr><td>\.</td><td>prints . char</td></tr>
<tr><td>\::</td><td>prints ::</td></tr>
</table>
</div>
<h3><a name="Doxygen_unsupported_tags">17.3.3 Unsupported tags</a></h3>
<p> Doxygen has a wealth of tags such as @latexonly that have no
 equivalent in Javadoc (all supported tags are listed in <a href="https://docs.oracle.com/javase/7/docs/technotes/tools/windows/javadoc.html">
Javadoc documentation</a>). As a result several tags have no translation
 or particular use, such as some linking and section tags. These are
 suppressed with their content just printed out (if the tag has any
 sense, typically text content). Here is the list of these tags:</p>
<div class="diagram"><b> Unsupported Doxygen tags</b>
<ul style="list-style-type:none;column-count:4;">
<li>\addindex</li>
<li>\addtogroup</li>
<li>\anchor</li>
<li>\attention</li>
<li>\brief</li>
<li>\bug</li>
<li>\callergraph</li>
<li>\callgraph</li>
<li>\category</li>
<li>\class</li>
<li>\copybrief</li>
<li>\copydetails</li>
<li>\copydoc</li>
<li>\date</li>
<li>\def</li>
<li>\defgroup</li>
<li>\details</li>
<li>\dir</li>
<li>\dontinclude</li>
<li>\dot</li>
<li>\dotfile</li>
<li>\enddot</li>
<li>\endhtmlonly</li>
<li>\endinternal</li>
<li>\endlatexonly</li>
<li>\endmanonly</li>
<li>\endmsc</li>
<li>\endrtfonly</li>
<li>\endxmlonly</li>
<li>\enum</li>
<li>\example</li>
<li>\extends</li>
<li>\file</li>
<li>\fn</li>
<li>\headerfile</li>
<li>\hideinitializer</li>
<li>\htmlinclude</li>
<li>\htmlonly</li>
<li>\implements</li>
<li>\include</li>
<li>\includelineno</li>
<li>\ingroup</li>
<li>\interface</li>
<li>\internal</li>
<li>\invariant</li>
<li>\latexonly</li>
<li>\line</li>
<li>\mainpage</li>
<li>\manonly</li>
<li>\memberof</li>
<li>\msc</li>
<li>\mscfile</li>
<li>\name</li>
<li>\namespace</li>
<li>\nosubgrouping</li>
<li>\package</li>
<li>\page</li>
<li>\paragraph</li>
<li>\post</li>
<li>\pre</li>
<li>\private</li>
<li>\privatesection</li>
<li>\property</li>
<li>\protected</li>
<li>\protectedsection</li>
<li>\protocol</li>
<li>\public</li>
<li>\publicsection</li>
<li>\ref</li>
<li>\related</li>
<li>\relatedalso</li>
<li>\relates</li>
<li>\relatesalso</li>
<li>\retval</li>
<li>\rtfonly</li>
<li>\section</li>
<li>\short</li>
<li>\showinitializer</li>
<li>\skip</li>
<li>\skipline</li>
<li>\snippet</li>
<li>\struct</li>
<li>\subpage</li>
<li>\subsection</li>
<li>\subsubsection</li>
<li>\tableofcontents</li>
<li>\test</li>
<li>\typedef</li>
<li>\union</li>
<li>\until</li>
<li>\var</li>
<li>\verbinclude</li>
<li>\weakgroup</li>
<li>\xmlonly</li>
<li>\xrefitem</li>
</ul>
</div>
<p> If one of the following Doxygen tags appears as the first tag in a
 comment, the whole comment block is ignored:
<!-- see parser.y, function isStructuralDoxygen() -->
</p>
<div class="diagram"><b> Ignored Doxygen tags</b>
<ul style="list-style-type:none;column-count:4;">
<li>\addtogroup</li>
<li>\callergraph</li>
<li>\callgraph</li>
<li>\category</li>
<li>\class</li>
<li>\def</li>
<li>\defgroup</li>
<li>\dir</li>
<li>\enum</li>
<li>\example</li>
<li>\file</li>
<li>\fn</li>
<li>\headerfile</li>
<li>\hideinitializer</li>
<li>\interface</li>
<li>\internal</li>
<li>\mainpage</li>
<li>\name</li>
<li>\namespace</li>
<li>\nosubgrouping</li>
<li>\overload</li>
<li>\package</li>
<li>\page</li>
<li>\property</li>
<li>\protocol</li>
<li>\relates</li>
<li>\relatesalso</li>
<li>\showinitializer</li>
<li>\struct</li>
<li>\typedef</li>
<li>\union</li>
<li>\var</li>
<li>\weakgroup</li>
</ul>
</div>
<h3><a name="Doxygen_further_details">17.3.4 Further details</a></h3>
<p> TO BE ADDED.</p>
<h2><a name="Doxygen_to_pydoc">17.4 Doxygen to Pydoc</a></h2>
<p> If translation is enabled, Pydoc formatted comments should be
 automatically placed in the correct locations in the resulting module
 and proxy files. The problem is that Pydoc has no tag mechanism like
 Doxygen or Javadoc, so most of Doxygen commands are translated by
 merely copying the appropriate command text.</p>
<h3><a name="Doxygen_python_basic_example">17.4.1 Basic example</a></h3>
<p> Here is an example segment from an included header file</p>
<div class="code">
<pre>
/*! This is describing class Shape
 \author Bob
 */

class Shape {
public:
  Shape() {
    nshapes++;
  }
  virtual ~Shape() {
    nshapes--;
  };
  double  x, y; /*!&lt; Important Variables */
  void    move(double dx, double dy); /*!&lt; Moves the Shape */
  virtual double area(void) = 0; /*!&lt; \return the area */
  virtual double perimeter(void) = 0; /*!&lt; \return the perimeter */
  static  int nshapes;
};
</pre>
</div>
<p> Simply running SWIG should result in the following code being
 present in Shapes.py</p>
<div class="targetlang">
<pre>

...

class Shape(_object):
    &quot;&quot;&quot;
    This is describing class Shape 
    Authors:
    Bob 

    &quot;&quot;&quot;
    
    ...
    
    def move(self, *args):
        &quot;&quot;&quot;
        Moves the Shape 
        &quot;&quot;&quot;
        return _Shapes.Shape_move(self, *args)

    def area(self):
        &quot;&quot;&quot;
        Return:
        the area 
        &quot;&quot;&quot;
        return _Shapes.Shape_area(self)

    def perimeter(self):
        &quot;&quot;&quot;
        Return:
        the perimeter 
        &quot;&quot;&quot;
        return _Shapes.Shape_perimeter(self)
</pre>
</div>
<p> If any parameters of a function or a method are documented in the
 Doxygen comment, their description is copied into the generated output
 using <a href="http://sphinx-doc.org/">Sphinx</a> documentation
 conventions. For example</p>
<div class="code">
<pre>
/**
    Set a breakpoint at the given location.

    @param filename The full path to the file.
    @param line_number The line number in the file.
 */
bool SetBreakpoint(const char* filename, int line_number);
</pre>
</div>
<p> would be translated to</p>
<div class="targetlang">
<pre>
def SetBreakpoint(filename, line_number):
    r&quot;&quot;&quot;
    Set a breakpoint at the given location.

    :type filename: string
    :param filename: The full path to the file.
    :type line_number: int
    :param line_number: The line number in the file.
    &quot;&quot;&quot;
</pre>
</div>
<p> The types used for the parameter documentation come from the
 &quot;doctype&quot; typemap which is defined for all the primitive types and a
 few others (e.g. <tt>std::string</tt> and <tt>shared_ptr&lt;T&gt;</tt>) but
 for non-primitive types is taken to be just the C++ name of the type
 with namespace scope delimiters (<tt>::</tt>) replaced with a dot. To
 change this, you can define your own typemaps for the custom types,
 e.g:</p>
<div class="code">
<pre>
%typemap(doctype) MyDate &quot;datetime.date&quot;;
</pre>
</div>
<p> Currently Doxygen comments assigned to global variables and static
 member variables are not present in generated code, so they have no
 comment translated for them.</p>
<p><b> Whitespace and tables</b> Whitespace is preserved when
 translating comments, so it makes sense to have Doxygen comments
 formatted in a readable way. This includes tables, where tags &lt;th&gt;,
 &lt;td&gt; and &lt;/tr&gt;are translated to '|'. The line after line with &lt;th&gt; tags
 contains dashes. If we take care about whitespace, comments in Python
 are much more readable. Example:<div class="code">
<pre>
/**
 * &lt;table border = '1'&gt;
 * &lt;caption&gt;Animals&lt;/caption&gt;
 * &lt;tr&gt;&lt;th&gt; Column 1 &lt;/th&gt;&lt;th&gt; Column 2 &lt;/th&gt;&lt;/tr&gt;
 * &lt;tr&gt;&lt;td&gt; cow      &lt;/td&gt;&lt;td&gt; dog      &lt;/td&gt;&lt;/tr&gt;
 * &lt;tr&gt;&lt;td&gt; cat      &lt;/td&gt;&lt;td&gt; mouse    &lt;/td&gt;&lt;/tr&gt;
 * &lt;tr&gt;&lt;td&gt; horse    &lt;/td&gt;&lt;td&gt; parrot   &lt;/td&gt;&lt;/tr&gt;
 * &lt;/table&gt;
 */
</pre>
</div></p>
<p> translates to Python as:</p>
<div class="diagram">
<pre>
  Animals
  | Column 1 | Column 2 |
  -----------------------
  | cow      | dog      |
  | cat      | mouse    |
  | horse    | parrot   |
</pre>
</div>
<p><b> Overloaded functions</b> Since all the overloaded functions in
 c++ are wrapped into one Python function, Pydoc translator will combine
 every comment of every overloaded function and put it into the comment
 for the one wrapper function.</p>
<p> If you intend to use resulting generated Python file with the
 Doxygen docs generator, rather than Pydoc, you may want to turn off
 translation completely (doxygen:notranslate feature). Then SWIG will
 just copy the comments to the proxy file and reformat them if needed,
 but all the comment content will be left as is. As Doxygen doesn't
 support special commands in Python comments (see <a href="http://www.doxygen.nl/manual/docblocks.html#pythonblocks">
Doxygen docs</a>), you may want to use some tool like doxypy (<a href="https://pypi.org/project/doxypy/">
doxypy</a>) to do the work.</p>
<h3><a name="Doxygen_pydoc_tags">17.4.2 Pydoc translator</a></h3>
<p> Here is the list of all Doxygen tags and the description of how they
 are translated to Pydoc</p>
<div class="diagram">
<table border="0" summary="Python Doxygen tags">
<tr><th align="left">Doxygen tags</th></tr>
<tr><td>\a</td><td>wrapped with '*'</td></tr>
<tr><td>\arg</td><td>prepended with '* '</td></tr>
<tr><td>\author</td><td>prints 'Author:'</td></tr>
<tr><td>\authors</td><td>prints 'Authors:'</td></tr>
<tr><td>\b</td><td>wrapped with '**'</td></tr>
<tr><td>\c</td><td>wrapped with '``'</td></tr>
<tr><td>\cite</td><td>wrapped with single quotes</td></tr>
<tr><td>\code</td><td>replaced with '.. code-block:: c++'</td></tr>
<tr><td>\code{&lt;ext&gt;}</td><td>replaced with '.. code-block:: &lt;lang&gt;',
 where the following doxygen code languages are recognized: .c -&gt; C, .py
 -&gt; python, .java &gt; java</td></tr>
<tr><td>\cond</td><td>translated to 'Conditional comment: &lt;condition&gt;'</td>
</tr>
<tr><td>\copyright</td><td>prints 'Copyright:'</td></tr>
<tr><td>\deprecated</td><td>prints 'Deprecated:'</td></tr>
<tr><td>\e</td><td>wrapped with '*'</td></tr>
<tr><td>\else</td><td>replaced with '}Else:{'</td></tr>
<tr><td>\elseif</td><td>replaced with '}Else if: &lt;condition&gt;{'</td></tr>
<tr><td>\em</td><td>wrapped with '*'</td></tr>
<tr><td>\endcond</td><td>replaced with 'End of conditional comment.'</td>
</tr>
<tr><td>\endif</td><td>replaced with '}'</td></tr>
<tr><td>\example</td><td>replaced with 'Example:'</td></tr>
<tr><td>\exception</td><td>replaced with ':raises:'</td></tr>
<tr><td>\f$</td><td>rendered using ':math:``'</td></tr>
<tr><td>\f[</td><td>rendered using '.. math::'</td></tr>
<tr><td>\f{</td><td>rendered using '.. math::'</td></tr>
<tr><td>\if</td><td>replaced with 'If: &lt;condition&gt; {'</td></tr>
<tr><td>\ifnot</td><td>replaced with 'If not: &lt;condition&gt; {'</td></tr>
<tr><td>\li</td><td>prepended with '* '</td></tr>
<tr><td>\n</td><td>replaced with newline char</td></tr>
<tr><td>\note</td><td>replaced with 'Note:'</td></tr>
<tr><td>\overload</td><td>prints 'This is an overloaded ...' according
 to Doxygen docs</td></tr>
<tr><td>\p</td><td>wrapped with '``'</td></tr>
<tr><td>\par</td><td>replaced with 'Title: ...'</td></tr>
<tr><td>\param</td><td>add ':type:' and ':param:' directives</td></tr>
<tr><td>\param[&lt;dir&gt;]</td><td>same as \param, but direction ('in';
 'out'; 'in,out') is included in ':type:' directive</td></tr>
<tr><td>\remark</td><td>replaced with 'Remarks:'</td></tr>
<tr><td>\remarks</td><td>replaced with 'Remarks:'</td></tr>
<tr><td>\result</td><td>add ':rtype:' and ':return:' directives</td></tr>
<tr><td>\return</td><td>add ':rtype:' and ':return:' directives</td></tr>
<tr><td>\returns</td><td>add ':rtype:' and ':return:' directives</td></tr>
<tr><td>\sa</td><td>replaced with 'See also:'</td></tr>
<tr><td>\see</td><td>replaced with 'See also:'</td></tr>
<tr><td>\since</td><td>replaced with 'Since:'</td></tr>
<tr><td>\throw</td><td>replaced with ':raises:'</td></tr>
<tr><td>\throws</td><td>replaced wih ':raises:'</td></tr>
<tr><td>\todo</td><td>replaced with 'TODO:'</td></tr>
<tr><td>\tparam</td><td>add ':type:' and ':param:' directives</td></tr>
<tr><td>\verbatim</td><td>content copied verbatim</td></tr>
<tr><td>\version</td><td>replaced with 'Version:'</td></tr>
<tr><td>\warning</td><td>translated to 'Warning:'</td></tr>
<tr><td>\$</td><td>prints $ char</td></tr>
<tr><td>\@</td><td>prints @ char</td></tr>
<tr><td>\\</td><td>prints \ char</td></tr>
<tr><td>\&amp;</td><td>prints &amp; char</td></tr>
<tr><td>\~</td><td>prints ~ char</td></tr>
<tr><td>\&lt;</td><td>prints &lt; char</td></tr>
<tr><td>\&gt;</td><td>prints &gt; char</td></tr>
<tr><td>\#</td><td>prints # char</td></tr>
<tr><td>\%</td><td>prints % char</td></tr>
<tr><td>\&quot;</td><td>prints &quot; char</td></tr>
<tr><td>\.</td><td>prints . character</td></tr>
<tr><td>\::</td><td>prints ::</td></tr>
</table>
</div>
<h3><a name="Doxygen_python_unsupported_tags">17.4.3 Unsupported tags</a>
</h3>
<p> Doxygen has a wealth of tags such as @latexonly that have no
 equivalent in Pydoc. As a result several tags that have no translation
 (or particular use, such as some linking and section tags) are
 suppressed with their content just printed out (if it has any sense,
 typically text content). Here is the list of these tags:</p>
<div class="diagram"><b> Unsupported Python Doxygen tags</b>
<ul style="list-style-type:none;column-count:4;">
<li>\addindex</li>
<li>\addtogroup</li>
<li>\anchor</li>
<li>\attention</li>
<li>\brief</li>
<li>\bug</li>
<li>\callergraph</li>
<li>\callgraph</li>
<li>\category</li>
<li>\class</li>
<li>\copybrief</li>
<li>\copydetails</li>
<li>\copydoc</li>
<li>\date</li>
<li>\def</li>
<li>\defgroup</li>
<li>\details</li>
<li>\dir</li>
<li>\dontinclude</li>
<li>\dot</li>
<li>\dotfile</li>
<li>\enddot</li>
<li>\endhtmlonly</li>
<li>\endinternal</li>
<li>\endlatexonly</li>
<li>\endlink</li>
<li>\endmanonly</li>
<li>\endmsc</li>
<li>\endrtfonly</li>
<li>\endxmlonly</li>
<li>\enum</li>
<li>\extends</li>
<li>\file</li>
<li>\fn</li>
<li>\headerfile</li>
<li>\hideinitializer</li>
<li>\htmlinclude</li>
<li>\htmlonly</li>
<li>\image</li>
<li>\implements</li>
<li>\include</li>
<li>\includelineno</li>
<li>\ingroup</li>
<li>\interface</li>
<li>\internal</li>
<li>\invariant</li>
<li>\latexonly</li>
<li>\line</li>
<li>\link</li>
<li>\mainpage</li>
<li>\manonly</li>
<li>\memberof</li>
<li>\msc</li>
<li>\mscfile</li>
<li>\name</li>
<li>\namespace</li>
<li>\nosubgrouping</li>
<li>\package</li>
<li>\page</li>
<li>\paragraph</li>
<li>\post</li>
<li>\pre</li>
<li>\private</li>
<li>\privatesection</li>
<li>\property</li>
<li>\protected</li>
<li>\protectedsection</li>
<li>\protocol</li>
<li>\public</li>
<li>\publicsection</li>
<li>\ref</li>
<li>\related</li>
<li>\relatedalso</li>
<li>\relates</li>
<li>\relatesalso</li>
<li>\retval</li>
<li>\rtfonly</li>
<li>\section</li>
<li>\short</li>
<li>\showinitializer</li>
<li>\skip</li>
<li>\skipline</li>
<li>\snippet</li>
<li>\struct</li>
<li>\subpage</li>
<li>\subsection</li>
<li>\subsubsection</li>
<li>\tableofcontents</li>
<li>\test</li>
<li>\typedef</li>
<li>\union</li>
<li>\until</li>
<li>\var</li>
<li>\verbinclude</li>
<li>\weakgroup</li>
<li>\xmlonly</li>
<li>\xrefitem</li>
</ul>
</div>
<h3><a name="Doxygen_python_further_details">17.4.4 Further details</a></h3>
<p> TO BE ADDED.</p>
<h2><a name="Doxygen_troubleshooting">17.5 Troubleshooting</a></h2>
<p> When running SWIG with command line option <tt>-doxygen</tt>, it may
 happen that SWIG will fail to parse the code, which is valid C++ code
 and is parsed without problems without the option. The problem is, that
 Doxygen comments are not tokens (the C/C++ compiler actually never sees
 them) and that they can appear anywhere in the code. That's why it is
 practically impossible to handle all corner cases with the parser.
 However, these problems can usually be avoided by minor changes in the
 code or comment. Known problems and solutions are shown in this
 section.</p>
<p> Recommended approach is to first run SWIG without command line
 option <tt>-doxygen</tt>. When it successfully processes the code,
 include the option and fix problems with Doxygen comments.</p>
<h3><a name="troubleshooting_ifndef">17.5.1 Problem with conditional
 compilation</a></h3>
<p> Inserting a conditional compilation preprocessor directive between a
 Doxygen comment and a commented item may break parsing:</p>
<div class="code">
<pre>
class A {
  /**
   * Some func.
   */
  <font color="#ff0000">#ifndef SWIG</font>
  void myfunc()
  {
  }
  #endif
};
</pre>
</div>
<p> The solution is to move the directive above the comment:</p>
<div class="code">
<pre>
class A {
  <font color="#00d000">#ifndef SWIG</font>
  /**
   * Some func.
   */
  void myfunc()
  {
  }
  #endif
};
</pre>
</div>
<h2><a name="Doxygen_developer_details">17.6 Developer information</a></h2>
<p> This section contains information for developers enhancing the
 Doxygen translator.</p>
<h3><a name="Doxygen_translator_design">17.6.1 Doxygen translator design</a>
</h3>
<p> If this functionality is turned on, SWIG places all comments found
 into the SWIG parse tree. Nodes contain an additional attribute called <tt>
doxygen</tt> when a comment is present. Individual nodes containing
 Doxygen with Structural Indicators, such as @file, as their first
 command, are also present in the parse tree. These individual &quot;blobs&quot;
 of Doxygen such as :</p>
<div class="code">
<pre>
/*! This is describing function Foo
 \param x some random variable
 \author Bob
 \return Foo
 */
</pre>
</div>
<p> are passed on individually to the Doxygen Translator module. This
 module builds its own private parse tree and hands it to a separate
 class for translation into the target documentation language. For
 example, <tt>JavaDocConverter</tt> is the Javadoc module class.</p>
<h3><a name="Doxygen_debugging_commands">17.6.2 Debugging the Doxygen
 parser and translator</a></h3>
<p> There are two handy command line options, that enable lots of
 detailed debug information printing.</p>
<div class="shell">
<pre>
  -debug-doxygen-parser     - Display Doxygen parser module debugging information
  -debug-doxygen-translator - Display Doxygen translator module debugging information
</pre>
</div>
<h3><a name="Doxygen_tests">17.6.3 Tests</a></h3>
<p> Doxygen tests have been added to the regular SWIG test-suite. There
 are a number of tests beginning <tt>doxygen_</tt> in the
 Examples/test-suite sub-directory.</p>
<p> Like any other SWIG test case, the tests are included in
 Examples/test-suite/common.mk and can be tested with commands like <tt>
make check-test-suite</tt> or <tt>make check-python-test-suite</tt>. To
 run them individually, type <tt>make -s &lt;testname&gt;.cpptest</tt> in the
 language-specific sub-directory in <tt>Examples/test-suite</tt>
 directory. For example:</p>
<div class="shell">
<pre>
  Examples/test-suite/java $ make -s doxygen_parsing.cpptest
</pre>
</div>
<p> If the test fails, both expected and translated comments are printed
 to std out, but also written to files<i> expected.txt</i> and<i>
 got.txt</i>. Since it is often difficult to find a single character
 difference in several lines of text, we can use some diff tool, for
 example:</p>
<div class="shell">
<pre>
  Examples/test-suite/java $ kdiff3 expected.txt got.txt
</pre>
</div>
<p> Runtime tests in Java are implemented using Javadoc doclets. To make
 that work, you should have tools.jar from the JDK in your classpath. Or
 you should have JAVA_HOME environment variable defined and pointing to
 the JDK location.</p>
<p> The Java's comment parsing code (the testing part) is located in
 commentParser.java. It checks the generated code. It is possible to run
 this file as a stand-alone program, with <tt>java commentParser &lt;some
 java package&gt;</tt>, and it will print the list of comments found in the
 specified directory (in the format it has used in the runtime tests).
 So, when you want to create a new Doxygen test case, just copy an
 existing one and replace the actual comment content (section of entries
 in form 'wantedComments.put(...)' with the output of the above command.</p>
<p> Runtime tests in Python are just plain string comparisons of the
 __doc__ properties.</p>
<h2><a name="Doxygen_language_extension">17.7 Extending to other
 languages</a></h2>
<p> In general, an extension to another language requires a fairly deep
 understanding of the target language module, such as Modules/python.cxx
 for Python. Searching for &quot;doxygen&quot; in the java.cxx module can give you
 a good idea of the process for placing documentation comments into the
 correct areas. The basic gist is that anywhere a comment may reside on
 a node, there needs to be a catch for it in front of where that
 function, class, or other object is written out to a target language
 file. The other half of extension is building a target documentation
 language comment generator that handles one blob at a time. However,
 this is relatively simple and nowhere near as complex as the wrapper
 generating modules in SWIG. See Source/Doxygen/javadoc.cxx for a good
 example. The target language module passes the Doxygen Translator the
 blob to translate, and receives back the translated text.</p>
<p><b> What is given to the Doxygen Translator</b></p>
<div class="code">
<pre>
/*! This is describing function Foo
 \param x some random variable
 \author Bob
 \return Foo
 */
</pre>
</div>
<p><b> What is received back by java.cxx</b></p>
<div class="targetlang">
<pre>
/** This is describing function Foo
 *
 * @param x some random variable
 * @author Bob
 * @return Foo
 */
</pre>
</div>
<p> Development of the comment translator itself is simplified by the
 fact that the Doxygen Translator module can easily include a <tt>main</tt>
 function and thus be developed, compiled, and tested independently of
 SWIG.</p>
<HR NOSHADE>
<h1><a name="Warnings">18 Warning Messages</a></h1>

<!-- INDEX -->
<div class="sectiontoc">
<ul>
<li><a href="#Warnings_nn2">Introduction</a></li>
<li><a href="#Warnings_suppression">Warning message suppression</a></li>
<li><a href="#Warnings_nn4">Enabling extra warnings</a></li>
<li><a href="#Warnings_nn5">Issuing a warning message</a></li>
<li><a href="#Warnings_symbolic_symbols">Symbolic symbols</a></li>
<li><a href="#Warnings_nn6">Commentary</a></li>
<li><a href="#Warnings_nn7">Warnings as errors</a></li>
<li><a href="#Warnings_nn8">Message output format</a></li>
<li><a href="#Warnings_nn9">Warning number reference</a>
<ul>
<li><a href="#Warnings_nn10">Deprecated features (100-199)</a></li>
<li><a href="#Warnings_nn11">Preprocessor (200-299)</a></li>
<li><a href="#Warnings_nn12">C/C++ Parser (300-399)</a></li>
<li><a href="#Warnings_nn13">Types and typemaps (400-499)</a></li>
<li><a href="#Warnings_nn14">Code generation (500-559)</a></li>
<li><a href="#Warnings_doxygen">Doxygen comments (560-599)</a></li>
<li><a href="#Warnings_nn15">Language module specific (700-899)</a></li>
<li><a href="#Warnings_nn16">User defined (900-999)</a></li>
</ul>
</li>
<li><a href="#Warnings_nn17">History</a></li>
</ul>
</div>
<!-- INDEX -->
<h2><a name="Warnings_nn2">18.1 Introduction</a></h2>
<p> During compilation, SWIG may generate a variety of warning messages.
 For example:</p>
<div class="shell">
<pre>
example.i:16: Warning 501: Overloaded declaration ignored.  bar(double)
example.i:15: Warning 501: Previous declaration is bar(int)
</pre>
</div>
<p> Typically, warning messages indicate non-fatal problems with the
 input where the generated wrapper code will probably compile, but it
 may not work like you expect.</p>
<h2><a name="Warnings_suppression">18.2 Warning message suppression</a></h2>
<p> All warning messages have a numeric code that is shown in the
 warning message itself. To suppress the printing of a warning message,
 a number of techniques can be used. First, you can run SWIG with the <tt>
-w</tt> command line option. For example:</p>
<div class="shell">
<pre>
% swig -python -w501 example.i
% swig -python -w501,505,401 example.i
</pre>
</div>
<p> Alternatively, warnings can be suppressed by inserting a special
 preprocessor pragma into the input file:</p>
<div class="code">
<pre>
%module example
#pragma SWIG nowarn=501
#pragma SWIG nowarn=501,505,401
</pre>
</div>
<p> Finally, code-generation warnings can be disabled on a declaration
 by declaration basis using the <tt>%warnfilter</tt> directive. For
 example:</p>
<div class="code">
<pre>
%module example
%warnfilter(501) foo;
...
int foo(int);
int foo(double);              // Silently ignored.
</pre>
</div>
<p> The <tt>%warnfilter</tt> directive has the same semantics as other
 declaration modifiers like <tt>%rename</tt>, <tt>%ignore</tt> and <tt>
%feature</tt>, see the <a href="#Customization_features">%feature
 directive</a> section. For example, if you wanted to suppress a warning
 for a method in a class hierarchy, you could do this:</p>
<div class="code">
<pre>
%warnfilter(501) Object::foo;
class Object {
public:
  int foo(int);
  int foo(double);      // Silently ignored
  ...
};

class Derived : public Object {
public:
  int foo(int);
  int foo(double);      // Silently ignored
  ...
};
</pre>
</div>
<p> Warnings can be suppressed for an entire class by supplying a class
 name. For example:</p>
<div class="code">
<pre>
%warnfilter(501) Object;

class Object {
public:
  ...                      // All 501 warnings ignored in class
};
</pre>
</div>
<p> There is no option to suppress all SWIG warning messages. The
 warning messages are there for a reason---to tell you that something
 may be<em> broken</em> in your interface. Ignore the warning messages
 at your own peril.</p>
<h2><a name="Warnings_nn4">18.3 Enabling extra warnings</a></h2>
<p> Some warning messages are disabled by default and are generated only
 to provide additional diagnostics. These warnings can be turned on
 using the <tt>-Wextra</tt> option. For example:</p>
<div class="shell">
<pre>
% swig -Wextra -python example.i
</pre>
</div>
<p> To selectively turn on extra warning messages, you can use the
 directives and options in the previous section--simply add a &quot;+&quot; to all
 warning numbers. For example:</p>
<div class="shell">
<pre>
% swig -w+309,+452 example.i
</pre>
</div>
<p> or in your interface file use either</p>
<div class="code">
<pre>
#pragma SWIG nowarn=+309,+452
</pre>
</div>
<p> or</p>
<div class="code">
<pre>
%warnfilter(+309,+452) foo;
</pre>
</div>
<p> Note: selective enabling of warnings with <tt>%warnfilter</tt>
 overrides any global settings you might have made using <tt>-w</tt> or <tt>
#pragma</tt>.</p>
<p> You can of course also enable all warnings and suppress a select
 few, for example:</p>
<div class="shell">
<pre>
% swig -Wextra -w309,452 example.i
</pre>
</div>
<p> The warnings on the right take precedence over the warnings on the
 left, so in the above example <tt>-Wextra</tt> adds numerous warnings
 including 452, but then <tt>-w309,452</tt> overrides this and so 452 is
 suppressesed.</p>
<p> If you would like all warnings to appear, regardless of the warning
 filters used, then use the <tt>-Wall</tt> option. The <tt>-Wall</tt>
 option also turns on the extra warnings that <tt>-Wextra</tt> adds,
 however, it is subtely different. When <tt>-Wall</tt> is used, it also
 disables all other warning filters, that is, any warnings suppressed or
 added in <tt>%warnfilter</tt>, <tt>#pragma SWIG nowarn</tt> or the <tt>
-w</tt> option.</p>
<h2><a name="Warnings_nn5">18.4 Issuing a warning message</a></h2>
<p> Warning messages can be issued from an interface file using a number
 of directives. The <tt>%warn</tt> directive is the most simple:</p>
<div class="code">
<pre>
%warn &quot;900:This is your last warning!&quot;
</pre>
</div>
<p> All warning messages are optionally prefixed by the warning number
 to use. If you are generating your own warnings, make sure you don't
 use numbers defined in the table at the end of this section.</p>
<p> The <tt>%ignorewarn</tt> directive is the same as <tt>%ignore</tt>
 except that it issues a warning message whenever a matching declaration
 is found. For example:</p>
<div class="code">
<pre>
%ignorewarn(&quot;362:operator= ignored&quot;) operator=;
</pre>
</div>
<p> Warning messages can be associated with typemaps using the <tt>
warning</tt> attribute of a typemap declaration. For example:</p>
<div class="code">
<pre>
%typemap(in, warning=&quot;901:You are really going to regret this usage of $1_type $1_name&quot;) blah * {
  ...
}
</pre>
</div>
<p> In this case, the warning message will be printed whenever the
 typemap is actually used and the <a href="#Typemaps_special_variables">
special variables</a> will be expanded as appropriate, for example:</p>
<div class="shell">
<pre>
example.i:23: Warning 901: You are really going to regret this usage of blah * self
example.i:24: Warning 901: You are really going to regret this usage of blah * stuff
</pre>
</div>
<h2><a name="Warnings_symbolic_symbols">18.5 Symbolic symbols</a></h2>
<p> The <tt>swigwarn.swg</tt> file that is installed with SWIG contains
 symbol constants that could also be used in <tt>%warnfilter</tt> and <tt>
#pragma SWIG nowarn</tt>. For example this file contains the following
 line:</p>
<div class="code">
<pre>
%define SWIGWARN_TYPE_UNDEFINED_CLASS 401 %enddef
</pre>
</div>
<p> so <tt>SWIGWARN_TYPE_UNDEFINED_CLASS</tt> could be used instead of
 401, for example:</p>
<div class="code">
<pre>
#pragma SWIG nowarn=SWIGWARN_TYPE_UNDEFINED_CLASS
</pre>
</div>
<p> or</p>
<div class="code">
<pre>
%warnfilter(SWIGWARN_TYPE_UNDEFINED_CLASS) Foo;
</pre>
</div>
<h2><a name="Warnings_nn6">18.6 Commentary</a></h2>
<p> The ability to suppress warning messages is really only provided for
 advanced users and is not recommended in normal use. You are advised to
 modify your interface to fix the problems highlighted by the warnings
 wherever possible instead of suppressing warnings.</p>
<p> Certain types of SWIG problems are errors. These usually arise due
 to parsing errors (bad syntax) or semantic problems for which there is
 no obvious recovery. There is no mechanism for suppressing error
 messages.</p>
<h2><a name="Warnings_nn7">18.7 Warnings as errors</a></h2>
<p> Warnings can be handled as errors by using the <tt>-Werror</tt>
 command line option. This will cause SWIG to exit with a non successful
 exit code if a warning is encountered.</p>
<h2><a name="Warnings_nn8">18.8 Message output format</a></h2>
<p> The output format for both warnings and errors can be selected for
 integration with your favourite IDE/editor. Editors and IDEs can
 usually parse error messages and if in the appropriate format will
 easily take you directly to the source of the error. The standard
 format is used by default except on Windows where the Microsoft format
 is used by default. These can be overridden using command line options,
 for example:</p>
<div class="shell">
<pre>
$ swig -python -Fstandard example.i
example.i:4: Syntax error in input(1).
$ swig -python -Fmicrosoft example.i
example.i(4) : Syntax error in input(1).
</pre>
</div>
<h2><a name="Warnings_nn9">18.9 Warning number reference</a></h2>
<h3><a name="Warnings_nn10">18.9.1 Deprecated features (100-199)</a></h3>
<ul>
<li>101. Deprecated <tt>%extern</tt> directive.</li>
<li>102. Deprecated <tt>%val</tt> directive.</li>
<li>103. Deprecated <tt>%out</tt> directive.</li>
<li>104. Deprecated <tt>%disabledoc</tt> directive.</li>
<li>105. Deprecated <tt>%enabledoc</tt> directive.</li>
<li>106. Deprecated <tt>%doconly</tt> directive.</li>
<li>107. Deprecated <tt>%style</tt> directive.</li>
<li>108. Deprecated <tt>%localstyle</tt> directive.</li>
<li>109. Deprecated <tt>%title</tt> directive.</li>
<li>110. Deprecated <tt>%section</tt> directive.</li>
<li>111. Deprecated <tt>%subsection</tt> directive.</li>
<li>112. Deprecated <tt>%subsubsection</tt> directive.</li>
<li>113. Deprecated <tt>%addmethods</tt> directive.</li>
<li>114. Deprecated <tt>%readonly</tt> directive.</li>
<li>115. Deprecated <tt>%readwrite</tt> directive.</li>
<li>116. Deprecated <tt>%except</tt> directive.</li>
<li>117. Deprecated <tt>%new</tt> directive.</li>
<li>118. Deprecated <tt>%typemap(except)</tt>.</li>
<li>119. Deprecated <tt>%typemap(ignore)</tt>.</li>
<li>120. Deprecated command line option (-runtime, -noruntime).</li>
<li>121. Deprecated <tt>%name</tt> directive.</li>
<li>126. The 'nestedworkaround' feature is deprecated.</li>
</ul>
<h3><a name="Warnings_nn11">18.9.2 Preprocessor (200-299)</a></h3>
<ul>
<li>201. Unable to find<em> filename</em>.</li>
<li>202. Could not evaluate expression<em> expr</em>.</li>
<li>203. Both includeall and importall are defined: using includeall.</li>
<li>204. CPP #warning, &quot;<em>warning</em>&quot;.</li>
<li>205. CPP #error, &quot;<em>error</em>&quot;.</li>
<li>206. Unexpected tokens after #<em>directive</em> directive.</li>
</ul>
<h3><a name="Warnings_nn12">18.9.3 C/C++ Parser (300-399)</a></h3>
<ul>
<li>301. <tt>class</tt> keyword used, but not in C++ mode.</li>
<li>302. Identifier '<em>name</em>' redefined (ignored).</li>
<li>303. <tt>%extend</tt> defined for an undeclared class '<em>name</em>
'.</li>
<li>304. Unsupported constant value (ignored).</li>
<li>305. Bad constant value (ignored).</li>
<li>306. '<em>identifier</em>' is private in this context.</li>
<li>307. Can't set default argument value (ignored)</li>
<li>308. Namespace alias '<em>name</em>' not allowed here. Assuming '<em>
name</em>'</li>
<li>309. [private | protected] inheritance ignored.</li>
<li>310. Template '<em>name</em>' was already wrapped as '<em>name</em>'
 (ignored)</li>
<li>312. Unnamed nested class not currently supported (ignored).</li>
<li>313. Unrecognized extern type &quot;<em>name</em>&quot; (ignored).</li>
<li>314. '<em>identifier</em>' is a<em> lang</em> keyword.</li>
<li>315. Nothing known about '<em>identifier</em>'.</li>
<li>316. Repeated %module directive.</li>
<li>317. Specialization of non-template '<em>name</em>'.</li>
<li>318. Instantiation of template '<em>name</em>' is ambiguous,
 instantiation<em> templ</em> used, instantiation<em> templ</em>
 ignored.</li>
<li>319. No access specifier given for base class<em> name</em>
 (ignored).</li>
<li>320. Explicit template instantiation ignored.</li>
<li>321.<em> identifier</em> conflicts with a built-in name.</li>
<li>322. Redundant redeclaration of '<em>name</em>'.</li>
<li>323. Recursive scope inheritance of '<em>name</em>'.</li>
<li>324. Named nested template instantiations not supported. Processing
 as if no name was given to %template().</li>
<li>325. Nested<em> kind</em> not currently supported (<em>name</em>
 ignored).</li>
<li>326. Deprecated %extend name used - the<em> kind</em> name '<em>name</em>
' should be used instead of the typedef name '<em>name</em>'.</li>
<li>350. operator new ignored.</li>
<li>351. operator delete ignored.</li>
<li>352. operator+ ignored.</li>
<li>353. operator- ignored.</li>
<li>354. operator* ignored.</li>
<li>355. operator/ ignored.</li>
<li>356. operator% ignored.</li>
<li>357. operator^ ignored.</li>
<li>358. operator&amp; ignored.</li>
<li>359. operator| ignored.</li>
<li>360. operator~ ignored.</li>
<li>361. operator! ignored.</li>
<li>362. operator= ignored.</li>
<li>363. operator&lt; ignored.</li>
<li>364. operator&gt; ignored.</li>
<li>365. operator+= ignored.</li>
<li>366. operator-= ignored.</li>
<li>367. operator*= ignored.</li>
<li>368. operator/= ignored.</li>
<li>369. operator%= ignored.</li>
<li>370. operator^= ignored.</li>
<li>371. operator&amp;= ignored.</li>
<li>372. operator|= ignored.</li>
<li>373. operator&lt;&lt; ignored.</li>
<li>374. operator&gt;&gt;ignored.</li>
<li>375. operator&lt;&lt;= ignored.</li>
<li>376. operator&gt;&gt;= ignored.</li>
<li>377. operator== ignored.</li>
<li>378. operator!= ignored.</li>
<li>379. operator&lt;= ignored.</li>
<li>380. operator&gt;= ignored.</li>
<li>381. operator&amp;&amp; ignored.</li>
<li>382. operator|| ignored.</li>
<li>383. operator++ ignored.</li>
<li>384. operator-- ignored.</li>
<li>385. operator, ignored.</li>
<li>386. operator-&lt;* ignored.</li>
<li>387. operator-&lt; ignored.</li>
<li>388. operator() ignored.</li>
<li>389. operator[] ignored.</li>
<li>390. operator+ ignored (unary).</li>
<li>391. operator- ignored (unary).</li>
<li>392. operator* ignored (unary).</li>
<li>393. operator&amp; ignored (unary).</li>
<li>394. operator new[] ignored.</li>
<li>395. operator delete[] ignored.</li>
</ul>
<h3><a name="Warnings_nn13">18.9.4 Types and typemaps (400-499)</a></h3>
<ul>
<li>401. Nothing known about class 'name'. Ignored.</li>
<li>402. Base class 'name' is incomplete.</li>
<li>403. Class 'name' might be abstract.</li>
<li>450. Deprecated typemap feature ($source/$target).</li>
<li>451. Setting const char * variable may leak memory.</li>
<li>452. Reserved</li>
<li>453. Can't apply (pattern). No typemaps are defined.</li>
<li>460. Unable to use type<em> type</em> as a function argument.</li>
<li>461. Unable to use return type<em> type</em> in function<em> name</em>
.</li>
<li>462. Unable to set variable of type<em> type</em>.</li>
<li>463. Unable to read variable of type<em> type</em>.</li>
<li>464. Unsupported constant value.</li>
<li>465. Unable to handle type<em> type</em>.</li>
<li>466. Unsupported variable type<em> type</em>.</li>
<li>467. Overloaded<em> declaration</em> not supported (incomplete type
 checking rule - no precedence level in typecheck typemap for '<em>type</em>
')</li>
<li>468. No 'throw' typemap defined for exception type<em> type</em></li>
<li>469. No or improper directorin typemap defined for<em> type</em></li>
<li>470. Thread/reentrant unsafe wrapping, consider returning by value
 instead.</li>
<li>471. Unable to use return type<em> type</em> in director method</li>
<li>474. Method<em> method</em> usage of the optimal attribute ignored
 in the out typemap as the following cannot be used to generate optimal
 code:<em> code</em></li>
<li>475. Multiple calls to<em> method</em> might be generated due to
 optimal attribute usage in the out typemap.</li>
<li>476. Initialization using std::initializer_list.</li>
<li>477. No directorthrows typemap defined for<em> type</em></li>
</ul>
<h3><a name="Warnings_nn14">18.9.5 Code generation (500-559)</a></h3>
<ul>
<li>501. Overloaded declaration ignored.<em> decl</em>. Previous
 declaration is<em> decl</em>.</li>
<li>502. Overloaded constructor ignored.<em> decl</em>. Previous
 declaration is<em> decl</em>.</li>
<li>503. Can't wrap '<em>identifier</em>' unless renamed to a valid
 identifier.</li>
<li>504. Function<em> name</em> must have a return type. Ignored.</li>
<li>505. Variable length arguments discarded.</li>
<li>506. Can't wrap varargs with keyword arguments enabled.</li>
<li>507. Adding native function<em> name</em> not supported (ignored).</li>
<li>508. Declaration of '<em>name</em>' shadows declaration accessible
 via operator-&gt;(), previous declaration of'<em>declaration</em>'.</li>
<li>509. Overloaded method<em> declaration</em> effectively ignored, as
 it is shadowed by<em> declaration</em>.</li>
<li>510. Friend function '<em>name</em>' ignored.</li>
<li>511. Can't use keyword arguments with overloaded functions.</li>
<li>512. Overloaded method<em> declaration</em> ignored, using non-const
 method<em> declaration</em> instead.</li>
<li>513. Can't generate wrappers for unnamed struct/class.</li>
<li>514.</li>
<li>515.</li>
<li>516. Overloaded method<em> declaration</em> ignored, using<em>
 declaration</em> instead.</li>
<li>517.</li>
<li>518. Portability warning: File<em> file1</em> will be overwritten by<em>
 file2</em> on case insensitive filesystems such as Windows' FAT32 and
 NTFS unless the class/module name is renamed.</li>
<li>519. %template() contains no name. Template method ignored:<em>
 declaration</em></li>
<li>520.<em> Base/Derived</em> class '<em>classname1</em>' of '<em>
classname2</em>' is not similarly marked as a smart pointer.</li>
<li>521. Illegal destructor name<em> name</em>. Ignored.</li>
<li>522. Use of an illegal constructor name '<em>name</em>' in %extend
 is deprecated, the constructor name should be '<em>name</em>'.</li>
<li>523. Use of an illegal destructor name '<em>name</em>' in %extend is
 deprecated, the destructor name should be '<em>name</em>'.</li>
<li>524. Experimental target language. Target language<em> language</em>
 specified by<em> lang</em> is an experimental language. Please read
 about SWIG experimental languages,<em> htmllink</em>.</li>
<li>525. Destructor<em> declaration</em> is final,<em> name</em> cannot
 be a director class.</li>
</ul>
<h3><a name="Warnings_doxygen">18.9.6 Doxygen comments (560-599)</a></h3>
<ul>
<li>560: Unknown Doxygen command:<em> command</em>.</li>
<li>561: Unexpected end of Doxygen comment encountered.</li>
<li>562: Expected Doxygen command:<em> command</em></li>
<li>563: Doxygen HTML error for tag<em> tag</em>:<em> error text</em>.</li>
<li>564: Error parsing Doxygen command<em> command</em>:<em> error text</em>
. Command ignored.&quot;</li>
</ul>
<h3><a name="Warnings_nn15">18.9.7 Language module specific (700-899)</a>
</h3>
<ul>
<li>801. Wrong name (corrected to '<em>name</em>'). (Ruby).</li>
</ul>
<ul>
<li>810. No jni typemap defined for<em> type</em> (Java).</li>
<li>811. No jtype typemap defined for<em> type</em> (Java).</li>
<li>812. No jstype typemap defined for<em> type</em> (Java).</li>
<li>813. Warning for<em> classname</em>, base<em> baseclass</em>
 ignored. Multiple inheritance is not supported in Java. (Java).</li>
<li>814.</li>
<li>815. No javafinalize typemap defined for<em> type</em> (Java).</li>
<li>816. No javabody typemap defined for<em> type</em> (Java).</li>
<li>817. No javaout typemap defined for<em> type</em> (Java).</li>
<li>818. No javain typemap defined for<em> type</em> (Java).</li>
<li>819. No javadirectorin typemap defined for<em> type</em> (Java).</li>
<li>820. No javadirectorout typemap defined for<em> type</em> (Java).</li>
<li>821.</li>
<li>822. Covariant return types not supported in Java. Proxy method will
 return<em> basetype</em> (Java).</li>
<li>823. No javaconstruct typemap defined for<em> type</em> (Java).</li>
<li>824. Missing JNI descriptor in directorin typemap defined for<em>
 type</em> (Java).</li>
<li>825. &quot;directorconnect&quot; attribute missing in<em> type</em>
 &quot;javaconstruct&quot; typemap. (Java).</li>
<li>826. The nspace feature is used on '<em>type</em>' without -package.
 The generated code may not compile as Java does not support types
 declared in a named package accessing types declared in an unnamed
 package. (Java).</li>
</ul>
<ul>
<li>830. No ctype typemap defined for<em> type</em> (C#).</li>
<li>831. No cstype typemap defined for<em> type</em> (C#).</li>
<li>832. No cswtype typemap defined for<em> type</em> (C#).</li>
<li>833. Warning for<em> classname</em>, base<em> baseclass</em>
 ignored. Multiple inheritance is not supported in C#. (C#).</li>
<li>834.</li>
<li>835. No csfinalize typemap defined for<em> type</em> (C#).</li>
<li>836. No csbody typemap defined for<em> type</em> (C#).</li>
<li>837. No csout typemap defined for<em> type</em> (C#).</li>
<li>838. No csin typemap defined for<em> type</em> (C#).</li>
<li>839.</li>
<li>840.</li>
<li>841.</li>
<li>842. Covariant return types not supported in C#. Proxy method will
 return<em> basetype</em> (C#).</li>
<li>843. No csconstruct typemap defined for<em> type</em> (C#).</li>
<li>844. C# exception may not be thrown - no $excode or excode attribute
 in<em> typemap</em> typemap. (C#).</li>
<li>845. Unmanaged code contains a call to a
 SWIG_CSharpSetPendingException method and C# code does not handle
 pending exceptions via the canthrow attribute. (C#).</li>
</ul>
<ul>
<li>870. Warning for<em> classname</em>: Base<em> baseclass</em>
 ignored. Multiple inheritance is not supported in PHP. (Php).</li>
<li>871. Unrecognized pragma<em> pragma</em>. (Php).</li>
</ul>
<h3><a name="Warnings_nn16">18.9.8 User defined (900-999)</a></h3>
<p> These numbers can be used by your own application.</p>
<h2><a name="Warnings_nn17">18.10 History</a></h2>
<p> The ability to control warning messages was first added to
 SWIG-1.3.12.</p>
<HR NOSHADE>
<h1><a name="Modules">19 Working with Modules</a></h1>

<!-- INDEX -->
<div class="sectiontoc">
<ul>
<li><a href="#Modules_introduction">Modules Introduction</a></li>
<li><a href="#Modules_nn1">Basics</a></li>
<li><a href="#Modules_nn2">The SWIG runtime code</a></li>
<li><a href="#Modules_external_run_time">External access to the runtime</a>
</li>
<li><a href="#Modules_nn4">A word of caution about static libraries</a></li>
<li><a href="#Modules_nn5">References</a></li>
<li><a href="#Modules_nn6">Reducing the wrapper file size</a></li>
</ul>
</div>
<!-- INDEX -->
<h2><a name="Modules_introduction">19.1 Modules Introduction</a></h2>
<p> Each invocation of SWIG requires a module name to be specified. The
 module name is used to name the resulting target language extension
 module. Exactly what this means and what the name is used for depends
 on the target language, for example the name can define a target
 language namespace or merely be a useful name for naming files or
 helper classes. Essentially, a module comprises target language
 wrappers for a chosen collection of global variables/functions,
 structs/classes and other C/C++ types.</p>
<p> The module name can be supplied in one of two ways. The first is to
 specify it with the special <tt>%module</tt> directive. This directive
 must appear at the beginning of the interface file. The general form of
 this directive is:</p>
<div class="code">
<pre>
<tt>%module(option1=&quot;value1&quot;, option2=&quot;value2&quot;, ...) modulename</tt>
</pre>
</div>
<p> where the modulename is mandatory and the options add one or more
 optional additional features. Typically no options are specified, for
 example:</p>
<div class="code">
<pre>
<tt>%module mymodule</tt>
</pre>
</div>
<p> The second way to specify the module name is with the <tt>-module</tt>
 command line option, for example <tt>-module mymodule</tt>. If the
 module name is supplied on the command line, it overrides the name
 specified by the <tt>%module</tt> directive.</p>
<p> When first working with SWIG, users commonly start by creating a
 single module. That is, you might define a single SWIG interface that
 wraps some set of C/C++ code. You then compile all of the generated
 wrapper code together and use it. For large applications, however, this
 approach is problematic---the size of the generated wrapper code can be
 rather large. Moreover, it is probably easier to manage the target
 language interface when it is broken up into smaller pieces.</p>
<p> This chapter describes the problem of using SWIG in programs where
 you want to create a collection of modules. Each module in the
 collection is created via separate invocations of SWIG.</p>
<h2><a name="Modules_nn1">19.2 Basics</a></h2>
<p> The basic usage case with multiple modules is when modules do not
 have cross-references (ie. when wrapping multiple independent C APIs).
 In that case, swig input files should just work out of the box - you
 simply create multiple wrapper .cxx files, link them into your
 application, and insert/load each in the scripting language runtime as
 you would do for the single module case.</p>
<p> A bit more complex is the case in which modules need to share
 information. For example, when one module extends the class of another
 by deriving from it:</p>
<div class="code">
<pre>
// File: base.h
class base {
public:
  int foo();
};
</pre>
</div> &nbsp;<div class="code">
<pre>
// File: base_module.i
%module base_module

%{
#include &quot;base.h&quot;
%}
%include &quot;base.h&quot;
</pre>
</div> &nbsp;<div class="code">
<pre>
// File: derived_module.i
%module derived_module

%import &quot;base_module.i&quot;

%inline %{
class derived : public base {
public:
  int bar();
};
%}
</pre>
</div>
<p>To create the wrapper properly, module <tt>derived_module</tt> needs
 to know about the <tt>base</tt> class and that its interface is covered
 in another module. The line <tt>%import &quot;base_module.i&quot;</tt> lets SWIG
 know exactly that. Often the <tt>.h</tt> file is passed to <tt>%import</tt>
 instead of the <tt>.i</tt>, which unfortunately doesn't work for all
 language modules. For example, Python requires the name of module that
 the base class exists in so that the proxy classes can fully inherit
 the base class's methods. Typically you will get a warning when the
 module name is missing, eg:</p>
<div class="shell">
<pre>
derived_module.i:8: Warning 401: Base class 'base' ignored - unknown module name for base. Either
import
the appropriate module interface file or specify the name of the module in the %import directive.
</pre>
</div>
<p> It is sometimes desirable to import the header file rather than the
 interface file and overcome the above warning. For example in the case
 of the imported interface being quite large, it may be desirable to
 simplify matters and just import a small header file of dependent
 types. This can be done by specifying the optional <tt>module</tt>
 attribute in the <tt>%import</tt> directive. The <tt>derived_module.i</tt>
 file shown above could be replaced with the following:<div class="code">
<pre>
// File: derived_module.i
%module derived_module

%import(module=&quot;base_module&quot;) &quot;base.h&quot;

%inline %{
class derived : public base {
public:
  int bar();
};
</pre>
</div></p>
<p> Note that &quot;base_module&quot; is the module name and is the same as that
 specified in <tt>%module</tt> in <tt>base_module.i</tt> as well as the <tt>
%import</tt> in <tt>derived_module.i</tt>.</p>
<p> Another issue to beware of is that multiple dependent wrappers
 should not be linked/loaded in parallel from multiple threads as SWIG
 provides no locking - for more on that issue, read on.</p>
<h2><a name="Modules_nn2">19.3 The SWIG runtime code</a></h2>
<p> Many of SWIG's target languages generate a set of functions commonly
 known as the &quot;SWIG runtime.&quot; These functions are primarily related to
 the runtime type system which checks pointer types and performs other
 tasks such as proper casting of pointer values in C++. As a general
 rule, the statically typed target languages, such as Java, use the
 language's built in static type checking and have no need for a SWIG
 runtime. All the dynamically typed / interpreted languages rely on the
 SWIG runtime.</p>
<p> The runtime functions are private to each SWIG-generated module.
 That is, the runtime functions are declared with &quot;static&quot; linkage and
 are visible only to the wrapper functions defined in that module. The
 only problem with this approach is that when more than one SWIG module
 is used in the same application, those modules often need to share type
 information. This is especially true for C++ programs where SWIG must
 collect and share information about inheritance relationships that
 cross module boundaries.</p>
<p> To solve the problem of sharing information across modules, a
 pointer to the type information is stored in a global variable in the
 target language namespace. During module initialization, type
 information is loaded into the global data structure of type
 information from all modules.</p>
<p> There are a few trade offs with this approach. This type information
 is global across all SWIG modules loaded, and can cause type conflicts
 between modules that were not designed to work together. To solve this
 approach, the SWIG runtime code uses a define SWIG_TYPE_TABLE to
 provide a unique type table. This behavior can be enabled when
 compiling the generated _wrap.cxx or _wrap.c file by adding
 -DSWIG_TYPE_TABLE=myprojectname to the command line argument.</p>
<p> Then, only modules compiled with SWIG_TYPE_TABLE set to
 myprojectname will share type information. So if your project has three
 modules, all three should be compiled with
 -DSWIG_TYPE_TABLE=myprojectname, and then these three modules will
 share type information. But any other project's types will not
 interfere or clash with the types in your module.</p>
<p> Another issue relating to the global type table is thread safety. If
 two modules try and load at the same time, the type information can
 become corrupt. SWIG currently does not provide any locking, and if you
 use threads, you must make sure that modules are loaded serially. Be
 careful if you use threads and the automatic module loading that some
 scripting languages provide. One solution is to load all modules before
 spawning any threads, or use SWIG_TYPE_TABLE to separate type tables so
 they do not clash with each other.</p>
<p> Lastly, SWIG uses a #define SWIG_RUNTIME_VERSION, located in
 Lib/swigrun.swg and near the top of every generated module. This number
 gets incremented when the data structures change, so that SWIG modules
 generated with different versions can peacefully coexist. So the type
 structures are separated by the (SWIG_TYPE_TABLE, SWIG_RUNTIME_VERSION)
 pair, where by default SWIG_TYPE_TABLE is empty. Only modules compiled
 with the same pair will share type information.</p>
<h2><a name="Modules_external_run_time">19.4 External access to the
 runtime</a></h2>
<p>As described in <a href="#Typemaps_runtime_type_checker">The run-time
 type checker</a>, the functions <tt>SWIG_TypeQuery</tt>, <tt>
SWIG_NewPointerObj</tt>, and others sometimes need to be called. Calling
 these functions from a typemap is supported, since the typemap code is
 embedded into the <tt>_wrap.c</tt> file, which has those declarations
 available. If you need to call the SWIG run-time functions from another
 C file, there is one header you need to include. To generate the header
 that needs to be included, SWIG can be run in a different mode via <tt>
-external-runtime</tt> to generate the run-time instead of the normal
 mode of processing an input interface file. For example:<div class="shell">
<pre>
$ swig -python -external-runtime &lt;filename&gt;
</pre>
</div></p>
<p>The filename argument is optional and if it is not passed, then the
 default filename will be something like <tt>swigpyrun.h</tt>, depending
 on the language. This header file should be treated like any of the
 other _wrap.c output files, and should be regenerated when the _wrap
 files are. After including this header, your code will be able to call <tt>
SWIG_TypeQuery</tt>, <tt>SWIG_NewPointerObj</tt>, <tt>SWIG_ConvertPtr</tt>
 and others. The exact argument parameters for these functions might
 differ between language modules; please check the language module
 chapters for more information.</p>
<p>Inside this header the functions are declared static and are included
 inline into the file, and thus the file does not need to be linked
 against any SWIG libraries or code (you might still need to link
 against the language libraries like libpython-2.3). Data is shared
 between this file and the _wrap.c files through a global variable in
 the scripting language. It is also possible to copy this header file
 along with the generated wrapper files into your own package, so that
 you can distribute a package that can be compiled without SWIG
 installed (this works because the header file is self-contained, and
 does not need to link with anything).</p>
<p> This header will also use the -DSWIG_TYPE_TABLE described above, so
 when compiling any code which includes the generated header file should
 define the SWIG_TYPE_TABLE to be the same as the module whose types you
 are trying to access.</p>
<h2><a name="Modules_nn4">19.5 A word of caution about static libraries</a>
</h2>
<p> When working with multiple SWIG modules, you should take care not to
 use static libraries. For example, if you have a static library <tt>
libfoo.a</tt> and you link a collection of SWIG modules with that
 library, each module will get its own private copy of the library code
 inserted into it. This is very often<b> NOT</b> what you want and it
 can lead to unexpected or bizarre program behavior. When working with
 dynamically loadable modules, you should try to work exclusively with
 shared libraries.</p>
<h2><a name="Modules_nn5">19.6 References</a></h2>
<p> Due to the complexity of working with shared libraries and multiple
 modules, it might be a good idea to consult an outside reference. John
 Levine's &quot;Linkers and Loaders&quot; is highly recommended.</p>
<h2><a name="Modules_nn6">19.7 Reducing the wrapper file size</a></h2>
<p> Using multiple modules with the <tt>%import</tt> directive is the
 most common approach to modularising large projects. In this way a
 number of different wrapper files can be generated, thereby avoiding
 the generation of a single large wrapper file. There are a couple of
 alternative solutions for reducing the size of a wrapper file through
 the use of command line options and features.</p>
<p><b> -fcompact</b>
<br> This command line option will compact the size of the wrapper file
 without changing the code generated into the wrapper file. It simply
 removes blank lines and joins lines of code together. This is useful
 for compilers that have a maximum file size that can be handled.</p>
<p><b> -fvirtual</b>
<br> This command line option will remove the generation of superfluous
 virtual method wrappers. Consider the following inheritance hierarchy:</p>
<div class="code">
<pre>
struct Base {
  virtual void method();
  ...
};

struct Derived : Base {
  virtual void method();
  ...
};
</pre>
</div>
<p> Normally wrappers are generated for both methods, whereas this
 command line option will suppress the generation of a wrapper for <tt>
Derived::method</tt>. Normal polymorphic behaviour remains as <tt>
Derived::method</tt> will still be called should you have a <tt>Derived</tt>
 instance and call the wrapper for <tt>Base::method</tt>.</p>
<p><b> %feature(&quot;compactdefaultargs&quot;)</b>
<br> This feature can reduce the number of wrapper methods when wrapping
 methods with default arguments. The section on <a href="#SWIGPlus_default_args">
default arguments</a> discusses the feature and its limitations.</p>
<HR NOSHADE>
<h1><a name="CCache">20 Using SWIG with ccache - ccache-swig(1) manpage</a>
</h1>

<!-- INDEX -->
<div class="sectiontoc">
<ul>
<li><a href="#CCache_nn2">NAME</a></li>
<li><a href="#CCache_nn3">SYNOPSIS</a></li>
<li><a href="#CCache_nn4">DESCRIPTION</a></li>
<li><a href="#CCache_nn5">OPTIONS SUMMARY</a></li>
<li><a href="#CCache_nn6">OPTIONS</a></li>
<li><a href="#CCache_nn7">INSTALLATION</a></li>
<li><a href="#CCache_nn8">EXTRA OPTIONS</a></li>
<li><a href="#CCache_nn9">ENVIRONMENT VARIABLES</a></li>
<li><a href="#CCache_nn10">CACHE SIZE MANAGEMENT</a></li>
<li><a href="#CCache_nn11">CACHE COMPRESSION</a></li>
<li><a href="#CCache_nn12">HOW IT WORKS</a></li>
<li><a href="#CCache_nn13">USING CCACHE WITH DISTCC</a></li>
<li><a href="#CCache_nn14">SHARING A CACHE</a></li>
<li><a href="#CCache_nn15">HISTORY</a></li>
<li><a href="#CCache_nn16">DIFFERENCES FROM COMPILERCACHE</a></li>
<li><a href="#CCache_nn17">CREDITS</a></li>
<li><a href="#CCache_nn18">AUTHOR</a></li>
</ul>
</div>
<!-- INDEX -->
<p></p>
<h2><a name="CCache_nn2">20.1 NAME</a></h2>
<p> ccache-swig - a fast compiler cache</p>
<p></p>
<h2><a name="CCache_nn3">20.2 SYNOPSIS</a></h2>
<p> ccache-swig [OPTION]</p>
<p> ccache-swig &lt;compiler&gt; [COMPILER OPTIONS]</p>
<p> &lt;compiler&gt; [COMPILER OPTIONS]</p>
<p></p>
<h2><a name="CCache_nn4">20.3 DESCRIPTION</a></h2>
<p> ccache-swig is a compiler cache. It speeds up re-compilation of
 C/C++/SWIG code by caching previous compiles and detecting when the
 same compile is being done again. ccache-swig is ccache plus support
 for SWIG. ccache and ccache-swig are used interchangeably in this
 document.</p>
<p></p>
<h2><a name="CCache_nn5">20.4 OPTIONS SUMMARY</a></h2>
<p> Here is a summary of the options to ccache-swig.</p>
<p></p>
<pre>

-s                      show statistics summary
-z                      zero statistics
-c                      run a cache cleanup
-C                      clear the cache completely
-F &lt;n&gt;                  set maximum files in cache
-M &lt;n&gt;                  set maximum size of cache (use G, M or K)
-h                      this help page
-V                      print version number

</pre>
<p></p>
<h2><a name="CCache_nn6">20.5 OPTIONS</a></h2>
<p> These options only apply when you invoke ccache as &quot;ccache-swig&quot;.
 When invoked as a compiler none of these options apply. In that case
 your normal compiler options apply and you should refer to your
 compilers documentation.</p>
<p></p>
<dl>
<p>
<dt><strong><strong>-h</strong></strong></dt>
<dd> Print a options summary page
<p></p>
<p></p>
</dd>
<dt><strong><strong>-s</strong></strong></dt>
<dd> Print the current statistics summary for the cache. The statistics
 are stored spread across the subdirectories of the cache. Using
 &quot;ccache-swig -s&quot; adds up the statistics across all subdirectories and
 prints the totals.
<p></p>
<p></p>
</dd>
<dt><strong><strong>-z</strong></strong></dt>
<dd> Zero the cache statistics.
<p></p>
<p></p>
</dd>
<dt><strong><strong>-V</strong></strong></dt>
<dd> Print the ccache version number
<p></p>
<p></p>
</dd>
<dt><strong><strong>-c</strong></strong></dt>
<dd> Clean the cache and re-calculate the cache file count and size
 totals. Normally the -c option should not be necessary as ccache keeps
 the cache below the specified limits at runtime and keeps statistics up
 to date on each compile. This option is mostly useful if you manually
 modify the cache contents or believe that the cache size statistics may
 be inaccurate.
<p></p>
<p></p>
</dd>
<dt><strong><strong>-C</strong></strong></dt>
<dd> Clear the entire cache, removing all cached files.
<p></p>
<p></p>
</dd>
<dt><strong><strong>-F &lt;maxfiles&gt;</strong></strong></dt>
<dd> This sets the maximum number of files allowed in the cache. The
 value is stored inside the cache directory and applies to all future
 compiles. Due to the way the value is stored the actual value used is
 always rounded down to the nearest multiple of 16.
<p></p>
<p></p>
</dd>
<dt><strong><strong>-M &lt;maxsize&gt;</strong></strong></dt>
<dd> This sets the maximum cache size. You can specify a value in
 gigabytes, megabytes or kilobytes by appending a G, M or K to the
 value. The default is gigabytes. The actual value stored is rounded
 down to the nearest multiple of 16 kilobytes.
<p></p>
</dd>
</p>
</dl>
<p></p>
<h2><a name="CCache_nn7">20.6 INSTALLATION</a></h2>
<p> There are two ways to use ccache. You can either prefix your compile
 commands with &quot;ccache-swig&quot; or you can create a symbolic link between
 ccache-swig and the names of your compilers. The first method is most
 convenient if you just want to try out ccache or wish to use it for
 some specific projects. The second method is most useful for when you
 wish to use ccache for all your compiles.</p>
<p> To install for usage by the first method just copy ccache-swig to
 somewhere in your path.</p>
<p> To install for the second method do something like this:</p>
<pre>

  cp ccache-swig /usr/local/bin/
  ln -s /usr/local/bin/ccache-swig /usr/local/bin/gcc
  ln -s /usr/local/bin/ccache-swig /usr/local/bin/g++
  ln -s /usr/local/bin/ccache-swig /usr/local/bin/cc
  ln -s /usr/local/bin/ccache-swig /usr/local/bin/swig

</pre>
 This will work as long as /usr/local/bin comes before the path to gcc
 (which is usually in /usr/bin). After installing you may wish to run
 &quot;which gcc&quot; to make sure that the correct link is being used.
<p> Note! Do not use a hard link, use a symbolic link. A hardlink will
 cause &quot;interesting&quot; problems.</p>
<p></p>
<h2><a name="CCache_nn8">20.7 EXTRA OPTIONS</a></h2>
<p> When run as a compiler front end ccache usually just takes the same
 command line options as the compiler you are using. The only exception
 to this is the option '--ccache-skip'. That option can be used to tell
 ccache that the next option is definitely not a input filename, and
 should be passed along to the compiler as-is.</p>
<p> The reason this can be important is that ccache does need to parse
 the command line and determine what is an input filename and what is a
 compiler option, as it needs the input filename to determine the name
 of the resulting object file (among other things). The heuristic ccache
 uses in this parse is that any string on the command line that exists
 as a file is treated as an input file name (usually a C file). By using
 --ccache-skip you can force an option to not be treated as an input
 file name and instead be passed along to the compiler as a command line
 option.</p>
<p></p>
<h2><a name="CCache_nn9">20.8 ENVIRONMENT VARIABLES</a></h2>
<p> ccache uses a number of environment variables to control operation.
 In most cases you won't need any of these as the defaults will be fine.</p>
<p></p>
<dl>
<p></p>
<p>
<dt><strong><strong>CCACHE_DIR</strong></strong></dt>
<dd> the CCACHE_DIR environment variable specifies where ccache will
 keep its cached compiler output. The default is &quot;$HOME/.ccache&quot;.
<p></p>
<p></p>
</dd>
<dt><strong><strong>CCACHE_TEMPDIR</strong></strong></dt>
<dd> the CCACHE_TEMPDIR environment variable specifies where ccache will
 put temporary files. The default is the same as CCACHE_DIR. Note that
 the CCACHE_TEMPDIR path must be on the same filesystem as the
 CCACHE_DIR path, so that renames of files between the two directories
 can work.
<p></p>
<p></p>
</dd>
<dt><strong><strong>CCACHE_LOGFILE</strong></strong></dt>
<dd> If you set the CCACHE_LOGFILE environment variable then ccache will
 write some log information on cache hits and misses in that file. This
 is useful for tracking down problems.
<p></p>
<p></p>
</dd>
<dt><strong><strong>CCACHE_VERBOSE</strong></strong></dt>
<dd> If you set the CCACHE_VERBOSE environment variable then ccache will
 display on stdout all the compiler invocations that it makes. This can
 useful for debugging unexpected problems.
<p></p>
<p></p>
</dd>
<dt><strong><strong>CCACHE_PATH</strong></strong></dt>
<dd> You can optionally set CCACHE_PATH to a colon separated path where
 ccache will look for the real compilers. If you don't do this then
 ccache will look for the first executable matching the compiler name in
 the normal PATH that isn't a symbolic link to ccache itself.
<p></p>
<p></p>
</dd>
<dt><strong><strong>CCACHE_CC</strong></strong></dt>
<dd> You can optionally set CCACHE_CC to force the name of the compiler
 to use. If you don't do this then ccache works it out from the command
 line.
<p></p>
<p></p>
</dd>
<dt><strong><strong>CCACHE_PREFIX</strong></strong></dt>
<dd> This option adds a prefix to the command line that ccache runs when
 invoking the compiler. Also see the section below on using ccache with
 distcc.
<p></p>
<p></p>
</dd>
<dt><strong><strong>CCACHE_DISABLE</strong></strong></dt>
<dd> If you set the environment variable CCACHE_DISABLE then ccache will
 just call the real compiler, bypassing the cache completely.
<p></p>
<p></p>
</dd>
<dt><strong><strong>CCACHE_READONLY</strong></strong></dt>
<dd> the CCACHE_READONLY environment variable tells ccache to attempt to
 use existing cached object files, but not to try to add anything new to
 the cache. If you are using this because your CCACHE_DIR is read-only,
 then you may find that you also need to set CCACHE_TEMPDIR as otherwise
 ccache will fail to create the temporary files.
<p></p>
<p></p>
</dd>
<dt><strong><strong>CCACHE_CPP2</strong></strong></dt>
<dd> If you set the environment variable CCACHE_CPP2 then ccache will
 not use the optimisation of avoiding the 2nd call to the pre-processor
 by compiling the pre-processed output that was used for finding the
 hash in the case of a cache miss. This is primarily a debugging option,
 although it is possible that some unusual compilers will have problems
 with the intermediate filename extensions used in this optimisation, in
 which case this option could allow ccache to be used.
<p></p>
<p></p>
</dd>
<dt><strong><strong>CCACHE_NOCOMPRESS</strong></strong></dt>
<dd> If you set the environment variable CCACHE_NOCOMPRESS then there is
 no compression used on files that go into the cache. However, this
 setting has no effect on how files are retrieved from the cache,
 compressed results will still be usable.
<p></p>
<p></p>
</dd>
<dt><strong><strong>CCACHE_NOSTATS</strong></strong></dt>
<dd> If you set the environment variable CCACHE_NOSTATS then ccache will
 not update the statistics files on each compile.
<p></p>
<p></p>
</dd>
<dt><strong><strong>CCACHE_NLEVELS</strong></strong></dt>
<dd> The environment variable CCACHE_NLEVELS allows you to choose the
 number of levels of hash in the cache directory. The default is 2. The
 minimum is 1 and the maximum is 8.
<p></p>
<p></p>
</dd>
<dt><strong><strong>CCACHE_HARDLINK</strong></strong></dt>
<dd> If you set the environment variable CCACHE_HARDLINK then ccache
 will attempt to use hard links from the cache directory when creating
 the compiler output rather than using a file copy. Using hard links is
 faster, but can confuse programs like 'make' that rely on modification
 times. Hard links are never made for compressed cache files.
<p></p>
<p></p>
</dd>
<dt><strong><strong>CCACHE_RECACHE</strong></strong></dt>
<dd> This forces ccache to not use any cached results, even if it finds
 them. New results are still cached, but existing cache entries are
 ignored.
<p></p>
<p></p>
</dd>
<dt><strong><strong>CCACHE_UMASK</strong></strong></dt>
<dd> This sets the umask for ccache and all child processes (such as the
 compiler). This is mostly useful when you wish to share your cache with
 other users. Note that this also affects the file permissions set on
 the object files created from your compilations.
<p></p>
<p></p>
</dd>
<dt><strong><strong>CCACHE_HASHDIR</strong></strong></dt>
<dd> This tells ccache to hash the current working directory when
 calculating the hash that is used to distinguish two compiles. This
 prevents a problem with the storage of the current working directory in
 the debug info of a object file, which can lead ccache to give a cached
 object file that has the working directory in the debug info set
 incorrectly. This option is off by default as the incorrect setting of
 this debug info rarely causes problems. If you strike problems with gdb
 not using the correct directory then enable this option.
<p></p>
<p></p>
</dd>
<dt><strong><strong>CCACHE_UNIFY</strong></strong></dt>
<dd> If you set the environment variable CCACHE_UNIFY then ccache will
 use the C/C++ unifier when hashing the pre-processor output if -g is
 not used in the compile. The unifier is slower than a normal hash, so
 setting this environment variable loses a little bit of speed, but it
 means that ccache can take advantage of not recompiling when the
 changes to the source code consist of reformatting only. Note that
 using CCACHE_UNIFY changes the hash, so cached compiles with
 CCACHE_UNIFY set cannot be used when CCACHE_UNIFY is not set and vice
 versa. The reason the unifier is off by default is that it can give
 incorrect line number information in compiler warning messages.
<p></p>
<p></p>
</dd>
<dt><strong><strong>CCACHE_EXTENSION</strong></strong></dt>
<dd> Normally ccache tries to automatically determine the extension to
 use for intermediate C pre-processor files based on the type of file
 being compiled. Unfortunately this sometimes doesn't work, for example
 when using the aCC compiler on HP-UX. On systems like this you can use
 the CCACHE_EXTENSION option to override the default. On HP-UX set this
 environment variable to &quot;i&quot; if you use the aCC compiler.
<p></p>
<p></p>
</dd>
<dt><strong><strong>CCACHE_STRIPC</strong></strong></dt>
<dd> If you set the environment variable CCACHE_STRIPC then ccache will
 strip the -c option when invoking the preprocessor. This option is
 primarily for the Sun Workshop C++ compiler as without this option an
 unwarranted warning is displayed: CC: Warning: &quot;-E&quot; redefines product
 from &quot;object&quot; to &quot;source (stdout)&quot; when -E and -c is used together.
<p></p>
<p></p>
</dd>
<dt><strong><strong>CCACHE_SWIG</strong></strong></dt>
<dd> When using SWIG as the compiler and it does not have 'swig' in the
 executable name, then the CCACHE_SWIG environment variable needs to be
 set in order for ccache to work correctly with SWIG. The use of
 CCACHE_CPP2 is also recommended for SWIG due to some preprocessor
 quirks, however, use of CCACHE_CPP2 can often be skipped -- check your
 generated code with and without this option set. Known problems are
 using preprocessor directives within %inline blocks and the use of
 '#pragma SWIG'.
<p></p>
</dd>
</p>
</dl>
<p></p>
<h2><a name="CCache_nn10">20.9 CACHE SIZE MANAGEMENT</a></h2>
<p> By default ccache has a one gigabyte limit on the cache size and no
 maximum number of files. You can set a different limit using the
 &quot;ccache -M&quot; and &quot;ccache -F&quot; options, which set the size and number of
 files limits.</p>
<p> When these limits are reached ccache will reduce the cache to 20%
 below the numbers you specified in order to avoid doing the cache clean
 operation too often.</p>
<p></p>
<h2><a name="CCache_nn11">20.10 CACHE COMPRESSION</a></h2>
<p> By default on most platforms ccache will compress all files it puts
 into the cache using the zlib compression. While this involves a
 negligible performance slowdown, it significantly increases the number
 of files that fit in the cache. You can turn off compression setting
 the CCACHE_NOCOMPRESS environment variable.</p>
<p></p>
<h2><a name="CCache_nn12">20.11 HOW IT WORKS</a></h2>
<p> The basic idea is to detect when you are compiling exactly the same
 code a 2nd time and use the previously compiled output. You detect that
 it is the same code by forming a hash of:</p>
<p></p>
<ul>
<li> the pre-processor output from running the compiler with -E</li>
<li> the command line options</li>
<li> the real compilers size and modification time</li>
<li> any stderr output generated by the compiler</li>
</ul>
<p> These are hashed using md4 (a strong hash) and a cache file is
 formed based on that hash result. When the same compilation is done a
 second time ccache is able to supply the correct compiler output
 (including all warnings etc) from the cache.</p>
<p> ccache has been carefully written to always produce exactly the same
 compiler output that you would get without the cache. If you ever
 discover a case where ccache changes the output of your compiler then
 please let me know.</p>
<p></p>
<h2><a name="CCache_nn13">20.12 USING CCACHE WITH DISTCC</a></h2>
<p> distcc is a very useful program for distributing compilation across
 a range of compiler servers. It is often useful to combine distcc with
 ccache, so that compiles that are done are sped up by distcc, but that
 ccache avoids the compile completely where possible.</p>
<p> To use distcc with ccache I recommend using the CCACHE_PREFIX
 option. You just need to set the environment variable CCACHE_PREFIX to
 'distcc' and ccache will prefix the command line used with the compiler
 with the command 'distcc'.</p>
<p></p>
<h2><a name="CCache_nn14">20.13 SHARING A CACHE</a></h2>
<p> A group of developers can increase the cache hit rate by sharing a
 cache directory. The hard links however cause unwanted side effects, as
 all links to a cached file share the file's modification timestamp.
 This results in false dependencies to be triggered by timestamp-based
 build systems whenever another user links to an existing file.
 Typically, users will see that their libraries and binaries are
 relinked without reason. To share a cache without side effects, the
 following conditions need to be met:</p>
<p></p>
<ul>
<li> Use the same<strong> CCACHE_DIR</strong> environment variable
 setting</li>
<li> Unset the<strong> CCACHE_HARDLINK</strong> environment variable</li>
<li> Make sure everyone sets the CCACHE_UMASK environment variable to
 002, this ensures that cached files are accessible to everyone in the
 group.</li>
<li> Make sure that all users have write permission in the entire cache
 directory (and that you trust all users of the shared cache).</li>
<li> Make sure that the setgid bit is set on all directories in the
 cache. This tells the filesystem to inherit group ownership for new
 directories. The command &quot;chmod g+s `find $CCACHE_DIR -type d`&quot; might
 be useful for this.</li>
<li> Set<strong> CCACHE_NOCOMPRESS</strong> for all users, if there are
 users with versions of ccache that do not support compression.</li>
</ul>
<p></p>
<h2><a name="CCache_nn15">20.14 HISTORY</a></h2>
<p> ccache was inspired by the compilercache shell script written by
 Erik Thiele and I would like to thank him for an excellent piece of
 work. See <a href="http://www.erikyyy.de/compilercache/">
http://www.erikyyy.de/compilercache/</a> for the Erik's scripts.
 ccache-swig is a port of the original ccache with support added for use
 with SWIG.</p>
<p> I wrote ccache because I wanted to get a bit more speed out of a
 compiler cache and I wanted to remove some of the limitations of the
 shell-script version.</p>
<p></p>
<h2><a name="CCache_nn16">20.15 DIFFERENCES FROM COMPILERCACHE</a></h2>
<p> The biggest differences between Erik's compilercache script and
 ccache are:</p>
<ul>
<li> ccache is written in C, which makes it a bit faster (calling out to
 external programs is mostly what slowed down the scripts).</li>
<li> ccache can automatically find the real compiler</li>
<li> ccache keeps statistics on hits/misses</li>
<li> ccache can do automatic cache management</li>
<li> ccache can cache compiler output that includes warnings. In many
 cases this gives ccache a much higher cache hit rate.</li>
<li> ccache can handle a much wider ranger of compiler options</li>
<li> ccache avoids a double call to cpp on a cache miss</li>
</ul>
<p></p>
<h2><a name="CCache_nn17">20.16 CREDITS</a></h2>
<p> Thanks to the following people for their contributions to ccache</p>
<ul>
<li> Erik Thiele for the original compilercache script</li>
<li> Luciano Rocha for the idea of compiling the pre-processor output to
 avoid a 2nd cpp pass</li>
<li> Paul Russell for many suggestions and the debian packaging</li>
</ul>
<p></p>
<h2><a name="CCache_nn18">20.17 AUTHOR</a></h2>
<p> ccache was written by Andrew Tridgell <a href="https://www.samba.org/~tridge/">
https://www.samba.org/~tridge/</a>. ccache was adapted to create
 ccache-swig for use with SWIG by William Fulton.</p>
<p> If you wish to report a problem or make a suggestion then please
 email the SWIG developers on the swig-devel mailing list, see <a href="http://www.swig.org/mail.html">
http://www.swig.org/mail.html</a></p>
<p> ccache is released under the GNU General Public License version 2 or
 later. Please see the file COPYING for license details.</p>
<p></p>
<HR NOSHADE>
<h1><a name="Android">21 SWIG and Android</a></h1>

<!-- INDEX -->
<div class="sectiontoc">
<ul>
<li><a href="#Android_overview">Overview</a></li>
<li><a href="#Android_examples">Android examples</a>
<ul>
<li><a href="#Android_examples_intro">Examples introduction</a></li>
<li><a href="#Android_example_simple">Simple C example</a></li>
<li><a href="#Android_example_class">C++ class example</a></li>
<li><a href="#Android_examples_other">Other examples</a></li>
</ul>
</li>
<li><a href="#Android_stl">C++ STL</a></li>
</ul>
</div>
<!-- INDEX -->
<p> This chapter describes SWIG's support of Android.</p>
<h2><a name="Android_overview">21.1 Overview</a></h2>
<p> The Android chapter is fairly short as support for Android is the
 same as for Java, where the Java Native Interface (JNI) is used to call
 from Android Java into C or C++ compiled code. Everything in the <a href="#Java">
Java chapter</a> applies to generating code for access from Android Java
 code. This chapter contains a few Android specific notes and examples.</p>
<h2><a name="Android_examples">21.2 Android examples</a></h2>
<h3><a name="Android_examples_intro">21.2.1 Examples introduction</a></h3>
<p> The examples require the <a href="https://developer.android.com/sdk/">
Android SDK</a> and <a href="https://developer.android.com/ndk/">Android
 NDK</a> which can be installed as per instructions in the links. The
 Eclipse version is not required for these examples as just the command
 line tools are used (shown for Linux as the host, but Windows will be
 very similar, if not identical in most places). Add the SDK tools and
 NDK tools to your path and create a directory somewhere for your
 Android projects (adjust PATH as necessary to where you installed the
 tools):</p>
<div class="shell">
<pre>
$ export PATH=$HOME/android/android-sdk-linux_x86/tools:$HOME/android/android-sdk-linux_x86/platform-tools:$HOME/android/android-ndk-r6b:$PATH
$ mkdir AndroidApps 
$ cd AndroidApps
</pre>
</div>
<p> The examples use a target id of 1. This might need changing
 depending on your setup. After installation of the Android SDK, the
 available target ids can be viewed by running the command below. Please
 adjust the id to suit your target device.</p>
<div class="shell">
<pre>
$ android list targets
</pre>
</div>
<p> The following examples are shipped with SWIG under the
 Examples/android directory and include a Makefile to build and install
 each example.</p>
<h3><a name="Android_example_simple">21.2.2 Simple C example</a></h3>
<p> This simple C example shows how to call a C function as well as read
 and modify a global variable. First we'll create and build a pure Java
 Android app. Afterwards the JNI code will be generated by SWIG and
 built into the app. First create and build an app called <tt>SwigSimple</tt>
 in a subdirectory called <tt>simple</tt> using the commands below.
 Adjust the <tt>--target</tt> id as mentioned earlier in the <a href="#Android_examples_intro">
Examples introduction</a>. <a href="http://developer.android.com/guide/developing/projects/projects-cmdline.html">
Managing Projects from the Command Line</a> on the Android developer's
 site is a useful reference for these steps.</p>
<div class="shell">
<pre>
$ android create project --target 1 --name SwigSimple --path ./simple --activity SwigSimple --package org.swig.simple
$ cd simple
$ ant debug
</pre>
</div>
<p> Modify <tt>src/org/swig/simple/SwigSimple.java</tt> from the default
 to:</p>
<div class="code">
<pre>
package org.swig.simple;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.ScrollView;
import android.text.method.ScrollingMovementMethod;

public class SwigSimple extends Activity
{
    TextView outputText = null;
    ScrollView scroller = null;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        outputText = (TextView)findViewById(R.id.OutputText);
        outputText.setText(&quot;Press 'Run' to start...\n&quot;);
        outputText.setMovementMethod(new ScrollingMovementMethod());

        scroller = (ScrollView)findViewById(R.id.Scroller);
    }

    public void onRunButtonClick(View view)
    {
      outputText.append(&quot;Started...\n&quot;);
      nativeCall();
      outputText.append(&quot;Finished!\n&quot;);
      
      // Ensure scroll to end of text
      scroller.post(new Runnable() {
        public void run() {
          scroller.fullScroll(ScrollView.FOCUS_DOWN);
        }
      });
    }

    /** Calls into C/C++ code */
    public void nativeCall()
    {
        // TODO
    }
}
</pre>
</div>
<p> The above simply adds a<i> Run</i> button and scrollable text view
 as the GUI aspects of the program. The associated resources need to be
 created, modify <tt>res/layout/main.xml</tt> as follows:</p>
<div class="code">
<pre>
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;LinearLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
    android:orientation=&quot;vertical&quot;
    android:layout_width=&quot;fill_parent&quot;
    android:layout_height=&quot;fill_parent&quot;
    &gt;
&lt;Button
    android:id=&quot;@+id/RunButton&quot;  
    android:layout_width=&quot;wrap_content&quot;  
    android:layout_height=&quot;wrap_content&quot;  
    android:text=&quot;Run...&quot;  
    android:onClick=&quot;onRunButtonClick&quot;
    /&gt;
&lt;ScrollView
    android:id=&quot;@+id/Scroller&quot;
    android:layout_width=&quot;fill_parent&quot;
    android:layout_height=&quot;fill_parent&quot;
    &gt;
&lt;TextView
    android:id=&quot;@+id/OutputText&quot;
    android:layout_width=&quot;wrap_content&quot;
    android:layout_height=&quot;wrap_content&quot;
    /&gt;
&lt;/ScrollView&gt;
&lt;/LinearLayout&gt;
</pre>
</div>
<p> Rebuild the project with your changes:</p>
<div class="shell">
<pre>
$ ant debug
</pre>
</div>
<p> Although there are no native function calls in the code, yet, you
 may want to check that this simple pure Java app runs before adding in
 the native calls. First, set up your Android device for hardware
 debugging, see <a href="http://developer.android.com/guide/developing/device.html">
Using hardware devices</a> on the Android developer's site. When
 complete your device should be listed in those attached, something
 like:</p>
<div class="shell">
<pre>
$ adb devices
List of devices attached 
A32-6DBE0001-9FF80000-015D62C3-02018028 device
</pre>
</div>
<p> This means you are now ready to install the application...</p>
<div class="shell">
<pre>
$ adb install bin/SwigSimple-debug.apk 
95 KB/s (4834 bytes in 0.049s)
        pkg: /data/local/tmp/SwigSimple-debug.apk
Success
</pre>
</div>
<p> The newly installed 'SwigSimple' app will be amongst all your other
 applications on the home screen. Run the app and it will show a<i> Run</i>
 button text box below it. Press the<i> Run</i> button to see the simple
 text output.</p>
<p> The application can be uninstalled like any other application and in
 fact must be uninstalled before installing an updated version.
 Uninstalling is quite easy too from your host computer:</p>
<div class="shell">
<pre>
$ adb uninstall org.swig.simple
Success
</pre>
</div>
<p> Now that you have a pure Java Android app working, let's add some
 JNI code generated from SWIG.</p>
<p> First create a <tt>jni</tt> subdirectory and then create some C
 source code in <tt>jni/example.c</tt>:</p>
<div class="code">
<pre>
/* File : example.c */

/* A global variable */
double Foo = 3.0;

/* Compute the greatest common divisor of positive integers */
int gcd(int x, int y) {
  int g;
  g = y;
  while (x &gt; 0) {
    g = x;
    x = y % x;
    y = g;
  }
  return g;
}
</pre>
</div>
<p> Create a SWIG interface file for this C code, <tt>jni/example.i</tt>
:</p>
<div class="code">
<pre>
/* File : example.i */
%module example

%inline %{
extern int    gcd(int x, int y);
extern double Foo;
%}
</pre>
</div>
<p> Invoke SWIG as follows:</p>
<div class="shell">
<pre>
$ swig -java -package org.swig.simple -outdir src/org/swig/simple -o jni/example_wrap.c jni/example.i
</pre>
</div>
<p> SWIG generates the following files:</p>
<ul>
<li><tt>src/org/swig/simple/exampleJNI.java</tt></li>
<li><tt>src/org/swig/simple/example.java</tt></li>
<li><tt>jni/example_wrap.c</tt></li>
</ul>
<p> Next we need to create a standard Android NDK build system file <tt>
jni/Android.mk</tt>:</p>
<div class="code">
<pre>
# File: Android.mk
LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)

LOCAL_MODULE    := example
LOCAL_SRC_FILES := example_wrap.c example.c

include $(BUILD_SHARED_LIBRARY)
</pre>
</div>
<p> See the <a href="https://developer.android.com/ndk/">Android NDK
 documentation</a> for more on the NDK build system and getting started
 with the NDK. A simple invocation of ndk-build will compile the .c
 files and generate a shared object/system library. Output will be
 similar to:</p>
<div class="shell">
<pre>
$ ndk-build
Compile thumb  : example &lt;= example_wrap.c
Compile thumb  : example &lt;= example.c
SharedLibrary  : libexample.so
Install        : libexample.so =&gt; libs/armeabi/libexample.so
</pre>
</div>
<p> Now that the C JNI layer has been built, we can write Java code to
 call into the this layer. Modify the <tt>nativeCall</tt> method in <tt>
src/org/swig/simple/SwigSimple.java</tt> to call the JNI code as follows
 and add the static constructor to load the system library containing
 the compiled JNI C code:</p>
<div class="code">
<pre>
    /** Calls into C/C++ code */
    public void nativeCall()
    {
      // Call our gcd() function
      
      int x = 42;
      int y = 105;
      int g = example.gcd(x, y);
      outputText.append(&quot;The greatest common divisor of &quot; + x + &quot; and &quot; + y + &quot; is &quot; + g + &quot;\n&quot;);

      // Manipulate the Foo global variable

      // Output its current value
      double foo = example.getFoo();
      outputText.append(&quot;Foo = &quot; + foo + &quot;\n&quot;);

      // Change its value
      example.setFoo(3.1415926);

      // See if the change took effect
      outputText.append(&quot;Foo = &quot; + example.getFoo() + &quot;\n&quot;);

      // Restore value
      example.setFoo(foo);
    }

    /** static constructor */
    static {
        System.loadLibrary(&quot;example&quot;);
    }
</pre>
</div>
<p> Compile the Java code as usual, uninstall the old version of the app
 if still installed and re-install the new app:</p>
<div class="shell">
<pre>
$ ant debug
$ adb uninstall org.swig.simple
$ adb install bin/SwigSimple-debug.apk 
</pre>
</div>
<p> Run the app again and this time you will see the output pictured
 below, showing the result of calls into the C code:</p>
<center><img alt="Android screenshot of SwigSimple example" HEIGHT="400" src="android-simple.png"
WIDTH="256"></center>
<h3><a name="Android_example_class">21.2.3 C++ class example</a></h3>
<p> The steps for calling C++ code are almost identical to those in the
 previous C code example. All the steps required to compile and use a
 simple hierarchy of classes for shapes are shown in this example.</p>
<p> First create an Android project called <tt>SwigClass</tt> in a
 subdirectory called <tt>class</tt>. The steps below create and build
 the JNI C++ app. Adjust the <tt>--target</tt> id as mentioned earlier
 in the <a href="#Android_examples_intro">Examples introduction</a>.</p>
<div class="shell">
<pre>
$ android create project --target 1 --name SwigClass --path ./class --activity SwigClass --package org.swig.classexample
$ cd class
</pre>
</div>
<p> Now create a <tt>jni</tt> subdirectory and then create a C++ header
 file <tt>jni/example.h</tt> which defines our hierarchy of shape
 classes:</p>
<div class="code">
<pre>
/* File : example.h */

class Shape {
public:
  Shape() {
    nshapes++;
  }
  virtual ~Shape() {
    nshapes--;
  }
  double  x, y;   
  void    move(double dx, double dy);
  virtual double area() = 0;
  virtual double perimeter() = 0;
  static  int nshapes;
};

class Circle : public Shape {
private:
  double radius;
public:
  Circle(double r) : radius(r) { }
  virtual double area();
  virtual double perimeter();
};

class Square : public Shape {
private:
  double width;
public:
  Square(double w) : width(w) { }
  virtual double area();
  virtual double perimeter();
};
</pre>
</div>
<p> and create the implementation in the <tt>jni/example.cpp</tt> file:</p>
<div class="code">
<pre>
/* File : example.cpp */

#include &quot;example.h&quot;
#define M_PI 3.14159265358979323846

/* Move the shape to a new location */
void Shape::move(double dx, double dy) {
  x += dx;
  y += dy;
}

int Shape::nshapes = 0;

double Circle::area() {
  return M_PI*radius*radius;
}

double Circle::perimeter() {
  return 2*M_PI*radius;
}

double Square::area() {
  return width*width;
}

double Square::perimeter() {
  return 4*width;
}
</pre>
</div>
<p> Create a SWIG interface file for this C++ code in <tt>jni/example.i</tt>
:</p>
<div class="code">
<pre>
/* File : example.i */
%module example

%{
#include &quot;example.h&quot;
%}

/* Let's just grab the original header file here */
%include &quot;example.h&quot;
</pre>
</div>
<p> Invoke SWIG as follows, note that the -c++ option is required for
 C++ code:</p>
<div class="shell">
<pre>
$ swig -c++ -java -package org.swig.classexample -outdir src/org/swig/classexample -o jni/example_wrap.cpp jni/example.i
</pre>
</div>
<p> SWIG generates the following files:</p>
<ul>
<li><tt>src/org/swig/classexample/Square.java</tt></li>
<li><tt>src/org/swig/classexample/exampleJNI.java</tt></li>
<li><tt>src/org/swig/classexample/example.java</tt></li>
<li><tt>src/org/swig/classexample/Circle.java</tt></li>
<li><tt>src/org/swig/classexample/Shape.java</tt></li>
<li><tt>jni/example_wrap.cpp</tt></li>
</ul>
<p> Next we need to create an Android NDK build system file for
 compiling the C++ code <tt>jni/Android.mk</tt>. The <tt>-frtti</tt>
 compiler flag isn't strictly needed for this example, but is needed for
 any code that uses C++ RTTI:</p>
<div class="code">
<pre>
# File: Android.mk
LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)

LOCAL_MODULE    := example
LOCAL_SRC_FILES := example_wrap.cpp example.cpp
LOCAL_CFLAGS    := -frtti

include $(BUILD_SHARED_LIBRARY)
</pre>
</div>
<p> A simple invocation of ndk-build will compile the .cpp files and
 generate a shared object/system library. Output will be similar to:</p>
<div class="shell">
<pre>
$ ndk-build
Compile++ thumb  : example &lt;= example_wrap.cpp
Compile++ thumb  : example &lt;= example.cpp
StaticLibrary  : libstdc++.a
SharedLibrary  : libexample.so
Install        : libexample.so =&gt; libs/armeabi/libexample.so
</pre>
</div>
<p> Now that the C JNI layer has been built, we can write Java code to
 call into this layer. Modify <tt>
src/org/swig/classexample/SwigClass.java</tt> from the default to:</p>
<div class="code">
<pre>
package org.swig.classexample;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.ScrollView;
import android.text.method.ScrollingMovementMethod;

public class SwigClass extends Activity
{
    TextView outputText = null;
    ScrollView scroller = null;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        outputText = (TextView)findViewById(R.id.OutputText);
        outputText.setText(&quot;Press 'Run' to start...\n&quot;);
        outputText.setMovementMethod(new ScrollingMovementMethod());

        scroller = (ScrollView)findViewById(R.id.Scroller);
    }

    public void onRunButtonClick(View view)
    {
      outputText.append(&quot;Started...\n&quot;);
      nativeCall();
      outputText.append(&quot;Finished!\n&quot;);
      
      // Ensure scroll to end of text
      scroller.post(new Runnable() {
        public void run() {
          scroller.fullScroll(ScrollView.FOCUS_DOWN);
        }
      });
    }

    /** Calls into C/C++ code */
    public void nativeCall()
    {
      // ----- Object creation -----

      outputText.append( &quot;Creating some objects:\n&quot; );
      Circle c = new Circle(10);
      outputText.append( &quot;    Created circle &quot; + c + &quot;\n&quot;);
      Square s = new Square(10);
      outputText.append( &quot;    Created square &quot; + s + &quot;\n&quot;);

      // ----- Access a static member -----

      outputText.append( &quot;\nA total of &quot; + Shape.getNshapes() + &quot; shapes were created\n&quot; );

      // ----- Member data access -----

      // Notice how we can do this using functions specific to
      // the 'Circle' class.
      c.setX(20);
      c.setY(30);

      // Now use the same functions in the base class
      Shape shape = s;
      shape.setX(-10);
      shape.setY(5);

      outputText.append( &quot;\nHere is their current position:\n&quot; );
      outputText.append( &quot;    Circle = (&quot; + c.getX() + &quot; &quot; + c.getY() + &quot;)\n&quot; );
      outputText.append( &quot;    Square = (&quot; + s.getX() + &quot; &quot; + s.getY() + &quot;)\n&quot; );

      // ----- Call some methods -----

      outputText.append( &quot;\nHere are some properties of the shapes:\n&quot; );
      Shape[] shapes = {c, s};
      for (int i=0; i&lt;shapes.length; i++)
      {
        outputText.append( &quot;   &quot; + shapes[i].toString() + &quot;\n&quot; );
        outputText.append( &quot;        area      = &quot; + shapes[i].area() + &quot;\n&quot; );
        outputText.append( &quot;        perimeter = &quot; + shapes[i].perimeter() + &quot;\n&quot; );
      }

      // Notice how the area() and perimeter() functions really
      // invoke the appropriate virtual method on each object.

      // ----- Delete everything -----

      outputText.append( &quot;\nGuess I'll clean up now\n&quot; );

      // Note: this invokes the virtual destructor
      // You could leave this to the garbage collector
      c.delete();
      s.delete();

      outputText.append( Shape.getNshapes() + &quot; shapes remain\n&quot; );
      outputText.append( &quot;Goodbye\n&quot; );
    }

    /** static constructor */
    static {
        System.loadLibrary(&quot;example&quot;);
    }
}
</pre>
</div>
<p> Note the static constructor and the interesting JNI code is in the <tt>
nativeCall</tt> method. The remaining code deals with the GUI aspects
 which are identical to the previous C simple example. Modify <tt>
res/layout/main.xml</tt> to contain the xml for the 'Run' button and
 scrollable text view:</p>
<div class="code">
<pre>
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;LinearLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
    android:orientation=&quot;vertical&quot;
    android:layout_width=&quot;fill_parent&quot;
    android:layout_height=&quot;fill_parent&quot;
    &gt;
&lt;Button
    android:id=&quot;@+id/RunButton&quot;  
    android:layout_width=&quot;wrap_content&quot;  
    android:layout_height=&quot;wrap_content&quot;  
    android:text=&quot;Run...&quot;  
    android:onClick=&quot;onRunButtonClick&quot;
    /&gt;
&lt;ScrollView
    android:id=&quot;@+id/Scroller&quot;
    android:layout_width=&quot;fill_parent&quot;
    android:layout_height=&quot;fill_parent&quot;
    &gt;
&lt;TextView
    android:id=&quot;@+id/OutputText&quot;
    android:layout_width=&quot;wrap_content&quot;
    android:layout_height=&quot;wrap_content&quot;
    /&gt;
&lt;/ScrollView&gt;
&lt;/LinearLayout&gt;
</pre>
</div>
<p> Compile the Java code as usual, uninstall the old version of the app
 if installed and re-install the new app:</p>
<div class="shell">
<pre>
$ ant debug
$ adb uninstall org.swig.classexample
$ adb install bin/SwigClass-debug.apk 
</pre>
</div>
<p> Run the app to see the result of calling the C++ code from Java:</p>
<center><img alt="Android screenshot of SwigClass example" HEIGHT="400" src="android-class.png"
WIDTH="256"></center>
<h3><a name="Android_examples_other">21.2.4 Other examples</a></h3>
<p> The Examples/android directory contains further examples which can
 be run and installed in a similar manner to the previous two examples.</p>
<p> Note that the 'extend' example is demonstrates the directors
 feature. Normally C++ exception handling and the STL is not available
 by default in the version of g++ shipped with Android, but this example
 turns these features on as described in the next section.</p>
<h2><a name="Android_stl">21.3 C++ STL</a></h2>
<p> Should the C++ Standard Template Library (STL) be required, an <tt>
Application.mk</tt> file needs to be created in the same directory as
 the <tt>Android.mk</tt> directory containing information about the STL
 to use. See the NDK documentation in the $NDKROOT/docs folder
 especially CPLUSPLUS-SUPPORT.html. Below is an example of the <tt>
Application.mk</tt> file to make the STLport static library available
 for use:</p>
<div class="code">
<pre>
# File: Application.mk
APP_STL := gnustl_static
</pre>
</div><HR NOSHADE>
<h1><a name="CSharp">22 SWIG and C#</a></h1>

<!-- INDEX -->
<div class="sectiontoc">
<ul>
<li><a href="#CSharp_introduction">Introduction</a>
<ul>
<li><a href="#CSharp_introduction_swig2_compatibility">SWIG 2
 Compatibility</a></li>
<li><a href="#CSharp_commandline">Additional command line options</a></li>
</ul>
</li>
<li><a href="#CSharp_differences_java">Differences to the Java module</a>
</li>
<li><a href="#CSharp_void_pointers">Void pointers</a></li>
<li><a href="#CSharp_arrays">C# Arrays</a>
<ul>
<li><a href="#CSharp_arrays_swig_library">The SWIG C arrays library</a></li>
<li><a href="#CSharp_arrays_pinvoke_default_array_marshalling">Managed
 arrays using P/Invoke default array marshalling</a></li>
<li><a href="#CSharp_arrays_pinning">Managed arrays using pinning</a></li>
</ul>
</li>
<li><a href="#CSharp_exceptions">C# Exceptions</a>
<ul>
<li><a href="#CSharp_exception_example_check_typemap">C# exception
 example using &quot;check&quot; typemap</a></li>
<li><a href="#CSharp_exception_example_percent_exception">C# exception
 example using %exception</a></li>
<li><a href="#CSharp_exception_example_exception_specifications">C#
 exception example using exception specifications</a></li>
<li><a href="#CSharp_custom_application_exception">Custom C#
 ApplicationException example</a></li>
</ul>
</li>
<li><a href="#CSharp_directors">C# Directors</a>
<ul>
<li><a href="#CSharp_directors_example">Directors example</a></li>
<li><a href="#CSharp_directors_implementation">Directors implementation</a>
</li>
<li><a href="#CSharp_director_caveats">Director caveats</a></li>
</ul>
</li>
<li><a href="#CSharp_multiple_modules">Multiple modules</a></li>
<li><a href="#CSharp_typemap_examples">C# Typemap examples</a>
<ul>
<li><a href="#CSharp_memory_management_member_variables">Memory
 management when returning references to member variables</a></li>
<li><a href="#CSharp_memory_management_objects">Memory management for
 objects passed to the C++ layer</a></li>
<li><a href="#CSharp_date_marshalling">Date marshalling using the csin
 typemap and associated attributes</a></li>
<li><a href="#CSharp_date_properties">A date example demonstrating
 marshalling of C# properties</a></li>
<li><a href="#CSharp_date_pre_post_directors">Date example demonstrating
 the 'pre' and 'post' typemap attributes for directors</a></li>
<li><a href="#CSharp_partial_classes">Turning proxy classes into partial
 classes</a></li>
<li><a href="#CSharp_sealed_proxy_class">Turning proxy classes into
 sealed classes</a></li>
<li><a href="#CSharp_extending_proxy_class">Extending proxy classes with
 additional C# code</a></li>
<li><a href="#CSharp_enum_underlying_type">Underlying type for enums</a></li>
</ul>
</li>
</ul>
</div>
<!-- INDEX -->
<h2><a name="CSharp_introduction">22.1 Introduction</a></h2>
<p> The purpose of the C# module is to offer an automated way of
 accessing existing C/C++ code from .NET languages. The wrapper code
 implementation uses C# and the Platform Invoke (PInvoke) interface to
 access natively compiled C/C++ code. The PInvoke interface has been
 chosen over Microsoft's Managed C++ interface as it is portable to both
 Microsoft Windows and non-Microsoft platforms. PInvoke is part of the
 ECMA/ISO C# specification. It is also better suited for robust
 production environments due to the Managed C++ flaw called the <a href="https://msdn.microsoft.com/en-us/ie/aa290048(v=vs.94)">
Mixed DLL Loading Problem</a>. SWIG C# works equally well on
 non-Microsoft operating systems such as Linux, Solaris and Apple Mac
 using <a href="https://www.mono-project.com/Main_Page/">Mono</a>.</p>
<p> SWIG 3 and later requires .NET 2.0 at a minimum. There are some
 minor exceptions, where the minimum required is .NET 4.0. This is when
 using the <tt>std::complex</tt> and <tt>std::list</tt> STL containers.</p>
<p> To get the most out of this chapter an understanding of interop is
 required. The <a href="https://msdn.microsoft.com">Microsoft Developer
 Network (MSDN)</a> has a good reference guide in a section titled
 &quot;Interop Marshaling&quot;. Monodoc, available from the Mono project, has a
 very useful section titled <a href="https://www.mono-project.com/docs/advanced/pinvoke/">
Interop with native libraries</a>.</p>
<h3><a name="CSharp_introduction_swig2_compatibility">22.1.1 SWIG 2
 Compatibility</a></h3>
<p> In order to minimize name collisions between names generated based
 on input to SWIG and names used in the generated code from the .NET
 framework, SWIG 3 fully qualifies the use of all .NET types.
 Furthermore, SWIG 3 avoids <tt>using</tt> directives in generated code.
 This breaks backwards compatibility with typemaps, pragmas, etc written
 for use with SWIG 2 that assume the presence of <tt>using System;</tt>
 or <tt>using System.Runtime.InteropServices;</tt> directives in the
 intermediate class imports, module imports, or proxy imports. SWIG 3
 supports backwards compatibility though the use of the <tt>SWIG2_CSHARP</tt>
 macro. If <tt>SWIG2_CSHARP</tt> is defined, SWIG 3 generates <tt>using</tt>
 directives in the intermediate class, module class, and proxy class
 code similar to those generated by SWIG 2. This can be done without
 modifying any of the input code by passing the <tt>-DSWIG2_CSHARP</tt>
 commandline parameter when executing <tt>swig</tt>.</p>
<h3><a name="CSharp_commandline">22.1.2 Additional command line options</a>
</h3>
<p> The following table lists the additional commandline options
 available for the C# module. They can also be seen by using:</p>
<div class="code">
<pre>
swig -csharp -help 
</pre>
</div>
<table summary="C# specific options">
<tr><th>C# specific options</th></tr>
<tr><td>-dllimport &lt;dl&gt;</td><td>Override DllImport attribute name to
 &lt;dl&gt;</td></tr>
<tr><td>-namespace &lt;nm&gt;</td><td>Generate wrappers into C# namespace &lt;nm&gt;</td>
</tr>
<tr><td>-noproxy</td><td>Generate the low-level functional interface
 instead of proxy classes</td></tr>
<tr><td>-oldvarnames</td><td>Old intermediary method names for variable
 wrappers</td></tr>
<tr><td>-outfile &lt;file&gt;</td><td>Write all C# into a single &lt;file&gt;
 located in the output directory</td></tr>
</table>
<p> The -outfile option combines all the generated C# code into a single
 output file instead of creating multiple C# files. The default, when
 this option is not provided, is to generate separate .cs files for the
 module class, intermediary class and each of the generated proxy and
 type wrapper classes. Note that the file extension (.cs) will not be
 automatically added and needs to be provided. Due to possible compiler
 limits it is not advisable to use <tt>-outfile</tt> for large projects.</p>
<h2><a name="CSharp_differences_java">22.2 Differences to the Java
 module</a></h2>
<p> The C# module is very similar to the Java module, so until some more
 complete documentation has been written, please use the <a href="#Java">
Java documentation</a> as a guide to using SWIG with C#. The C# module
 has the same major SWIG features as the Java module. The rest of this
 section should be read in conjunction with the Java documentation as it
 lists the main differences. The most notable differences to Java are
 the following:</p>
<ul>
<li> When invoking SWIG use the <tt>-csharp</tt> command line option
 instead of <tt>-java</tt>.</li>
<li> The <tt>-nopgcpp</tt> command line option does not exist.</li>
<li> The <tt>-package</tt> command line option does not exist.</li>
<li> The <tt>-namespace &lt;name&gt;</tt> commandline option will generate all
 code into the namespace specified by <tt>&lt;name&gt;</tt>. C# supports
 nested namespaces that are not lexically nested, so nested namespaces
 will of course also work. For example: <tt>-namespace com.bloggs.widget</tt>
, will generate code into C# namespaces:<div class="code">
<pre>
namespace com.bloggs.widget {
  ...
}
</pre>
</div> Note that by default, the generated C# classes have no namespace
 and the module name is unrelated to namespaces. The module name is just
 like in Java and is merely used to name some of the generated classes.</li>
<li> The <a href="#SWIGPlus_nspace">nspace feature</a> is also supported
 as described in this general section with a C# example. Unlike Java
 which requires the use of the -package option when using the <tt>nspace</tt>
 feature, the -namespace option is not mandatory for C#.</li>
<li> The <tt>-dllimport &lt;name&gt;</tt> commandline option specifies the
 name of the DLL for the <tt>DllImport</tt> attribute for every PInvoke
 method. If this commandline option is not given, the <tt>DllImport</tt>
 DLL name is the same as the module name. This option is useful for when
 one wants to invoke SWIG multiple times on different modules, yet
 compile all the resulting code into a single DLL.</li>
<li> C/C++ variables are wrapped with C# properties and not JavaBean
 style getters and setters.</li>
<li> Global constants are generated into the module class. There is no
 constants interface.</li>
<li> There is no implementation for type unsafe enums - not deemed
 necessary.</li>
<li> The default enum wrapping approach is proper C# enums, not typesafe
 enums.
<br> Note that %csconst(0) will be ignored when wrapping C/C++ enums
 with proper C# enums. This is because C# enum items must be initialised
 from a compile time constant. If an enum item has an initialiser and
 the initialiser doesn't compile as C# code, then the %csconstvalue
 directive must be used as %csconst(0) will have no effect. If it was
 used, it would generate an illegal runtime initialisation via a PInvoke
 call.</li>
<li> C# doesn't support the notion of throws clauses. Therefore there is
 no 'throws' typemap attribute support for adding exception classes to a
 throws clause. Likewise there is no need for an equivalent to <tt>
%javaexception</tt>. In fact, throwing C# exceptions works quite
 differently, see <a href="#CSharp_exceptions">C# Exceptions</a> below.</li>
<li> The majority of the typemaps are in csharp.swg, not java.swg.</li>
<li>
<p>Typemap equivalent names:</p>
<div class="code">
<pre>
jni                         -&gt; ctype
jtype                       -&gt; imtype
jstype                      -&gt; cstype
javain                      -&gt; csin
javaout                     -&gt; csout
javadirectorin              -&gt; csdirectorin
javadirectorout             -&gt; csdirectorout
javainterfaces              -&gt; csinterfaces and csinterfaces_derived
javabase                    -&gt; csbase
javaclassmodifiers          -&gt; csclassmodifiers
javacode                    -&gt; cscode
javaimports                 -&gt; csimports
javabody                    -&gt; csbody
javafinalize                -&gt; csfinalize
javadestruct                -&gt; csdisposing and csdispose
javadestruct_derived        -&gt; csdisposing_derived and csdispose_derived
javainterfacecode           -&gt; csinterfacecode
</pre>
</div></li>
<li>
<p>Typemap macros:</p>
<div class="code">
<pre>
SWIG_JAVABODY_PROXY         -&gt; SWIG_CSBODY_PROXY
SWIG_JAVABODY_TYPEWRAPPER   -&gt; SWIG_CSBODY_TYPEWRAPPER
</pre>
</div></li>
<li>
<p>Additional typemaps:</p>
<div class="code">
<pre>
csvarin                     C# code property set typemap
csvarout                    C# code property get typemap
csattributes                C# attributes for attaching to proxy classes/enums
</pre>
</div></li>
<li>
<p>Additional typemap attributes:</p>
<p> The &quot;null&quot; attribute in the &quot;out&quot; typemap can be specified to
 provide a value for <tt>$null</tt> to expand into for wrapped functions
 that return non-void. Normally the default value of <tt>0</tt> is used.
 For example this is needed if you change the return type to void:</p>
<div class="code">
<pre>
%typemap(ctype) Status &quot;void&quot;
%typemap(out, null=&quot;&quot;) Status { ... }
</pre>
</div></li>
<li>
<p>Feature equivalent names:</p>
<div class="code">
<pre>
%javaconst                  -&gt; %csconst
%javaconstvalue             -&gt; %csconstvalue
%javamethodmodifiers        -&gt; %csmethodmodifiers
</pre>
</div></li>
<li>
<p>Pragma equivalent names:</p>
<div class="code">
<pre>
%pragma(java)               -&gt; %pragma(csharp)
jniclassbase                -&gt; imclassbase
jniclassclassmodifiers      -&gt; imclassclassmodifiers
jniclasscode                -&gt; imclasscode
jniclassimports             -&gt; imclassimports
jniclassinterfaces          -&gt; imclassinterfaces
</pre>
</div></li>
<li>
<p>Special variable equivalent names:</p>
<div class="code">
<pre>
$javaclassname              -&gt; $csclassname
$&amp;javaclassname             -&gt; $&amp;csclassname
$*javaclassname             -&gt; $*csclassname
$javaclazzname              -&gt; $csclazzname
$javainput                  -&gt; $csinput
$jnicall                    -&gt; $imcall
$javainterfacename          -&gt; $csinterfacename
$&amp;javainterfacename         -&gt; $&amp;csinterfacename
$*javainterfacename         -&gt; $*csinterfacename
</pre>
</div></li>
<li>
<p> Unlike the &quot;javain&quot; typemap, the &quot;csin&quot; typemap does not support the
 'pgcpp' attribute as the C# module does not have a premature garbage
 collection prevention parameter. The &quot;csin&quot; typemap supports additional
 optional attributes called 'cshin' and 'terminator'. The &quot;csdirectorin&quot;
 typemap supports additional optional attributes called 'terminator'.
 The 'cshin' attribute should contain the parameter type and name
 whenever a <a href="#Java_constructor_helper_function">constructor
 helper function</a> is generated due to the 'pre' or 'post' attributes.
 The 'terminator' attribute normally just contains a closing brace for
 when the 'pre' attribute contains an opening brace, such as when a C# <tt>
using</tt> or <tt>fixed</tt> block is started. Note that 'pre', 'post',
 'terminator' and 'cshin' attributes are not used for marshalling the
 property set. Please see the <a href="#CSharp_date_marshalling">Date
 marshalling example</a> and <a href="#CSharp_date_properties">Date
 marshalling of properties example</a> for further understanding of
 these &quot;csin&quot; applicable attributes. Please see the <a href="#CSharp_date_pre_post_directors">
Date marshalling director example</a> for further understanding of the
 &quot;csdirectorin&quot; attributes.</p>
</li>
<li>
<p> Support for asymmetric type marshalling. The 'ctype', 'imtype' and
 'cstype' typemaps support an optional <tt>out</tt> attribute which is
 used for output types. If this typemap attribute is specified, then the
 type specified in the attribute is used for output types and the type
 specified in the typemap itself is used for the input type. If this
 typemap attribute is not specified, then the type used for both input
 and output is the type specified in the typemap. An example shows that <tt>
char *</tt> could be marshalled in different ways,</p>
<div class="code">
<pre>
%typemap(imtype, out=&quot;global::System.IntPtr&quot;) char * &quot;string&quot;
char * function(char *);
</pre>
</div>
<p> The output type is thus IntPtr and the input type is string. The
 resulting intermediary C# code is:</p>
<div class="code">
<pre>
public static extern global::System.IntPtr function(string jarg1);
</pre>
</div></li>
<li>
<p> Support for type attributes. The 'imtype' and 'cstype' typemaps can
 have an optional <tt>inattributes</tt> and <tt>outattributes</tt>
 typemap attribute. The 'imtype' typemap can also have an optional <tt>
directorinattributes</tt> and <tt>directoroutattributes</tt> typemap
 attribute which attaches to director delegates, an implementation
 detail of directors, see <a href="#CSharp_directors_implementation">
directors implementation</a>. Note that there are C# attributes and
 typemap attributes, don't get confused between the two!! The C#
 attributes specified in these typemap attributes are generated wherever
 the type is used in the C# wrappers. These can be used to specify any
 C# attribute associated with a C/C++ type, but are more typically used
 for the C# <tt>MarshalAs</tt> attribute. For example:</p>
<div class="code">
<pre>
%typemap(imtype,
         inattributes=&quot;[global::System.Runtime.InteropServices.MarshalAs(UnmanagedType.LPStr)]&quot;,
         outattributes=&quot;[return: global::System.Runtime.InteropServices.MarshalAs(UnmanagedType.LPStr)]&quot;) const char * &quot;String&quot;

const char * GetMsg() {}
void SetMsg(const char *msg) {}
</pre>
</div>
<p> The intermediary class will then have the marshalling as specified
 by everything in the 'imtype' typemap:</p>
<div class="code">
<pre>
class examplePINVOKE {
  ...
  [global::System.Runtime.InteropServices.DllImport(&quot;example&quot;, EntryPoint=&quot;CSharp_GetMsg&quot;)]
  [return: global::System.Runtime.InteropServices.MarshalAs(UnmanagedType.LPStr)]
  public static extern String GetMsg();

  [global::System.Runtime.InteropServices.DllImport(&quot;example&quot;, EntryPoint=&quot;CSharp_SetMsg&quot;)]
  public static extern void SetMsg([global::System.Runtime.InteropServices.MarshalAs(UnmanagedType.LPStr)]String jarg1);
}
</pre>
</div>
<p> Note that the <tt>DllImport</tt> attribute is always generated,
 irrespective of any additional attributes specified.</p>
<p> These attributes are associated with the C/C++ parameter type or
 return type, which is subtly different to the attribute features and
 typemaps covered next. Note that all these different C# attributes can
 be combined so that a method has more than one attribute.</p>
<p> The <tt>directorinattributes</tt> and <tt>directoroutattributes</tt>
 typemap attribute are attached to the delegates in the director class,
 for example, the SwigDelegateBase_0</p>
</li>
<li>
<p> Support for attaching C# attributes to wrapped methods, variables
 and enum values. This is done using the <tt>%csattributes</tt> feature,
 see <a href="#Customization_features">%feature directives</a>. Note
 that C# attributes are attached to proxy classes and enums using the <tt>
csattributes</tt> typemap. For example, imagine we have a custom
 attribute class, <tt>ThreadSafeAttribute</tt>, for labelling thread
 safety. The following SWIG code shows how to attach this C# attribute
 to some methods and the class declaration itself:</p>
<div class="code">
<pre>
%typemap(csattributes) AClass          &quot;[ThreadSafe]&quot;
%csattributes AClass::AClass(double d) &quot;[ThreadSafe(false)]&quot;
%csattributes AClass::AMethod()        &quot;[ThreadSafe(true)]&quot;

%inline %{
class AClass {
public:
  AClass(double a) {}
  void AMethod() {}
};
%}
</pre>
</div>
<p> will generate a C# proxy class:</p>
<div class="code">
<pre>
[ThreadSafe]
public class AClass : global::System.IDisposable {
  ...
  [ThreadSafe(false)]
  public AClass(double a) ...

  [ThreadSafe(true)]
  public void AMethod() ...
}
</pre>
</div>
<p> If C# attributes need adding to the <tt>set</tt> or <tt>get</tt>
 part of C# properties, when wrapping C/C++ variables, they can be added
 using the 'csvarin' and 'csvarout' typemaps respectively. Note that the
 type used for the property is specified in the 'cstype' typemap. If the
 'out' attribute exists in this typemap, then the type used is from the
 'out' attribute.</p>
<p> An example for attaching attributes to the enum and enum values is
 shown below.</p>
<div class="code">
<pre>
%typemap(csattributes) Couleur &quot;[global::System.ComponentModel.Description(\&quot;Colours\&quot;)]&quot;
%csattributes Rouge &quot;[global::System.ComponentModel.Description(\&quot;Red\&quot;)]&quot;
%csattributes Vert &quot;[global::System.ComponentModel.Description(\&quot;Green\&quot;)]&quot;
%inline %{
  enum Couleur { Rouge, Orange, Vert };
%}
</pre>
</div>
<p> which will result in the following C# enum:</p>
<div class="code">
<pre>
[global::System.ComponentModel.Description(&quot;Colours&quot;)]
public enum Couleur {
  [global::System.ComponentModel.Description(&quot;Red&quot;)]
  Rouge,
  Orange,
  [global::System.ComponentModel.Description(&quot;Green&quot;)]
  Vert
}
</pre>
</div></li>
<li>
<p> The intermediary classname has <tt>PINVOKE</tt> appended after the
 module name instead of <tt>JNI</tt>, for example <tt>modulenamePINVOKE</tt>
.</p>
</li>
<li>
<p> The <tt>%csmethodmodifiers</tt> feature can also be applied to
 variables as well as methods. In addition to the default <tt>public</tt>
 modifier that SWIG generates when <tt>%csmethodmodifiers</tt> is not
 specified, the feature will also replace the <tt>virtual</tt>/<tt>new</tt>
/<tt>override</tt> modifiers that SWIG thinks is appropriate. This
 feature is useful for some obscure cases where SWIG might get the <tt>
virtual</tt>/<tt>new</tt>/<tt>override</tt> modifiers incorrect, for
 example with multiple inheritance.</p>
</li>
<li> <a name="CSharp_module_directive"></a>
<p> The name of the intermediary class can be changed from its default,
 that is, the module name with PINVOKE appended after it. The module
 directive attribute <tt>imclassname</tt> is used to achieve this:</p>
<div class="code">
<pre>
%module (imclassname=&quot;name&quot;) modulename
</pre>
</div>
<p> If <tt>name</tt> is the same as <tt>modulename</tt> then the module
 class name gets changed from <tt>modulename</tt> to <tt>
modulenameModule</tt>.</p>
</li>
<li> There is no additional 'premature garbage collection prevention
 parameter' as the marshalling of the <tt>HandleRef</tt> object takes
 care of ensuring a reference to the proxy class is held until the
 unmanaged call completed.</li>
</ul>
<p><b> <tt>$dllimport</tt></b>
<br> This is a C# only special variable that can be used in typemaps,
 pragmas, features etc. The special variable will get translated into
 the value specified by the <tt>-dllimport</tt> commandline option if
 specified, otherwise it is equivalent to the<b> $module</b> special
 variable.</p>
<p><b> <tt>$imclassname</tt></b>
<br> This special variable expands to the intermediary class name. For
 C# this is usually the same as '$modulePINVOKE' ('$moduleJNI' for
 Java), unless the imclassname attribute is specified in the <a href="#CSharp_module_directive">
%module directive</a>.</p>
<p> The directory <tt>Examples/csharp</tt> has a number of simple
 examples. Visual Studio .NET 2003 solution and project files are
 available for compiling with the Microsoft .NET C# compiler on Windows.
 This also works with newer versions of Visual Studio if you allow it to
 convert the solution to the latest version. If your SWIG installation
 went well on a Unix environment and your C# compiler was detected, you
 should be able to type <tt>make</tt> in each example directory. After
 SWIG has run and both the C# and C/C++ compilers have finished
 building, the examples will be run, by either running <tt>runme.exe</tt>
 or by running <tt>mono runme.exe</tt> (Mono C# compiler). Windows users
 can also get the examples working using a <a href="http://www.cygwin.com">
Cygwin</a> or <a href="http://www.mingw.org">MinGW</a> environment for
 automatic configuration of the example makefiles. Any one of the C#
 compilers (Mono or Microsoft) can be detected from within a Cygwin or
 Mingw environment if installed in your path.</p>
<h2><a name="CSharp_void_pointers">22.3 Void pointers</a></h2>
<p> By default SWIG treats <tt>void *</tt> as any other pointer and
 hence marshalls it as a type wrapper class called <tt>SWIGTYPE_p_void</tt>
. If you want to marshall with the .NET <tt>System.IntPtr</tt> type
 instead, there is a simple set of named typemaps called <tt>void
 *VOID_INT_PTR</tt> that can be used. They can be applied like any other
 named typemaps:</p>
<div class="code">
<pre>
%apply void *VOID_INT_PTR { void * }
void * f(void *v);
</pre>
</div>
<h2><a name="CSharp_arrays">22.4 C# Arrays</a></h2>
<p> There are various ways to pass arrays from C# to C/C++. The default
 wrapping treats arrays as pointers and as such simple type wrapper
 classes are generated, eg <tt>SWIGTYPE_p_int</tt> when wrapping the C
 type <tt>int []</tt> or <tt>int *</tt>. This gives a rather restricted
 use of the underlying unmanaged code and the most practical way to use
 arrays is to enhance or customise with one of the following three
 approaches; namely the SWIG C arrays library, P/Invoke default array
 marshalling or pinned arrays.</p>
<h3><a name="CSharp_arrays_swig_library">22.4.1 The SWIG C arrays
 library</a></h3>
<p> The C arrays library keeps all the array memory in the unmanaged
 layer. The library is available to all language modules and is
 documented in the <a href="#Library_carrays">carrays.i library</a>
 section. Please refer to this section for details, but for convenience,
 the C# usage for the two examples outlined there is shown below.</p>
<p> For the <tt>%array_functions</tt> example, the equivalent usage
 would be:</p>
<div class="code">
<pre>
SWIGTYPE_p_double a = example.new_doubleArray(10);  // Create an array
for (int i=0; i&lt;10; i++)
  example.doubleArray_setitem(a, i, 2*i);           // Set a value
example.print_array(a);                             // Pass to C
example.delete_doubleArray(a);                      // Destroy array
</pre>
</div>
<p> and for the <tt>%array_class</tt> example, the equivalent usage
 would be:</p>
<div class="code">
<pre>
doubleArray c = new doubleArray(10);    // Create double[10]
for (int i=0; i&lt;10; i++)
  c.setitem(i, 2*i);                    // Assign values
example.print_array(c.cast());          // Pass to C
</pre>
</div>
<h3><a name="CSharp_arrays_pinvoke_default_array_marshalling">22.4.2
 Managed arrays using P/Invoke default array marshalling</a></h3>
<p> In the P/Invoke default marshalling scheme, one needs to designate
 whether the invoked function will treat a managed array parameter as
 input, output, or both. When the function is invoked, the CLR allocates
 a separate chunk of memory as big as the given managed array, which is
 automatically released at the end of the function call. If the array
 parameter is marked as being input, the content of the managed array is
 copied into this buffer when the call is made. Correspondingly, if the
 array parameter is marked as being output, the contents of the reserved
 buffer are copied back into the managed array after the call returns. A
 pointer to this buffer is passed to the native function.</p>
<p> The reason for allocating a separate buffer is to leave the CLR free
 to relocate the managed array object during garbage collection. If the
 overhead caused by the copying is causing a significant performance
 penalty, consider pinning the managed array and passing a direct
 reference as described in the next section.</p>
<p> For more information on the subject, see the <a href="https://docs.microsoft.com/en-us/dotnet/framework/interop/default-marshaling-for-arrays">
Default Marshaling for Arrays</a> article on MSDN.</p>
<p> The P/Invoke default marshalling is supported by the <tt>
arrays_csharp.i</tt> library via the INPUT, OUTPUT and INOUT typemaps.
 Let's look at some example usage. Consider the following C function:</p>
<div class="code">
<pre>
void myArrayCopy(int *sourceArray, int *targetArray, int nitems);
</pre>
</div>
<p> We can now instruct SWIG to use the default marshalling typemaps by</p>
<div class="code">
<pre>
%include &quot;arrays_csharp.i&quot;

%apply int INPUT[]  {int *sourceArray}
%apply int OUTPUT[] {int *targetArray}
</pre>
</div>
<p> As a result, we get the following method in the module class:</p>
<div class="code">
<pre>
public static void myArrayCopy(int[] sourceArray, int[] targetArray, int nitems) {
  examplePINVOKE.myArrayCopy(sourceArray, targetArray, nitems);
}
</pre>
</div>
<p> If we look beneath the surface at the corresponding intermediary
 class code, we see that SWIG has generated code that uses attributes
 (from the System.Runtime.InteropServices namespace) to tell the CLR to
 use default marshalling for the arrays:</p>
<div class="code">
<pre>
[global::System.Runtime.InteropServices.DllImport(&quot;example&quot;, EntryPoint=&quot;CSharp_myArrayCopy&quot;)]
public static extern void myArrayCopy([global::System.Runtime.InteropServices.In, global::System.Runtime.InteropServices.MarshalAs(UnmanagedType.LPArray)]int[] jarg1, 
                                      [global::System.Runtime.InteropServices.Out, global::System.Runtime.InteropServices.MarshalAs(UnmanagedType.LPArray)]int[] jarg2,
                                       int jarg3);
</pre>
</div>
<p> As an example of passing an inout array (i.e. the target function
 will both read from and write to the array), consider this C function
 that swaps a given number of elements in the given arrays:</p>
<div class="code">
<pre>
void myArraySwap(int *array1, int *array2, int nitems);
</pre>
</div>
<p> Now, we can instruct SWIG to wrap this by</p>
<div class="code">
<pre>
%include &quot;arrays_csharp.i&quot;

%apply int INOUT[] {int *array1}
%apply int INOUT[] {int *array2}
</pre>
</div>
<p> This results in the module class method</p>
<div class="code">
<pre>
  public static void myArraySwap(int[] array1, int[] array2, int nitems) {
    examplePINVOKE.myArraySwap(array1, array2, nitems);
  }
</pre>
</div>
<p> and intermediary class method</p>
<div class="code">
<pre>
  [global::System.Runtime.InteropServices.DllImport(&quot;example&quot;, EntryPoint=&quot;CSharp_myArraySwap&quot;)]
  public static extern void myArraySwap([global::System.Runtime.InteropServices.In, global::System.Runtime.InteropServices.Out, global::System.Runtime.InteropServices.MarshalAs(UnmanagedType.LPArray)]int[] jarg1, 
                                        [global::System.Runtime.InteropServices.In, global::System.Runtime.InteropServices.Out, global::System.Runtime.InteropServices.MarshalAs(UnmanagedType.LPArray)]int[] jarg2,
                                         int jarg3);
</pre>
</div>
<h3><a name="CSharp_arrays_pinning">22.4.3 Managed arrays using pinning</a>
</h3>
<p> It is also possible to pin a given array in memory (i.e. fix its
 location in memory), obtain a direct pointer to it, and then pass this
 pointer to the wrapped C/C++ function. This approach involves no
 copying, but it makes the work of the garbage collector harder as the
 managed array object can not be relocated before the fix on the array
 is released. You should avoid fixing arrays in memory in cases where
 the control may re-enter the managed side via a callback and/or another
 thread may produce enough garbage to trigger garbage collection.</p>
<p> For more information, see the <a href="https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/fixed-statement">
fixed statement</a> in the C# language reference.</p>
<p> Now let's look at an example using pinning, thus avoiding the CLR
 making copies of the arrays passed as parameters. The <tt>
arrays_csharp.i</tt> library file again provides the required support
 via the <tt>FIXED</tt> typemaps. Let's use the same function from the
 previous section:</p>
<div class="code">
<pre>
void myArrayCopy(int *sourceArray, int *targetArray, int nitems);
</pre>
</div>
<p> We now need to declare the module class method unsafe, as we are
 using pointers:</p>
<div class="code">
<pre>
%csmethodmodifiers myArrayCopy &quot;public unsafe&quot;;
 </pre>
</div>
<p> Apply the appropriate typemaps to the array parameters:</p>
<div class="code">
<pre>
%include &quot;arrays_csharp.i&quot;

%apply int FIXED[] {int *sourceArray}
%apply int FIXED[] {int *targetArray}
</pre>
</div>
<p> Notice that there is no need for separate in, out or inout typemaps
 as is the case when using P/Invoke default marshalling.</p>
<p> As a result, we get the following method in the module class:</p>
<div class="code">
<pre>
  public unsafe static void myArrayCopy(int[] sourceArray, int[] targetArray, int nitems) {
    fixed ( int *swig_ptrTo_sourceArray = sourceArray ) {
    fixed ( int *swig_ptrTo_targetArray = targetArray ) {
    {
      examplePINVOKE.myArrayCopy((global::System.IntPtr)swig_ptrTo_sourceArray, (global::System.IntPtr)swig_ptrTo_targetArray,
                                 nitems);
    }
    }
    }
  }
</pre>
</div>
<p> On the method signature level the only difference to the version
 using P/Invoke default marshalling is the &quot;unsafe&quot; quantifier, which is
 required because we are handling pointers.</p>
<p> Also the intermediary class method looks a little different from the
 default marshalling example - the method is expecting an IntPtr as the
 parameter type.</p>
<div class="code">
<pre>
[global::System.Runtime.InteropServices.DllImport(&quot;example&quot;, EntryPoint=&quot;CSharp_myArrayCopy&quot;)]
public static extern void myArrayCopy(global::System.IntPtr jarg1, global::System.IntPtr jarg2, int jarg3);
</pre>
</div>
<h2><a name="CSharp_exceptions">22.5 C# Exceptions</a></h2>
<p> It is possible to throw a C# Exception from C/C++ code. SWIG already
 provides the framework for throwing C# exceptions if it is able to
 detect that a C++ exception could be thrown. Automatically detecting
 that a C++ exception could be thrown is only possible when a C++
 exception specification is used, see <a href="#SWIGPlus_exception_specifications">
Exception specifications</a>. The <a href="#Customization_exception">
Exception handling with %exception</a> section details the <tt>
%exception</tt> feature. Customised code for handling exceptions with or
 without a C++ exception specification is possible and the details
 follow. However anyone wishing to do this should be familiar with the
 contents of the sections referred to above.</p>
<p> Unfortunately a C# exception cannot simply be thrown from unmanaged
 code for a variety of reasons. Most notably being that throwing a C#
 exception results in exceptions being thrown across the C PInvoke
 interface and C does not understand exceptions. The design revolves
 around a C# exception being constructed and stored as a pending
 exception, to be thrown only when the unmanaged code has completed.
 Implementing this is a tad involved and there are thus some unusual
 typemap constructs. Some practical examples follow and they should be
 read in conjunction with the rest of this section.</p>
<p> First some details about the design that must be followed. Each
 typemap or feature that generates<b> unmanaged code</b> supports an
 attribute called <tt>canthrow</tt>. This is simply a flag which when
 set indicates that the code in the typemap/feature has code which might
 want to throw a C# exception. The code in the typemap/feature can then
 raise a C# exception by calling one of the C functions, <tt>
SWIG_CSharpSetPendingException()</tt> or <tt>
SWIG_CSharpSetPendingExceptionArgument()</tt>. When called, the function
 makes a callback into the managed world via a delegate. The callback
 creates and stores an exception ready for throwing when the unmanaged
 code has finished. The typemap/feature unmanaged code is then expected
 to force an immediate return from the unmanaged wrapper function, so
 that the pending managed exception can then be thrown. The support code
 has been carefully designed to be efficient as well as thread-safe.
 However to achieve the goal of efficiency requires some optional code
 generation in the<b> managed code</b> typemaps. Code to check for
 pending exceptions is generated if and only if the unmanaged code has
 code to set a pending exception, that is if the <tt>canthrow</tt>
 attribute is set. The optional managed code is generated using the <tt>
excode</tt> typemap attribute and <tt>$excode</tt> special variable in
 the relevant managed code typemaps. Simply, if any relevant unmanaged
 code has the <tt>canthrow</tt> attribute set, then any occurrences of <tt>
$excode</tt> is replaced with the code in the <tt>excode</tt> attribute.
 If the <tt>canthrow</tt> attribute is not set, then any occurrences of <tt>
$excode</tt> are replaced with nothing.</p>
<p> The prototypes for the <tt>SWIG_CSharpSetPendingException()</tt> and
 <tt>SWIG_CSharpSetPendingExceptionArgument()</tt> functions are</p>
<div class="code">
<pre>
static void SWIG_CSharpSetPendingException(SWIG_CSharpExceptionCodes code,
                                           const char *msg);

static void SWIG_CSharpSetPendingExceptionArgument(SWIG_CSharpExceptionArgumentCodes code,
                                                   const char *msg,
                                                   const char *param_name);
</pre>
</div>
<p> The first parameter defines which .NET exceptions can be thrown:</p>
<div class="code">
<pre>
typedef enum {
  SWIG_CSharpApplicationException,
  SWIG_CSharpArithmeticException,
  SWIG_CSharpDivideByZeroException,
  SWIG_CSharpIndexOutOfRangeException,
  SWIG_CSharpInvalidCastException,
  SWIG_CSharpInvalidOperationException,
  SWIG_CSharpIOException,
  SWIG_CSharpNullReferenceException,
  SWIG_CSharpOutOfMemoryException,
  SWIG_CSharpOverflowException,
  SWIG_CSharpSystemException
} SWIG_CSharpExceptionCodes;

typedef enum {
  SWIG_CSharpArgumentException,
  SWIG_CSharpArgumentNullException,
  SWIG_CSharpArgumentOutOfRangeException,
} SWIG_CSharpExceptionArgumentCodes;
</pre>
</div>
<p> where, for example, <tt>SWIG_CSharpApplicationException</tt>
 corresponds to the .NET exception, <tt>ApplicationException</tt>. The <tt>
msg</tt> and <tt>param_name</tt> parameters contain the C# exception
 message and parameter name associated with the exception.</p>
<p> The <tt>%exception</tt> feature in C# has the <tt>canthrow</tt>
 attribute set. The <tt>%csnothrowexception</tt> feature is like <tt>
%exception</tt>, but it does not have the <tt>canthrow</tt> attribute
 set so should only be used when a C# exception is not created.</p>
<h3><a name="CSharp_exception_example_check_typemap">22.5.1 C# exception
 example using &quot;check&quot; typemap</a></h3>
<p> Let's say we have the following simple C++ method:</p>
<div class="code">
<pre>
void positivesonly(int number);
</pre>
</div>
<p> and we want to check that the input <tt>number</tt> is always
 positive and if not throw a C# <tt>ArgumentOutOfRangeException</tt>.
 The &quot;check&quot; typemap is designed for checking input parameters. Below
 you will see the <tt>canthrow</tt> attribute is set because the code
 contains a call to <tt>SWIG_CSharpSetPendingExceptionArgument()</tt>.
 The full example follows:</p>
<div class="code">
<pre>
%module example

%typemap(check, canthrow=1) int number %{
if ($1 &lt; 0) {
  SWIG_CSharpSetPendingExceptionArgument(SWIG_CSharpArgumentOutOfRangeException,
                                         &quot;only positive numbers accepted&quot;, &quot;number&quot;);
  return $null;
}
// SWIGEXCODE is a macro used by many other csout typemaps
%define SWIGEXCODE
 &quot;\n    if ($modulePINVOKE.SWIGPendingException.Pending)&quot;
 &quot;\n      throw $modulePINVOKE.SWIGPendingException.Retrieve();&quot;
%enddef
%typemap(csout, excode=SWIGEXCODE) void {
    $imcall;$excode
  }
%}

%inline %{

void positivesonly(int number) {
}

%}
</pre>
</div>
<p> When the following C# code is executed:</p>
<div class="code">
<pre>
public class runme {
  static void Main() {
    example.positivesonly(-1);
  }
}
</pre>
</div>
<p> The exception is thrown:</p>
<div class="code">
<pre>
Unhandled Exception: System.ArgumentOutOfRangeException: only positive numbers accepted
Parameter name: number
in &lt;0x00034&gt; example:positivesonly (int)
in &lt;0x0000c&gt; runme:Main ()
</pre>
</div>
<p> Now let's analyse the generated code to gain a fuller understanding
 of the typemaps. The generated unmanaged C++ code is:</p>
<div class="code">
<pre>
SWIGEXPORT void SWIGSTDCALL CSharp_positivesonly(int jarg1) {
  int arg1 ;

  arg1 = (int)jarg1;

  if (arg1 &lt; 0) {
    SWIG_CSharpSetPendingExceptionArgument(SWIG_CSharpArgumentOutOfRangeException,
      &quot;only positive numbers accepted&quot;, &quot;number&quot;);
    return ;
  }

  positivesonly(arg1);

}
</pre>
</div>
<p> This largely comes from the &quot;check&quot; typemap. The managed code in the
 module class is:</p>
<div class="code">
<pre>
public class example {
  public static void positivesonly(int number) {
    examplePINVOKE.positivesonly(number);
    if (examplePINVOKE.SWIGPendingException.Pending)
      throw examplePINVOKE.SWIGPendingException.Retrieve();
  }

}
</pre>
</div>
<p> This comes largely from the &quot;csout&quot; typemap.</p>
<p> The &quot;csout&quot; typemap is the same as the default void &quot;csout&quot; typemap
 so is not strictly necessary for the example. However, it is shown to
 demonstrate what managed output code typemaps should contain, that is,
 a <tt>$excode</tt> special variable and an <tt>excode</tt> attribute.
 Also note that <tt>$excode</tt> is expanded into the code held in the <tt>
excode</tt> attribute. The <tt>$imcall</tt> as always expands into <tt>
examplePINVOKE.positivesonly(number)</tt>. The exception support code in
 the intermediary class, <tt>examplePINVOKE</tt>, is not shown, but is
 contained within the inner classes, <tt>SWIGPendingException</tt> and <tt>
SWIGExceptionHelper</tt> and is always generated. These classes can be
 seen in any of the generated wrappers. However, all that is required of
 a user is as demonstrated in the &quot;csin&quot; typemap above. That is, is to
 check <tt>SWIGPendingException.Pending</tt> and to throw the exception
 returned by <tt>SWIGPendingException.Retrieve()</tt>.</p>
<p> If the &quot;check&quot; typemap did not exist, then the following module
 class would instead be generated:</p>
<div class="code">
<pre>
public class example {
  public static void positivesonly(int number) {
    examplePINVOKE.positivesonly(number);
  }

}
</pre>
</div>
<p> Here we see the pending exception checking code is omitted. In fact,
 the code above would be generated if the <tt>canthrow</tt> attribute
 was not in the &quot;check&quot; typemap, such as:</p>
<div class="code">
<pre>
%typemap(check) int number %{
if ($1 &lt; 0) {
  SWIG_CSharpSetPendingExceptionArgument(SWIG_CSharpArgumentOutOfRangeException,
                                         &quot;only positive numbers accepted&quot;, &quot;number&quot;);
  return $null;
}
%}
</pre>
</div>
<p> Note that if SWIG detects you have used <tt>
SWIG_CSharpSetPendingException()</tt> or <tt>
SWIG_CSharpSetPendingExceptionArgument()</tt> without setting the <tt>
canthrow</tt> attribute you will get a warning message similar to</p>
<div class="code">
<pre>
example.i:21: Warning 845: Unmanaged code contains a call to a SWIG_CSharpSetPendingException
method and C# code does not handle pending exceptions via the canthrow attribute.
</pre>
</div>
<p> Actually it will issue this warning for any function beginning with <tt>
SWIG_CSharpSetPendingException</tt>.</p>
<h3><a name="CSharp_exception_example_percent_exception">22.5.2 C#
 exception example using %exception</a></h3>
<p> Let's consider a similar, but more common example that throws a C++
 exception from within a wrapped function. We can use <tt>%exception</tt>
 as mentioned in <a href="#Customization_exception">Exception handling
 with %exception</a>.</p>
<div class="code">
<pre>
%exception negativesonly(int value) %{
try {
  $action
} catch (std::out_of_range e) {
  SWIG_CSharpSetPendingException(SWIG_CSharpApplicationException, e.what());
  return $null;
}
%}

%inline %{
#include &lt;stdexcept&gt;
void negativesonly(int value) {
  if (value &gt;= 0)
    throw std::out_of_range(&quot;number should be negative&quot;);
}
%}
</pre>
</div>
<p> The generated unmanaged code this time catches the C++ exception and
 converts it into a C# <tt>ApplicationException</tt>.</p>
<div class="code">
<pre>
SWIGEXPORT void SWIGSTDCALL CSharp_negativesonly(int jarg1) {
  int arg1 ;

  arg1 = (int)jarg1;

  try {
    negativesonly(arg1);

  } catch (std::out_of_range e) {
    SWIG_CSharpSetPendingException(SWIG_CSharpApplicationException, e.what());
    return ;
  }
}
</pre>
</div>
<p> The managed code generated does check for the pending exception as
 mentioned earlier as the C# version of <tt>%exception</tt> has the <tt>
canthrow</tt> attribute set by default:</p>
<div class="code">
<pre>
  public static void negativesonly(int value) {
    examplePINVOKE.negativesonly(value);
    if (examplePINVOKE.SWIGPendingException.Pending)
      throw examplePINVOKE.SWIGPendingException.Retrieve();
  }
</pre>
</div>
<h3><a name="CSharp_exception_example_exception_specifications">22.5.3
 C# exception example using exception specifications</a></h3>
<p> When C++ exception specifications are used, SWIG is able to detect
 that the method might throw an exception. By default SWIG will
 automatically generate code to catch the exception and convert it into
 a managed <tt>ApplicationException</tt>, as defined by the default
 &quot;throws&quot; typemaps. The following example has a user supplied &quot;throws&quot;
 typemap which is used whenever an exception specification contains a <tt>
std::out_of_range</tt>, such as the <tt>evensonly</tt> method below.</p>
<div class="code">
<pre>
%typemap(throws, canthrow=1) std::out_of_range {
  SWIG_CSharpSetPendingExceptionArgument(SWIG_CSharpArgumentException, $1.what(), NULL);
  return $null;
}

%inline %{
#include &lt;stdexcept&gt;
void evensonly(int input) throw (std::out_of_range) {
  if (input%2 != 0)
    throw std::out_of_range(&quot;number is not even&quot;);
}
%}
</pre>
</div>
<p> Note that the type for the throws typemap is the type in the
 exception specification. SWIG generates a try catch block with the
 throws typemap code in the catch handler.</p>
<div class="code">
<pre>
SWIGEXPORT void SWIGSTDCALL CSharp_evensonly(int jarg1) {
  int arg1 ;

  arg1 = (int)jarg1;
  try {
    evensonly(arg1);
  }
  catch(std::out_of_range &amp;_e) {
    {
      SWIG_CSharpSetPendingExceptionArgument(SWIG_CSharpArgumentException, (&amp;_e)-&gt;what(), NULL);
      return ;
    }
  }
}
</pre>
</div>
<p> Multiple catch handlers are generated should there be more than one
 exception specifications declared.</p>
<h3><a name="CSharp_custom_application_exception">22.5.4 Custom C#
 ApplicationException example</a></h3>
<p> This example involves a user defined exception. The conventional
 .NET exception handling approach is to create a custom <tt>
ApplicationException</tt> and throw it in your application. The goal in
 this example is to convert the STL <tt>std::out_of_range</tt> exception
 into one of these custom .NET exceptions.</p>
<p> The default exception handling is quite easy to use as the <tt>
SWIG_CSharpSetPendingException()</tt> and <tt>
SWIG_CSharpSetPendingExceptionArgument()</tt> methods are provided by
 SWIG. However, for a custom C# exception, the boiler plate code that
 supports these functions needs replicating. In essence this consists of
 some C/C++ code and C# code. The C/C++ code can be generated into the
 wrapper file using the <tt>%insert(runtime)</tt> directive and the C#
 code can be generated into the intermediary class using the <tt>
imclasscode</tt> pragma as follows:</p>
<div class="code">
<pre>
%insert(runtime) %{
  // Code to handle throwing of C# CustomApplicationException from C/C++ code.
  // The equivalent delegate to the callback, CSharpExceptionCallback_t, is CustomExceptionDelegate
  // and the equivalent customExceptionCallback instance is customDelegate
  typedef void (SWIGSTDCALL* CSharpExceptionCallback_t)(const char *);
  CSharpExceptionCallback_t customExceptionCallback = NULL;

  extern &quot;C&quot; SWIGEXPORT
  void SWIGSTDCALL CustomExceptionRegisterCallback(CSharpExceptionCallback_t customCallback) {
    customExceptionCallback = customCallback;
  }

  // Note that SWIG detects any method calls named starting with
  // SWIG_CSharpSetPendingException for warning 845
  static void SWIG_CSharpSetPendingExceptionCustom(const char *msg) {
    customExceptionCallback(msg);
  }
%}

%pragma(csharp) imclasscode=%{
  class CustomExceptionHelper {
    // C# delegate for the C/C++ customExceptionCallback
    public delegate void CustomExceptionDelegate(string message);
    static CustomExceptionDelegate customDelegate =
                                   new CustomExceptionDelegate(SetPendingCustomException);

    [global::System.Runtime.InteropServices.DllImport(&quot;$dllimport&quot;, EntryPoint=&quot;CustomExceptionRegisterCallback&quot;)]
    public static extern
           void CustomExceptionRegisterCallback(CustomExceptionDelegate customCallback);

    static void SetPendingCustomException(string message) {
      SWIGPendingException.Set(new CustomApplicationException(message));
    }

    static CustomExceptionHelper() {
      CustomExceptionRegisterCallback(customDelegate);
    }
  }
  static CustomExceptionHelper exceptionHelper = new CustomExceptionHelper();
%}
</pre>
</div>
<p> The method stored in the C# delegate instance, <tt>customDelegate</tt>
 is what gets called by the C/C++ callback. However, the equivalent to
 the C# delegate, that is the C/C++ callback, needs to be assigned
 before any unmanaged code is executed. This is achieved by putting the
 initialisation code in the intermediary class. Recall that the
 intermediary class contains all the PInvoke methods, so the static
 variables in the intermediary class will be initialised before any of
 the PInvoke methods in this class are called. The <tt>exceptionHelper</tt>
 static variable ensures the C/C++ callback is initialised with the
 value in <tt>customDelegate</tt> by calling the <tt>
CustomExceptionRegisterCallback</tt> method in the <tt>
CustomExceptionHelper</tt> static constructor. Once this has been done,
 unmanaged code can make callbacks into the managed world as <tt>
customExceptionCallback</tt> will be initialised with a valid
 callback/delegate. Any calls to <tt>
SWIG_CSharpSetPendingExceptionCustom()</tt> will make the callback to
 create the pending exception in the same way that <tt>
SWIG_CSharpSetPendingException()</tt> and <tt>
SWIG_CSharpSetPendingExceptionArgument()</tt> does. In fact the method
 has been similarly named so that SWIG can issue the warning about
 missing <tt>canthrow</tt> attributes as discussed earlier. It is an
 invaluable warning as it is easy to forget the <tt>canthrow</tt>
 attribute when writing typemaps/features.</p>
<p> The <tt>SWIGPendingException</tt> helper class is not shown, but is
 generated as an inner class into the intermediary class. It stores the
 pending exception in Thread Local Storage so that the exception
 handling mechanism is thread safe.</p>
<p> The boiler plate code above must be used in addition to a
 handcrafted <tt>CustomApplicationException</tt>:</p>
<div class="code">
<pre>
// Custom C# Exception
class CustomApplicationException : global::System.ApplicationException {
  public CustomApplicationException(string message) 
    : base(message) {
  }
}
</pre>
</div>
<p> and the SWIG interface code:</p>
<div class="code">
<pre>
%typemap(throws, canthrow=1) std::out_of_range {
  SWIG_CSharpSetPendingExceptionCustom($1.what());
  return $null;
}

%inline %{
void oddsonly(int input) throw (std::out_of_range) {
  if (input%2 != 1)
    throw std::out_of_range(&quot;number is not odd&quot;);
}
%}
</pre>
</div>
<p> The &quot;throws&quot; typemap now simply calls our new <tt>
SWIG_CSharpSetPendingExceptionCustom()</tt> function so that the
 exception can be caught, as such:</p>
<div class="code">
<pre>
try {
  example.oddsonly(2);
} catch (CustomApplicationException e) {
  ...
}
</pre>
</div>
<h2><a name="CSharp_directors">22.6 C# Directors</a></h2>
<p> The SWIG directors feature adds extra code to the generated C# proxy
 classes that enable these classes to be used in cross-language
 polymorphism. Essentially, it enables unmanaged C++ code to call back
 into managed code for virtual methods so that a C# class can derive
 from a wrapped C++ class.</p>
<p> The following sections provide information on the C# director
 implementation and contain most of the information required to use the
 C# directors. However, the <a href="#Java_directors">Java directors</a>
 section should also be read in order to gain more insight into
 directors.</p>
<h3><a name="CSharp_directors_example">22.6.1 Directors example</a></h3>
<p> Imagine we are wrapping a C++ base class, <tt>Base</tt>, from which
 we would like to inherit in C#. Such a class is shown below as well as
 another class, <tt>Caller</tt>, which calls the virtual method <tt>
UIntMethod</tt> from pure unmanaged C++ code.</p>
<div class="code">
<pre>
// file: example.h
class Base {
public:
  virtual ~Base() {}

  virtual unsigned int UIntMethod(unsigned int x) {
    std::cout &lt;&lt; &quot;Base - UIntMethod(&quot; &lt;&lt; x &lt;&lt; &quot;)&quot; &lt;&lt; std::endl;
    return x;
  }
  virtual void BaseBoolMethod(const Base &amp;b, bool flag) {}
};

class Caller {
public:
  Caller(): m_base(0) {}
  ~Caller() { delBase(); }
  void set(Base *b) { delBase(); m_base = b; }
  void reset() { m_base = 0; }
  unsigned int UIntMethodCall(unsigned int x) { return m_base-&gt;UIntMethod(x); }

private:
  Base *m_base;
  void delBase() { delete m_base; m_base = 0; }
};
</pre>
</div>
<p> The director feature is turned off by default and the following
 simple interface file shows how directors are enabled for the class <tt>
Base</tt>.</p>
<div class="code">
<pre>
/* File : example.i */
%module(directors=&quot;1&quot;) example
%{
#include &quot;example.h&quot;
%}

%feature(&quot;director&quot;) Base;

%include &quot;example.h&quot;
</pre>
</div>
<p> The following is a C# class inheriting from <tt>Base</tt>:</p>
<div class="code">
<pre>
public class CSharpDerived : Base
{
  public override uint UIntMethod(uint x)
  {
    Console.WriteLine(&quot;CSharpDerived - UIntMethod({0})&quot;, x);
    return x;
  }
}
</pre>
</div>
<p> The <tt>Caller</tt> class can demonstrate the <tt>UIntMethod</tt>
 method being called from unmanaged code using the following C# code:</p>
<div class="targetlang">
<pre>
public class runme
{
  static void Main() 
  {
    Caller myCaller = new Caller();

    // Test pure C++ class
    using (Base myBase = new Base())
    {
      makeCalls(myCaller, myBase);
    }

    // Test director / C# derived class
    using (Base myBase = new CSharpDerived())
    {
      makeCalls(myCaller, myBase);
    }
  }

  static void makeCalls(Caller myCaller, Base myBase)
  {
    myCaller.set(myBase);
    myCaller.UIntMethodCall(123);
    myCaller.reset();
  }
}
</pre>
</div>
<p> If the above is run, the output is then:</p>
<div class="shell">
<pre>
Base - UIntMethod(123)
CSharpDerived - UIntMethod(123)
</pre>
</div>
<h3><a name="CSharp_directors_implementation">22.6.2 Directors
 implementation</a></h3>
<p> The previous section demonstrated a simple example where the virtual
 <tt>UIntMethod</tt> method was called from C++ code, even when the
 overridden method is implemented in C#. The intention of this section
 is to gain an insight into how the director feature works. It shows the
 generated code for the two virtual methods, <tt>UIntMethod</tt> and <tt>
BaseBoolMethod</tt>, when the director feature is enabled for the <tt>
Base</tt> class.</p>
<p> Below is the generated C# <tt>Base</tt> director class.</p>
<div class="code">
<pre>
public class Base : global::System.IDisposable {
  private global::System.Runtime.InteropServices.HandleRef swigCPtr;
  protected bool swigCMemOwn;

  internal Base(global::System.IntPtr cPtr, bool cMemoryOwn) {
    swigCMemOwn = cMemoryOwn;
    swigCPtr = new global::System.Runtime.InteropServices.HandleRef(this, cPtr);
  }

  internal static global::System.Runtime.InteropServices.HandleRef getCPtr(Base obj) {
    return (obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr;
  }

  ~Base() {
    Dispose();
  }

  public virtual void Dispose() {
    lock(this) {
      if(swigCPtr.Handle != global::System.IntPtr.Zero &amp;&amp; swigCMemOwn) {
        swigCMemOwn = false;
        examplePINVOKE.delete_Base(swigCPtr);
      }
      swigCPtr = new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero);
      global::System.GC.SuppressFinalize(this);
    }
  }

  public virtual uint UIntMethod(uint x) {
    uint ret = examplePINVOKE.Base_UIntMethod(swigCPtr, x);
    return ret;
  }

  public virtual void BaseBoolMethod(Base b, bool flag) {
    examplePINVOKE.Base_BaseBoolMethod(swigCPtr, Base.getCPtr(b), flag);
    if (examplePINVOKE.SWIGPendingException.Pending)
      throw examplePINVOKE.SWIGPendingException.Retrieve();
  }

  public Base() : this(examplePINVOKE.new_Base(), true) {
    SwigDirectorConnect();
  }

  private void SwigDirectorConnect() {
    if (SwigDerivedClassHasMethod(&quot;UIntMethod&quot;, swigMethodTypes0))
      swigDelegate0 = new SwigDelegateBase_0(SwigDirectorMethodUIntMethod);
    if (SwigDerivedClassHasMethod(&quot;BaseBoolMethod&quot;, swigMethodTypes1))
      swigDelegate1 = new SwigDelegateBase_1(SwigDirectorMethodBaseBoolMethod);
    examplePINVOKE.Base_director_connect(swigCPtr, swigDelegate0, swigDelegate1);
  }

  private bool SwigDerivedClassHasMethod(string methodName, global::System.global::System.Type[] methodTypes) {
    System.Reflection.MethodInfo methodInfo = this.GetType().GetMethod(methodName, methodTypes);
    bool hasDerivedMethod = methodInfo.DeclaringType.IsSubclassOf(typeof(Base));
    return hasDerivedMethod;
  }

  private uint SwigDirectorMethodUIntMethod(uint x) {
    return UIntMethod(x);
  }

  private void SwigDirectorMethodBaseBoolMethod(global::System.IntPtr b, bool flag) {
    BaseBoolMethod(new Base(b, false), flag);
  }

  public delegate uint SwigDelegateBase_0(uint x);
  public delegate void SwigDelegateBase_1(global::System.IntPtr b, bool flag);

  private SwigDelegateBase_0 swigDelegate0;
  private SwigDelegateBase_1 swigDelegate1;

  private static global::System.Type[] swigMethodTypes0 = new global::System.Type[] { typeof(uint) };
  private static global::System.Type[] swigMethodTypes1 = new global::System.Type[] { typeof(Base), typeof(bool) };
}
</pre>
</div>
<p> Everything from the <tt>SwigDirectorConnect()</tt> method and below
 is code that is only generated when directors are enabled. The design
 comprises a C# delegate being initialised for each virtual method on
 construction of the class. Let's examine the <tt>BaseBoolMethod</tt>.</p>
<p> In the <tt>Base</tt> constructor a call is made to <tt>
SwigDirectorConnect()</tt> which contains the initialisation code for
 all the virtual methods. It uses a support method, <tt>
SwigDerivedClassHasMethod()</tt>, which simply uses reflection to
 determine if the named method, BaseBoolMethod, with the list of
 required parameter types, exists in a subclass. If it does not exist,
 the delegate is not initialised as there is no need for unmanaged code
 to call back into managed C# code. However, if there is an overridden
 method in any subclass, the delegate is required. It is then
 initialised to the <tt>SwigDirectorMethodBaseBoolMethod</tt> which in
 turn will call <tt>BaseBoolMethod</tt> if invoked. The delegate is not
 initialised to the <tt>BaseBoolMethod</tt> directly as quite often
 types will need marshalling from the unmanaged type to the managed type
 in which case an intermediary method (<tt>
SwigDirectorMethodBaseBoolMethod</tt>) is required for the marshalling.
 In this case, the C# <tt>Base</tt> class needs to be created from the
 unmanaged <tt>IntPtr</tt> type.</p>
<p> The last thing that <tt>SwigDirectorConnect()</tt> does is to pass
 the delegates to the unmanaged code. It calls the intermediary method <tt>
Base_director_connect()</tt> which is really a call to the C function <tt>
CSharp_Base_director_connect()</tt>. This method simply maps each C#
 delegate onto a C function pointer.</p>
<div class="code">
<pre>
SWIGEXPORT void SWIGSTDCALL CSharp_Base_director_connect(void *objarg, 
                                        SwigDirector_Base::SWIG_Callback0_t callback0,
                                        SwigDirector_Base::SWIG_Callback1_t callback1) {
  Base *obj = (Base *)objarg;
  SwigDirector_Base *director = dynamic_cast&lt;SwigDirector_Base *&gt;(obj);
  if (director) {
    director-&gt;swig_connect_director(callback0, callback1);
  }
}

class SwigDirector_Base : public Base, public Swig::Director {
public:
  SwigDirector_Base();
  virtual unsigned int UIntMethod(unsigned int x);
  virtual ~SwigDirector_Base();
  virtual void BaseBoolMethod(Base const &amp;b, bool flag);

  typedef unsigned int (SWIGSTDCALL* SWIG_Callback0_t)(unsigned int);
  typedef void (SWIGSTDCALL* SWIG_Callback1_t)(void *, unsigned int);
  void swig_connect_director(SWIG_Callback0_t callbackUIntMethod,
                             SWIG_Callback1_t callbackBaseBoolMethod);

private:
  SWIG_Callback0_t swig_callbackUIntMethod;
  SWIG_Callback1_t swig_callbackBaseBoolMethod;
  void swig_init_callbacks();
};

void SwigDirector_Base::swig_connect_director(SWIG_Callback0_t callbackUIntMethod, 
                                              SWIG_Callback1_t callbackBaseBoolMethod) {
  swig_callbackUIntMethod = callbackUIntMethod;
  swig_callbackBaseBoolMethod = callbackBaseBoolMethod;
}
</pre>
</div>
<p> Note that for each director class SWIG creates an unmanaged director
 class for making the callbacks. For example <tt>Base</tt> has <tt>
SwigDirector_Base</tt> and <tt>SwigDirector_Base</tt> is derived from <tt>
Base</tt>. Should a C# class be derived from <tt>Base</tt>, the
 underlying C++ <tt>SwigDirector_Base</tt> is created rather than <tt>
Base</tt>. The <tt>SwigDirector_Base</tt> class then implements all the
 virtual methods, redirecting calls up to managed code if the
 callback/delegate is non-zero. The implementation of <tt>
SwigDirector_Base::BaseBoolMethod</tt> shows this - the callback is made
 by invoking the <tt>swig_callbackBaseBoolMethod</tt> function pointer:</p>
<div class="code">
<pre>
void SwigDirector_Base::BaseBoolMethod(Base const &amp;b, bool flag) {
  void * jb = 0 ;
  unsigned int jflag  ;
  
  if (!swig_callbackBaseBoolMethod) {
    Base::BaseBoolMethod(b, flag);
    return;
  } else {
    jb = (Base *) &amp;b; 
    jflag = flag;
    swig_callbackBaseBoolMethod(jb, jflag);
  }
}
</pre>
</div>
<p> The delegates from the above example are <tt>public</tt> by default:</p>
<div class="code">
<pre>
  public delegate uint SwigDelegateBase_0(uint x);
  public delegate void SwigDelegateBase_1(global::System.IntPtr b, bool flag);
</pre>
</div>
<p> These can be changed if desired via the <tt>
csdirectordelegatemodifiers</tt> <a href="#Customization_features">
%feature directive</a>. For example, using <tt>
%feature(&quot;csdirectordelegatemodifiers&quot;) &quot;internal&quot;</tt> before SWIG
 parses the Base class will change all the delegates to <tt>internal</tt>
:</p>
<div class="code">
<pre>
  internal delegate uint SwigDelegateBase_0(uint x);
  internal delegate void SwigDelegateBase_1(global::System.IntPtr b, bool flag);
</pre>
</div>
<h3><a name="CSharp_director_caveats">22.6.3 Director caveats</a></h3>
<p> There is a subtle gotcha with directors. If default parameters are
 used, it is recommended to follow a pattern of always calling a single
 method in any C# derived class. An example will clarify this and the
 reasoning behind the recommendation. Consider the following C++ class
 wrapped as a director class:</p>
<div class="code">
<pre>
class Defaults {
public:
  virtual ~Defaults();
  virtual void DefaultMethod(int a=-100);
};
</pre>
</div>
<p> Recall that C++ methods with default parameters generate overloaded
 methods for each defaulted parameter, so a C# derived class can be
 created with two <tt>DefaultMethod</tt> override methods:</p>
<div class="code">
<pre>
public class CSharpDefaults : Defaults
{
  public override void DefaultMethod()
  {
    DefaultMethod(-100); // note C++ default value used
  }
  public override void DefaultMethod(int x)
  {
  }
}
</pre>
</div>
<p> It may not be clear at first, but should a user intend to call <tt>
CSharpDefaults.DefaultMethod()</tt> from C++, a call is actually made to
 <tt>CSharpDefaults.DefaultMethod(int)</tt>. This is because the initial
 call is made in C++ and therefore the <tt>DefaultMethod(int)</tt>
 method will be called as is expected with C++ calls to methods with
 defaults, with the default being set to -100. The callback/delegate
 matching this method is of course the overloaded method <tt>
DefaultMethod(int)</tt>. However, a call from C# to <tt>
CSharpDefaults.DefaultMethod()</tt> will of course call this exact
 method and in order for behaviour to be consistent with calls from C++,
 the implementation should pass the call on to <tt>
CSharpDefaults.DefaultMethod(int)</tt>using the C++ default value, as
 shown above.</p>
<h2><a name="CSharp_multiple_modules">22.7 Multiple modules</a></h2>
<p> When using <a href="#Modules">multiple modules</a> it is possible to
 compile each SWIG generated wrapper into a different assembly. However,
 by default the generated code may not compile if generated classes in
 one assembly use generated classes in another assembly. The visibility
 of the <tt>getCPtr()</tt> and pointer constructor generated from the <tt>
csbody</tt> typemaps needs changing. The default visibility is <tt>
internal</tt> but it needs to be <tt>public</tt> for access from a
 different assembly. Just changing 'internal' to 'public' in the typemap
 achieves this. Two macros are available in <tt>csharp.swg</tt> to make
 this easier and using them is the preferred approach over simply
 copying the typemaps and modifying as this is forward compatible with
 any changes in the <tt>csbody</tt> typemap in future versions of SWIG.
 The macros are for the proxy and typewrapper classes and can
 respectively be used to to make the method and constructor public:</p>
<div class="code">
<pre>
  SWIG_CSBODY_PROXY(public, public, SWIGTYPE)
  SWIG_CSBODY_TYPEWRAPPER(public, public, public, SWIGTYPE)
</pre>
</div>
<p> Alternatively, instead of exposing these as public, consider using
 the <tt>[assembly:InternalsVisibleTo(&quot;Name&quot;)]</tt> attribute available
 in the .NET framework when you know which assemblies these can be
 exposed to. Another approach would be to make these public, but also to
 hide them from intellisense by using the <tt>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
</tt> attribute if you don't want users to easily stumble upon these so
 called 'internal workings' of the wrappers.</p>
<h2><a name="CSharp_typemap_examples">22.8 C# Typemap examples</a></h2>
 This section includes a few examples of typemaps. For more examples,
 you might look at the files &quot;<tt>csharp.swg</tt>&quot; and &quot;<tt>typemaps.i</tt>
&quot; in the SWIG library.
<h3><a name="CSharp_memory_management_member_variables">22.8.1 Memory
 management when returning references to member variables</a></h3>
<p> This example shows how to prevent premature garbage collection of
 objects when the underlying C++ class returns a pointer or reference to
 a member variable. The example is a direct equivalent to this <a href="#Java_memory_management_objects">
Java equivalent</a>.</p>
<p> Consider the following C++ code:</p>
<div class="code">
<pre>
struct Wheel {
  int size;
  Wheel(int sz = 0) : size(sz) {}
};

class Bike {
  Wheel wheel;
public:
  Bike(int val) : wheel(val) {}
  Wheel&amp; getWheel() { return wheel; }
};
</pre>
</div>
<p> and the following usage from C# after running the code through SWIG:</p>
<div class="code">
<pre>
  Wheel wheel = new Bike(10).getWheel();
  Console.WriteLine(&quot;wheel size: &quot; + wheel.size);
  // Simulate a garbage collection
  global::System.GC.Collect();
  global::System.GC.WaitForPendingFinalizers();
  global::System.Console.WriteLine(&quot;wheel size: &quot; + wheel.size);
</pre>
</div>
<p> Don't be surprised that if the resulting output gives strange
 results such as...</p>
<div class="shell">
<pre>
wheel size: 10
wheel size: 135019664
</pre>
</div>
<p> What has happened here is the garbage collector has collected the <tt>
Bike</tt> instance as it doesn't think it is needed any more. The proxy
 instance, <tt>wheel</tt>, contains a reference to memory that was
 deleted when the <tt>Bike</tt> instance was collected. In order to
 prevent the garbage collector from collecting the <tt>Bike</tt>
 instance a reference to the <tt>Bike</tt> must be added to the <tt>
wheel</tt> instance. You can do this by adding the reference when the <tt>
getWheel()</tt> method is called using the following typemaps.</p>
<div class="code">
<pre>
%typemap(cscode) Wheel %{
  // Ensure that the GC doesn't collect any Bike instance set from C#
  private Bike bikeReference;
  internal void addReference(Bike bike) {
    bikeReference = bike;
  }
%}

// Add a C# reference to prevent premature garbage collection and resulting use
// of dangling C++ pointer. Intended for methods that return pointers or
// references to a member variable.
%typemap(csout, excode=SWIGEXCODE) Wheel&amp; getWheel {
    global::System.IntPtr cPtr = $imcall;$excode
    $csclassname ret = null;
    if (cPtr != global::System.IntPtr.Zero) {
      ret = new $csclassname(cPtr, $owner);
      ret.addReference(this);
    }
    return ret;
  }
</pre>
</div>
<p> The code in the first typemap gets added to the <tt>Wheel</tt> proxy
 class. The code in the second typemap constitutes the bulk of the code
 in the generated <tt>getWheel()</tt> function:</p>
<div class="code">
<pre>
public class Wheel : global::System.IDisposable {
  ...
  // Ensure that the GC doesn't collect any Bike instance set from C#
  private Bike bikeReference;
  internal void addReference(Bike bike) {
    bikeReference = bike;
  }
}

public class Bike : global::System.IDisposable {
  ...
  public Wheel getWheel() {
    global::System.IntPtr cPtr = examplePINVOKE.Bike_getWheel(swigCPtr);
    Wheel ret = null;
    if (cPtr != global::System.IntPtr.Zero) {
      ret = new Wheel(cPtr, false);
      ret.addReference(this);
    }
    return ret;
  }
}
</pre>
</div>
<p> Note the <tt>addReference</tt> call.</p>
<h3><a name="CSharp_memory_management_objects">22.8.2 Memory management
 for objects passed to the C++ layer</a></h3>
<p> The example is a direct equivalent to this <a href="#Java_memory_management_objects">
Java equivalent</a>. Managing memory can be tricky when using C++ and C#
 proxy classes. The previous example shows one such case and this
 example looks at memory management for a class passed to a C++ method
 which expects the object to remain in scope after the function has
 returned. Consider the following two C++ classes:</p>
<div class="code">
<pre>
struct Element {
  int value;
  Element(int val) : value(val) {}
};
class Container {
  Element* element;
public:
  Container() : element(0) {}
  void setElement(Element* e) { element = e; }
  Element* getElement() { return element; }
};
</pre>
</div>
<p> and usage from C++</p>
<div class="code">
<pre>
  Container container;
  Element element(20);
  container.setElement(&amp;element);
  cout &lt;&lt; &quot;element.value: &quot; &lt;&lt; container.getElement()-&gt;value &lt;&lt; endl;
</pre>
</div>
<p> and more or less equivalent usage from C#</p>
<div class="code">
<pre>
  Container container = new Container();
  Element element = new Element(20);
  container.setElement(element);
</pre>
</div>
<p> The C++ code will always print out 20, but the value printed out may
 not be this in the C# equivalent code. In order to understand why,
 consider a garbage collection occurring...</p>
<div class="code">
<pre>
  Container container = new Container();
  Element element = new Element(20);
  container.setElement(element);
  Console.WriteLine(&quot;element.value: &quot; + container.getElement().value);
  // Simulate a garbage collection
  global::System.GC.Collect();
  global::System.GC.WaitForPendingFinalizers();
  global::System.Console.WriteLine(&quot;element.value: &quot; + container.getElement().value);
</pre>
</div>
<p> The temporary element created with <tt>new Element(20)</tt> could
 get garbage collected which ultimately means the <tt>container</tt>
 variable is holding a dangling pointer, thereby printing out any old
 random value instead of the expected value of 20. One solution is to
 add in the appropriate references in the C# layer...</p>
<div class="code">
<pre>
public class Container : global::System.IDisposable {

  ...

  // Ensure that the GC doesn't collect any Element set from C#
  // as the underlying C++ class stores a shallow copy
  private Element elementReference;

  public void setElement(Element e) {
    examplePINVOKE.Container_setElement(swigCPtr, Element.getCPtr(e));
    elementReference = e;
  }
}
</pre>
</div>
<p> The following typemaps can be used to generate this code:</p>
<div class="code">
<pre>
%typemap(cscode) Container %{
  // Ensure that the GC doesn't collect any Element set from C#
  // as the underlying C++ class stores a shallow copy
  private Element elementReference;
%}

%typemap(csin,
         post=&quot;      elementReference = $csinput;&quot;
         ) Element *e &quot;Element.getCPtr($csinput)&quot;
</pre>
</div>
<p> The 'cscode' typemap simply adds in the specified code into the C#
 proxy class. The 'csin' typemap matches the input parameter type and
 name for the <tt>setElement</tt> method and the 'post' typemap
 attribute allows adding code after the PInvoke call. The 'post' code is
 generated into a finally block after the PInvoke call so the resulting
 code isn't quite as mentioned earlier, <tt>setElement</tt> is actually:</p>
<div class="code">
<pre>
  public void setElement(Element e) {
    try {
      examplePINVOKE.Container_setElement(swigCPtr, Element.getCPtr(e));
    } finally {
      elementReference = e;
    }
  }
</pre>
</div>
<h3><a name="CSharp_date_marshalling">22.8.3 Date marshalling using the
 csin typemap and associated attributes</a></h3>
<p> The <a href="#Java_nan_exception_typemap">NaN Exception example</a>
 is a simple example of the &quot;javain&quot; typemap and its 'pre' attribute.
 This example demonstrates how a C++ date class, say <tt>CDate</tt>, can
 be mapped onto the standard .NET date class, <tt>System.DateTime</tt>
 by using the 'pre', 'post' and 'pgcppname' attributes of the &quot;csin&quot;
 typemap (the C# equivalent to the &quot;javain&quot; typemap). The example is an
 equivalent to the <a href="#Java_date_marshalling">Java Date
 marshalling example</a>. The idea is that the <tt>System.DateTime</tt>
 is used wherever the C++ API uses a <tt>CDate</tt>. Let's assume the
 code being wrapped is as follows:</p>
<div class="code">
<pre>
class CDate {
public:
  CDate();
  CDate(int year, int month, int day);
  int getYear();
  int getMonth();
  int getDay();
  ...
};
struct Action {
  static int doSomething(const CDate &amp;dateIn, CDate &amp;dateOut);
  Action(const CDate &amp;date, CDate &amp;dateOut);
};
</pre>
</div>
<p> Note that <tt>dateIn</tt> is const and therefore read only and <tt>
dateOut</tt> is a non-const output type.</p>
<p> First let's look at the code that is generated by default, where the
 C# proxy class <tt>CDate</tt> is used in the proxy interface:</p>
<div class="code">
<pre>
public class Action : global::System.IDisposable {
  ...
  public Action(CDate dateIn, CDate dateOut) 
      : this(examplePINVOKE.new_Action(CDate.getCPtr(dateIn), CDate.getCPtr(dateOut)), true) {
    if (examplePINVOKE.SWIGPendingException.Pending) 
      throw examplePINVOKE.SWIGPendingException.Retrieve();
  }

  public int doSomething(CDate dateIn, CDate dateOut) {
    int ret = examplePINVOKE.Action_doSomething(swigCPtr, 
                                                CDate.getCPtr(dateIn), 
                                                CDate.getCPtr(dateOut));
    if (examplePINVOKE.SWIGPendingException.Pending) 
      throw examplePINVOKE.SWIGPendingException.Retrieve();
    return ret;
  }
}
</pre>
</div>
<p> The <tt>CDate &amp;</tt> and <tt>const CDate &amp;</tt> C# code is generated
 from the following two default typemaps:</p>
<div class="code">
<pre>
%typemap(cstype) SWIGTYPE &amp; &quot;$csclassname&quot;
%typemap(csin) SWIGTYPE &amp; &quot;$csclassname.getCPtr($csinput)&quot;
</pre>
</div>
<p> where '$csclassname' is translated into the proxy class name, <tt>
CDate</tt> and '$csinput' is translated into the name of the parameter,
 eg <tt>dateIn</tt>. From C#, the intention is then to call into a
 modified API with something like:</p>
<div class="code">
<pre>
System.DateTime dateIn = new System.DateTime(2011, 4, 13);
System.DateTime dateOut = new System.DateTime();

// Note in calls below, dateIn remains unchanged and dateOut 
// is set to a new value by the C++ call
Action action = new Action(dateIn, out dateOut);
dateIn = new System.DateTime(2012, 7, 14);
</pre>
</div>
<p> To achieve this mapping, we need to alter the default code
 generation slightly so that at the C# layer, a <tt>System.DateTime</tt>
 is converted into a <tt>CDate</tt>. The intermediary layer will still
 take a pointer to the underlying <tt>CDate</tt> class. The typemaps to
 achieve this are shown below.</p>
<div class="code">
<pre>
%typemap(cstype) const CDate &amp; &quot;System.DateTime&quot;
%typemap(csin, 
         pre=&quot;    CDate temp$csinput = new CDate($csinput.Year, $csinput.Month, $csinput.Day);&quot;
        ) const CDate &amp;
         &quot;$csclassname.getCPtr(temp$csinput)&quot;

%typemap(cstype) CDate &amp; &quot;out System.DateTime&quot;
%typemap(csin, 
         pre=&quot;    CDate temp$csinput = new CDate();&quot;, 
         post=&quot;      $csinput = new System.DateTime(temp$csinput.getYear(),&quot;
              &quot; temp$csinput.getMonth(), temp$csinput.getDay(), 0, 0, 0);&quot;,
         cshin=&quot;out $csinput&quot;
        ) CDate &amp;
         &quot;$csclassname.getCPtr(temp$csinput)&quot;

</pre>
</div>
<p> The resulting generated proxy code in the <tt>Action</tt> class
 follows:</p>
<div class="code">
<pre>
public class Action : global::System.IDisposable {
  ...
  public int doSomething(System.DateTime dateIn, out System.DateTime dateOut) {
    CDate tempdateIn = new CDate(dateIn.Year, dateIn.Month, dateIn.Day);
    CDate tempdateOut = new CDate();
    try {
      int ret = examplePINVOKE.Action_doSomething(swigCPtr, 
                                                  CDate.getCPtr(tempdateIn), 
                                                  CDate.getCPtr(tempdateOut));
      if (examplePINVOKE.SWIGPendingException.Pending) 
        throw examplePINVOKE.SWIGPendingException.Retrieve();
      return ret;
    } finally {
      dateOut = new System.DateTime(tempdateOut.getYear(), 
                                    tempdateOut.getMonth(), tempdateOut.getDay(), 0, 0, 0);
    }
  }

  static private global::System.IntPtr SwigConstructAction(System.DateTime dateIn, out System.DateTime dateOut) {
    CDate tempdateIn = new CDate(dateIn.Year, dateIn.Month, dateIn.Day);
    CDate tempdateOut = new CDate();
    try {
      return examplePINVOKE.new_Action(CDate.getCPtr(tempdateIn), CDate.getCPtr(tempdateOut));
    } finally {
      dateOut = new System.DateTime(tempdateOut.getYear(), 
                                    tempdateOut.getMonth(), tempdateOut.getDay(), 0, 0, 0);
    }
  }

  public Action(System.DateTime dateIn, out System.DateTime dateOut) 
      : this(Action.SwigConstructAction(dateIn, out dateOut), true) {
    if (examplePINVOKE.SWIGPendingException.Pending) 
      throw examplePINVOKE.SWIGPendingException.Retrieve();
  }
}
</pre>
</div>
<p> A few things to note:</p>
<ul>
<li> The &quot;cstype&quot; typemap has changed the parameter type to <tt>
System.DateTime</tt> instead of the default generated <tt>CDate</tt>
 proxy.</li>
<li> The non-const <tt>CDate &amp;</tt> type is marshalled as a reference
 parameter in C# as the date cannot be explicitly set once the object
 has been created, so a new object is created instead.</li>
<li> The code in the 'pre' attribute appears before the intermediary
 call (<tt>examplePINVOKE.new_Action</tt> / <tt>
examplePINVOKE.Action_doSomething</tt>).</li>
<li> The code in the 'post' attribute appears after the intermediary
 call.</li>
<li> A try .. finally block is generated with the intermediary call in
 the try block and 'post' code in the finally block. The alternative of
 just using a temporary variable for the return value from the
 intermediary call and the 'post' code being inserted before the return
 statement is not possible given that the intermediary call and method
 return comes from a single source (the &quot;csout&quot; typemap).</li>
<li> The temporary variables in the &quot;csin&quot; typemaps are called <tt>
temp$csin</tt>, where &quot;$csin&quot; is replaced with the parameter name.
 &quot;$csin&quot; is used to mangle the variable name so that more than one <tt>
CDate &amp;</tt> type can be used as a parameter in a method, otherwise two
 or more local variables with the same name would be generated.</li>
<li> The use of the &quot;csin&quot; typemap causes a constructor helper function
 (<tt>SwigConstructAction</tt>) to be generated. This allows C# code to
 be called before the intermediary call made in the constructor
 initialization list.</li>
<li> The 'cshin' attribute is required for the <tt>SwigConstructAction</tt>
 constructor helper function so that the 2nd parameter is declared as <tt>
out dateOut</tt> instead of just <tt>dateOut</tt>.</li>
</ul>
<p> So far we have considered the date as an input only and an output
 only type. Now let's consider <tt>CDate *</tt> used as an input/output
 type. Consider the following C++ function which modifies the date
 passed in:</p>
<div class="code">
<pre>
void addYears(CDate *pDate, int years) {
  *pDate = CDate(pDate-&gt;getYear() + years, pDate-&gt;getMonth(), pDate-&gt;getDay());
}
</pre>
</div>
<p> If usage of <tt>CDate *</tt> commonly follows this input/output
 pattern, usage from C# like the following</p>
<div class="code">
<pre>
System.DateTime christmasEve = new System.DateTime(2000, 12, 24);
example.addYears(ref christmasEve, 10); // christmasEve now contains 2010-12-24
</pre>
</div>
<p> will be possible with the following <tt>CDate *</tt> typemaps</p>
<div class="code">
<pre>
%typemap(cstype, out=&quot;System.DateTime&quot;) CDate * &quot;ref System.DateTime&quot;

%typemap(csin,
         pre=&quot;    CDate temp$csinput = new CDate($csinput.Year, $csinput.Month, $csinput.Day);&quot;,
         post=&quot;      $csinput = new System.DateTime(temp$csinput.getYear(),&quot;
              &quot; temp$csinput.getMonth(), temp$csinput.getDay(), 0, 0, 0);&quot;,
         cshin=&quot;ref $csinput&quot;
        ) CDate *
         &quot;$csclassname.getCPtr(temp$csinput)&quot;
</pre>
</div>
<p> Globals are wrapped by the module class and for a module called
 example, the typemaps result in the following code:</p>
<div class="code">
<pre>
public class example {
  public static void addYears(ref System.DateTime pDate, int years) {
    CDate temppDate = new CDate(pDate.Year, pDate.Month, pDate.Day);
    try {
      examplePINVOKE.addYears(CDate.getCPtr(temppDate), years);
    } finally {
      pDate = new System.DateTime(temppDate.getYear(), temppDate.getMonth(), temppDate.getDay(),
                                  0, 0, 0);
    }
  }
  ...
}
</pre>
</div>
<p> The following typemap is the same as the previous but demonstrates
 how a using block can be used for the temporary variable. The only
 change to the previous typemap is the introduction of the 'terminator'
 attribute to terminate the <tt>using</tt> block. The <tt>subtractYears</tt>
 method is nearly identical to the above <tt>addYears</tt> method.</p>
<div class="code">
<pre>
%typemap(csin,
  pre=&quot;    using (CDate temp$csinput = new CDate($csinput.Year, $csinput.Month, $csinput.Day)) {&quot;,
  post=&quot;      $csinput = new System.DateTime(temp$csinput.getYear(),&quot;
       &quot; temp$csinput.getMonth(), temp$csinput.getDay(), 0, 0, 0);&quot;,
  terminator=&quot;    } // terminate temp$csinput using block&quot;,
  cshin=&quot;ref $csinput&quot;
 ) CDate *
  &quot;$csclassname.getCPtr(temp$csinput)&quot;

void subtractYears(CDate *pDate, int years) {
  *pDate = CDate(pDate-&gt;getYear() - years, pDate-&gt;getMonth(), pDate-&gt;getDay());
}
</pre>
</div>
<p> The resulting generated code shows the termination of the <tt>using</tt>
 block:</p>
<div class="code">
<pre>
public class example {
  public static void subtractYears(ref System.DateTime pDate, int years) {
    using (CDate temppDate = new CDate(pDate.Year, pDate.Month, pDate.Day)) {
    try {
      examplePINVOKE.subtractYears(CDate.getCPtr(temppDate), years);
    } finally {
      pDate = new System.DateTime(temppDate.getYear(), temppDate.getMonth(), temppDate.getDay(),
                                  0, 0, 0);
    }
    } // terminate temppDate using block
  }
  ...
}
</pre>
</div>
<h3><a name="CSharp_date_properties">22.8.4 A date example demonstrating
 marshalling of C# properties</a></h3>
<p> The previous section looked at converting a C++ date class to <tt>
System.DateTime</tt> for parameters. This section extends this idea so
 that the correct marshalling is obtained when wrapping C++ variables.
 Consider the same <tt>CDate</tt> class from the previous section and a
 global variable:</p>
<div class="code">
<pre>
CDate ImportantDate = CDate(1999, 12, 31);
</pre>
</div>
<p> The aim is to use <tt>System.DateTime</tt> from C# when accessing
 this date as shown in the following usage where the module name is
 'example':</p>
<div class="code">
<pre>
example.ImportantDate = new System.DateTime(2000, 11, 22);
System.DateTime importantDate = example.ImportantDate;
Console.WriteLine(&quot;Important date: &quot; + importantDate);
</pre>
</div>
<p> When SWIG wraps a variable that is a class/struct/union, it is
 wrapped using a pointer to the type for the reasons given in <a href="#SWIG_structure_data_members">
Structure data members</a>. The typemap type required is thus <tt>CDate
 *</tt>. Given that the previous section already designed <tt>CDate *</tt>
 typemaps, we'll use those same typemaps plus the 'csvarin' and
 'csvarout' typemaps.<div class="code">
<pre>
%typemap(cstype, out=&quot;System.DateTime&quot;) CDate * &quot;ref System.DateTime&quot;

%typemap(csin,
         pre=&quot;    CDate temp$csinput = new CDate($csinput.Year, $csinput.Month, $csinput.Day);&quot;,
         post=&quot;      $csinput = new System.DateTime(temp$csinput.getYear(),&quot;
              &quot; temp$csinput.getMonth(), temp$csinput.getDay(), 0, 0, 0);&quot;,
         cshin=&quot;ref $csinput&quot;
        ) CDate *
         &quot;$csclassname.getCPtr(temp$csinput)&quot;

%typemap(csvarin, excode=SWIGEXCODE2) CDate * %{
    /* csvarin typemap code */
    set {
      CDate temp$csinput = new CDate($csinput.Year, $csinput.Month, $csinput.Day);
      $imcall;$excode
    } %}

%typemap(csvarout, excode=SWIGEXCODE2) CDate * %{
    /* csvarout typemap code */
    get {
      global::System.IntPtr cPtr = $imcall;
      CDate tempDate = (cPtr == global::System.IntPtr.Zero) ? null : new CDate(cPtr, $owner);$excode
      return new System.DateTime(tempDate.getYear(), tempDate.getMonth(), tempDate.getDay(),
                                 0, 0, 0);
    } %}
</pre>
</div></p>
<p> For a module called example, the typemaps result in the following
 code:</p>
<div class="code">
<pre>
public class example {
  public static System.DateTime ImportantDate {
    /* csvarin typemap code */
    set {
      CDate tempvalue = new CDate(value.Year, value.Month, value.Day);
      examplePINVOKE.ImportantDate_set(CDate.getCPtr(tempvalue));
    } 
    /* csvarout typemap code */
    get {
      global::System.IntPtr cPtr = examplePINVOKE.ImportantDate_get();
      CDate tempDate = (cPtr == global::System.IntPtr.Zero) ? null : new CDate(cPtr, false);
      return new System.DateTime(tempDate.getYear(), tempDate.getMonth(), tempDate.getDay(),
                                 0, 0, 0);
    } 
  }
  ...
}
</pre>
</div>
<p> Some points to note:</p>
<ul>
<li>The property set comes from the 'csvarin' typemap and the property
 get comes from the 'csvarout' typemap.</li>
<li>The type used for the property comes from the 'cstype' typemap. This
 particular example has the 'out' attribute set in the typemap and as it
 is specified, it is used in preference to the type in the typemap body.
 This is because the type in the 'out' attribute can never include
 modifiers such as 'ref', thereby avoiding code such as <tt>public
 static ref System.DateTime ImportantDate { ...</tt>, which would of
 course not compile.</li>
<li>The <tt>$excode</tt> special variable expands to nothing as there
 are no exception handlers specified in any of the unmanaged code
 typemaps (in fact the marshalling was done using the default unmanaged
 code typemaps.)</li>
<li>The <tt>$imcall</tt> typemap expands to the appropriate intermediary
 method call in the <tt>examplePINVOKE</tt> class.</li>
<li>The <tt>$csinput</tt> special variable in the 'csin' typemap always
 expands to <tt>value</tt> for properties. In this case <tt>
$csclassname.getCPtr(temp$csinput)</tt> expands to <tt>
CDate.getCPtr(tempvalue)</tt>.</li>
<li>The 'csin' typemap has 'pre', 'post' and 'cshin' attributes, and
 these are all ignored in the property set. The code in these attributes
 must instead be replicated within the 'csvarin' typemap. The line
 creating the <tt>temp$csinput</tt> variable is such an example; it is
 identical to what is in the 'pre' attribute.</li>
</ul>
<h3><a name="CSharp_date_pre_post_directors">22.8.5 Date example
 demonstrating the 'pre' and 'post' typemap attributes for directors</a></h3>
<p> The 'pre' and 'post' attributes in the &quot;csdirectorin&quot; typemap act
 like the attributes of the same name in the &quot;csin&quot; typemap. For example
 if we modify the <a href="#CSharp_date_marshalling">Date marshalling
 example</a> like this:</p>
<div class="code">
<pre>
class CDate {
  ...
  void setYear(int);
  void setMonth(int);
  void setDay(int);
};
struct Action {
  virtual void someCallback(CDate &amp;date);
  virtual ~Action();
  ...
};
</pre>
</div>
<p> and declare <tt>%feature (&quot;director&quot;)</tt> for the <tt>Action</tt>
 class, we would have to define additional marshalling rules for <tt>
CDate &amp;</tt> parameter. The typemap may look like this:</p>
<div class="code">
<pre>
%typemap(csdirectorin,
         pre=&quot;System.DateTime temp$iminput = new System.DateTime();&quot;,
         post=&quot;CDate temp2$iminput = new CDate($iminput, false);\n&quot;
              &quot;temp2$iminput.setYear(tempdate.Year);\n&quot;
              &quot;temp2$iminput.setMonth(tempdate.Month);\n&quot;
              &quot;temp2$iminput.setDay(tempdate.Day);&quot;
         ) CDate &amp;date &quot;out temp$iminput&quot;
</pre>
</div>
<p> The generated proxy class code will then contain the following
 wrapper for calling user-overloaded <tt>someCallback()</tt>:</p>
<div class="code">
<pre>
...
  private void SwigDirectorMethodsomeCallback(global::System.IntPtr date) {
    System.DateTime tempdate = new System.DateTime();
    try {
      someCallback(out tempdate);
    } finally {
      // we create a managed wrapper around the existing C reference, just for convenience
      CDate temp2date = new CDate(date, false);
      temp2date.setYear(tempdate.Year);
      temp2date.setMonth(tempdate.Month);
      temp2date.setDay(tempdate.Day);
    }
  }
...
</pre>
</div>
<p> Pay special attention to the memory management issues, using these
 attributes.</p>
<h3><a name="CSharp_partial_classes">22.8.6 Turning proxy classes into
 partial classes</a></h3>
<p> C# supports the notion of partial classes whereby a class definition
 can be split into more than one file. It is possible to turn the
 wrapped C++ class into a partial C# class using the <tt>
csclassmodifiers</tt> typemap. Consider a C++ class called <tt>ExtendMe</tt>
:</p>
<div class="code">
<pre>
class ExtendMe {
public:
  int Part1() { return 1; }
};
</pre>
</div>
<p> The default C# proxy class generated is:</p>
<div class="code">
<pre>
public class ExtendMe : global::System.IDisposable {
  ...
  public int Part1() {
    ...
  }
}
</pre>
</div>
<p> The default csclassmodifiers typemap shipped with SWIG is</p>
<div class="code">
<pre>
%typemap(csclassmodifiers) SWIGTYPE &quot;public class&quot;
</pre>
</div>
<p> Note that the type used is the special catch all type <tt>SWIGTYPE</tt>
. If instead we use the following typemap to override this for just the <tt>
ExtendMe</tt> class:</p>
<div class="code">
<pre>
%typemap(csclassmodifiers) ExtendMe &quot;public partial class&quot;
</pre>
</div>
<p> The C# proxy class becomes a partial class:</p>
<div class="code">
<pre>
public partial class ExtendMe : global::System.IDisposable {
  ...
  public int Part1() {
    ...
  }
}
</pre>
</div>
<p> You can then of course declare another part of the partial class
 elsewhere, for example:</p>
<div class="code">
<pre>
public partial class ExtendMe : global::System.IDisposable {
  public int Part2() {
    return 2;
  }
}
</pre>
</div>
<p> and compile the following code:</p>
<div class="code">
<pre>
ExtendMe em = new ExtendMe();
Console.WriteLine(&quot;part1: {0}&quot;, em.Part1());
Console.WriteLine(&quot;part2: {0}&quot;, em.Part2());
</pre>
</div>
<p> demonstrating that the class contains methods calling both unmanaged
 code - <tt>Part1()</tt> and managed code - <tt>Part2()</tt>. The
 following example is an alternative approach to adding managed code to
 the generated proxy class.</p>
<h3><a name="CSharp_sealed_proxy_class">22.8.7 Turning proxy classes
 into sealed classes</a></h3>
<p> The technique in the previous section can be used to make the proxy
 class a sealed class. Consider a C++ class <tt>NotABaseClass</tt> that
 you don't want to be derived from in C#:</p>
<div class="code">
<pre>
struct NotABaseClass {
  NotABaseClass();
  ~NotABaseClass();
};
</pre>
</div>
<p> The default C# proxy class method generated with Dispose method is:</p>
<div class="code">
<pre>
public class NotABaseClass : global::System.IDisposable {
  ...
  public virtual void Dispose() {
    ...
  }
}
</pre>
</div>
<p> The <tt>csclassmodifiers</tt> typemap can be used to modify the
 class modifiers and the <tt>csmethodmodifiers</tt> feature can be used
 on the destructor to modify the proxy's <tt>Dispose</tt> method:</p>
<div class="code">
<pre>
%typemap(csclassmodifiers) NotABaseClass &quot;public sealed class&quot;
%csmethodmodifiers NotABaseClass::~NotABaseClass &quot;public /*virtual*/&quot;;
</pre>
</div>
<p> The relevant generated code is thus:</p>
<div class="code">
<pre>
public sealed class NotABaseClass : global::System.IDisposable {
  ...
  public /*virtual*/ void Dispose() {
    ...
  }
}
</pre>
</div>
<p> Any attempt to derive from the <tt>NotABaseClass</tt> in C# will
 result in a C# compiler error, for example:</p>
<div class="code">
<pre>
public class Derived : NotABaseClass {
};
</pre>
</div><div class="shell">
<pre>
runme.cs(6,14): error CS0509: `Derived': cannot derive from sealed type `NotABaseClass'
</pre>
</div>
<p> Finally, if you get a warning about use of 'protected' in the
 generated base class:</p>
<div class="shell">
<pre>
NotABaseClass.cs(14,18): warning CS0628: `NotABaseClass.swigCMemOwn': new protected member declared in sealed class
</pre>
</div>
<p> Either suppress the warning or modify the generated code by copying
 and tweaking the default 'csbody' typemap code in csharp.swg by
 modifying swigCMemOwn to not be protected.</p>
<h3><a name="CSharp_extending_proxy_class">22.8.8 Extending proxy
 classes with additional C# code</a></h3>
<p> The previous example showed how to use partial classes to add
 functionality to a generated C# proxy class. It is also possible to
 extend a wrapped struct/class with C/C++ code by using the <a href="#SWIGPlus_class_extension">
%extend directive</a>. A third approach is to add some C# methods into
 the generated proxy class with the <tt>cscode</tt> typemap. If we
 declare the following typemap before SWIG parses the <tt>ExtendMe</tt>
 class used in the previous example</p>
<div class="code">
<pre>
%typemap(cscode) ExtendMe %{
  public int Part3() {
    return 3;
  }
%}

</pre>
</div>
<p> The generated C# proxy class will instead be:</p>
<div class="code">
<pre>
public class ExtendMe : global::System.IDisposable {
  ...
  public int Part3() {
    return 3;
  }
  public int Part1() {
    ...
  }
}
</pre>
</div>
<h3><a name="CSharp_enum_underlying_type">22.8.9 Underlying type for
 enums</a></h3>
<p> C# enums use int as the underlying type for each enum item. If you
 wish to change the underlying type to something else, then use the <tt>
csbase</tt> typemap. For example when your C++ code uses a value larger
 than int, this is necessary as the C# compiler will not compile values
 which are too large to fit into an int. Here is an example:</p>
<div class="code">
<pre>
%typemap(csbase) BigNumbers &quot;uint&quot;
%inline %{
  enum BigNumbers { big=0x80000000, bigger };
%}
</pre>
</div>
<p> The generated enum will then use the given underlying type and
 compile correctly:</p>
<div class="code">
<pre>
public enum BigNumbers : uint {
  big = 0x80000000,
  bigger
}
</pre>
</div><HR NOSHADE>
<h1><a name="D">23 SWIG and D</a></h1>

<!-- INDEX -->
<div class="sectiontoc">
<ul>
<li><a href="#D_introduction">Introduction</a></li>
<li><a href="#D_command_line_invocation">Command line invocation</a></li>
<li><a href="#D_typemaps">Typemaps</a>
<ul>
<li><a href="#D_typemap_name_comparison">C# &lt;-&gt; D name comparison</a></li>
<li><a href="#D_ctype_imtype_dtype">ctype, imtype, dtype</a></li>
<li><a href="#D_in_out_directorin_direcetorout">in, out, directorin,
 directorout</a></li>
<li><a href="#D_din_dout_ddirectorin_ddirectorout">din, dout,
 ddirectorin, ddirectorout</a></li>
<li><a href="#D_typecheck_typemaps">typecheck typemaps</a></li>
<li><a href="#D_code_injection_typemaps">Code injection typemaps</a></li>
<li><a href="#D_special_variables">Special variable macros</a></li>
</ul>
</li>
<li><a href="#D_features">D and %feature</a></li>
<li><a href="#D_pragmas">Pragmas</a></li>
<li><a href="#D_exceptions">D Exceptions</a></li>
<li><a href="#D_directors">D Directors</a></li>
<li><a href="#D_other_features">Other features</a>
<ul>
<li><a href="#D_nspace">Extended namespace support (nspace)</a></li>
<li><a href="#D_native_pointer_support">Native pointer support</a></li>
<li><a href="#D_operator_overloading">Operator overloading</a></li>
<li><a href="#D_test_suite">Running the test-suite</a></li>
</ul>
</li>
<li><a href="#D_typemap_examples">D Typemap examples</a></li>
<li><a href="#D_planned_features">Work in progress and planned features</a>
</li>
</ul>
</div>
<!-- INDEX -->
<h2><a name="D_introduction">23.1 Introduction</a></h2>
<p>From the <a href="http://www.digitalmars.com/d/">D Programming
 Language</a> web site:<em> D is a systems programming language. Its
 focus is on combining the power and high performance of C and C++ with
 the programmer productivity of modern languages like Ruby and Python.
 [...] The D language is statically typed and compiles directly to
 machine code.</em> As such, it is not very surprising that D is able to
 directly <a href="http://www.digitalmars.com/d/1.0/interfaceToC.html">
interface with C libraries</a>. Why would a SWIG module for D be needed
 then in the first place?</p>
<p>Well, besides the obvious downside that the C header files have to be
 manually converted to D modules for this to work, there is one major
 inconvenience with this approach: D code usually is on a higher
 abstraction level than C, and many of the features that make D
 interesting are simply not available when dealing with C libraries,
 requiring you e.g. to manually convert strings between pointers to <tt>
\0</tt>-terminated char arrays and D char arrays, making the algorithms
 from the D2 standard library unusable with C arrays and data
 structures, and so on.</p>
<p>While these issues can be worked around relatively easy by
 hand-coding a thin wrapper layer around the C library in question,
 there is another issue where writing wrapper code per hand is not
 feasible: C++ libraries. D did not support interfacing to C++ in
 version 1 at all, and even if <tt>extern(C++)</tt> has been added to
 D2, the support is still very limited, and a custom wrapper layer is
 still required in many cases.</p>
<p>To help addressing these issues, the SWIG C# module has been forked
 to support D. Is has evolved quite a lot since then, but there are
 still many similarities, so if you do not find what you are looking for
 on this page, it might be worth having a look at the chapter on <a href="#CSharp">
C#</a> (and also on <a href="#Java">Java</a>, since the C# module was in
 turn forked from it).</p>
<h2><a name="D_command_line_invocation">23.2 Command line invocation</a></h2>
<p>To activate the D module, pass the <tt>-d</tt> option to SWIG at the
 command line. The same standard command line options as with any other
 language module are available, plus the following D specific ones:</p>
<dl>
<dt><tt>-d2</tt></dt>
<dd>
<p>By default, SWIG generates code for D1/Tango. Use the <tt>-d2</tt>
 flag to target D2/Phobos instead.</p>
</dd>
<dt><a name="D_splitproxy"></a><tt>-splitproxy</tt></dt>
<dd>
<p>By default, SWIG generates two D modules: the<em> proxy</em> module,
 named like the source module (either specified via the <tt>%module</tt>
 directive or via the <tt>module</tt> command line option), which
 contains all the proxy classes, functions, enums, etc., and the<em>
 intermediary</em> module (named like the proxy module, but suffixed
 with <tt>_im</tt>), which contains all the <tt>extern(C)</tt> function
 declarations and other private parts only used internally by the proxy
 module.</p>
<p>If the split proxy mode is enabled by passing this option at the
 command line, all proxy classes and enums are emitted to their own D
 module instead. The main proxy module only contains free functions and
 constants in this case.</p>
</dd>
<dt><tt>-package &lt;pkg&gt;</tt></dt>
<dd>
<p>By default, the proxy D modules and the intermediary D module are
 written to the root package. Using this option, you can specify another
 target package instead.</p>
</dd>
<dt><tt>-wrapperlibrary &lt;wl&gt;</tt></dt>
<dd>
<p>The code SWIG generates to dynamically load the C/C++ wrapper layer
 looks for a library called <tt>$module_wrap</tt> by default. With this
 option, you can override the name of the file the wrapper code loads at
 runtime (the <tt>lib</tt> prefix and the suffix for shared libraries
 are appended automatically, depending on the OS).</p>
<p>This might especially be useful if you want to invoke SWIG several
 times on separate modules, but compile the resulting code into a single
 shared library.</p>
</dd>
</dl>
<h2><a name="D_typemaps">23.3 Typemaps</a></h2>
<h3><a name="D_typemap_name_comparison">23.3.1 C# &lt;-&gt; D name comparison</a>
</h3>
<p>If you already know the SWIG C# module, you might find the following
 name comparison table useful:</p>
<div class="diagram">
<pre>
 ctype                  &lt;-&gt;  ctype
 imtype                 &lt;-&gt;  imtype
 cstype                 &lt;-&gt;  dtype
 csin                   &lt;-&gt;  din
 csout                  &lt;-&gt;  dout
 csdirectorin           &lt;-&gt;  ddirectorin
 csdirectorout          &lt;-&gt;  ddirectorout
 csinterfaces           &lt;-&gt;  dinterfaces
 csinterfaces_derived   &lt;-&gt;  dinterfaces_derived
 csbase                 &lt;-&gt;  dbase
 csclassmodifiers       &lt;-&gt;  dclassmodifiers
 cscode                 &lt;-&gt;  dcode
 csimports              &lt;-&gt;  dimports
 csbody                 &lt;-&gt;  dbody
 csfinalize             &lt;-&gt;  ddestructor
 csdisposing            &lt;-&gt;  ddispose
 csdisposing_derived    &lt;-&gt;  ddispose_derived
</pre>
</div>
<h3><a name="D_ctype_imtype_dtype">23.3.2 ctype, imtype, dtype</a></h3>
<p>Mapping of types between the C/C++ library, the C/C++ library wrapper
 exposing the C functions, the D wrapper module importing these
 functions and the D proxy code.</p>
<p>The <tt>ctype</tt> typemap is used to determine the types to use in
 the C wrapper functions. The types from the <tt>imtype</tt> typemap are
 used in the extern(C) declarations of these functions in the
 intermediary D module. The <tt>dtype</tt> typemap contains the D types
 used in the D proxy module/class.</p>
<h3><a name="D_in_out_directorin_direcetorout">23.3.3 in, out,
 directorin, directorout</a></h3>
<p>Used for converting between the types for C/C++ and D when generating
 the code for the wrapper functions (on the C++ side).</p>
<p>The code from the <tt>in</tt> typemap is used to convert arguments to
 the C wrapper function to the type used in the wrapped code (<tt>ctype</tt>
-&gt;original C++ type), the <tt>out</tt> typemap is utilized to convert
 values from the wrapped code to wrapper function return types (original
 C++ type-&gt;<tt>ctype</tt>).</p>
<p>The <tt>directorin</tt> typemap is used to convert parameters to the
 type used in the D director callback function, its return value is
 processed by <tt>directorout</tt> (see below).</p>
<h3><a name="D_din_dout_ddirectorin_ddirectorout">23.3.4 din, dout,
 ddirectorin, ddirectorout</a></h3>
<p>Typemaps for code generation in D proxy and type wrapper classes.</p>
<p><a name="D_din"></a>The <tt>din</tt> typemap is used for converting
 function parameter types from the type used in the proxy module or
 class to the type used in the intermediary D module (the <a href="#D_dinput">
$dinput</a> macro is replaced). To inject further parameter processing
 code before or after the call to the intermediary layer, the <tt>pre</tt>
, <tt>post</tt> and <tt>terminator</tt> attributes can be used (please
 refer to the <a href="#CSharp_date_marshalling">C# date marshalling
 example</a> for more information on these).</p>
<p><a name="D_dout"></a>The <tt>dout</tt> typemap is used for converting
 function return values from the return type used in the intermediary D
 module to the type returned by the proxy function. The <tt>$excode</tt>
 special variable in <tt>dout</tt> typemaps is replaced by the <tt>
excode</tt> typemap attribute code if the method can throw any
 exceptions from unmanaged code, otherwise by nothing (the <a href="#D_imcall">
<tt>$imcall</tt> and <tt>$owner</tt></a> macros are replaced).</p>
<p><a name="D_ddirectorinout"></a>The code from the <tt>ddirectorin</tt>
 and <tt>ddirectorout</tt> typemaps is used for conversion in director
 callback functions. Arguments are converted to the type used in the
 proxy class method they are calling by using the code from <tt>
ddirectorin</tt>, the proxy class method return value is converted to
 the type the C++ code expects via the <tt>ddirectorout</tt> typemap
 (the <a href="#D_dpcall"><tt>$dcall</tt> and <tt>$winput</tt></a>
 macros are replaced).</p>
<p>The full chain of type conversions when a director callback is
 invoked looks like this:</p>
<div class="diagram">
<pre>
      type              CPPClass::method(type a)
        &uarr;                       &darr;
   &lt;directorout&gt;          &lt;directorin&gt;
        &uarr;                       &darr;
      ctype             methodCallback(ctype a)           C++
 :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
      imtype            methodCallback(imtype a)           D
        &uarr;                       &darr;
  &lt;ddirectorout&gt;          &lt;ddirectorin&gt;
        &uarr;                       &darr;
      dtype             DClass.method(dtype a)</pre>
</div>
<h3><a name="D_typecheck_typemaps">23.3.5 typecheck typemaps</a></h3>
<p>Because, unlike many scripting languages supported by SWIG, D does
 not need any dynamic dispatch helper to access an overloaded function,
 the purpose of these is merely to issue a warning for overloaded C++
 functions that cannot be overloaded in D (as more than one C++ type
 maps to a single D type).</p>
<h3><a name="D_code_injection_typemaps">23.3.6 Code injection typemaps</a>
</h3>
<p>These typemaps are used for generating the skeleton of proxy classes
 for C++ types.</p>
<p>By overriding <tt>dbase</tt>, <tt>dinterfaces</tt> or <tt>
dinterfaces_derived</tt>, the inheritance chain of the generated proxy
 class for a type can be modified. <tt>dclassmodifiers</tt> allows you
 to add any custom modifiers around the class keyword.</p>
<p>Using <tt>dcode</tt> and <tt>dimports</tt>, you can specify
 additional D code which will be emitted into the class body
 respectively the imports section of the D module the class is written
 to.</p>
<p><a name="D_class_code_typemaps"></a><tt>dconstructor</tt>, <tt>
ddestructor</tt>, <tt>ddispose</tt> and <tt>ddispose_derived</tt> are
 used to generate the class constructor, destructor and <tt>dispose()</tt>
 method, respectively. The auxiliary code for handling the pointer to
 the C++ object is stored in <tt>dbody</tt> and <tt>dbody_derived</tt>.
 You can override them for specific types.</p>
<p> Code can also be injected into the D proxy class using <tt>
%proxycode</tt>.</p>
<h3><a name="D_special_variables">23.3.7 Special variable macros</a></h3>
<p>The standard SWIG special variables are available for use within
 typemaps as described in the <a href="#Typemaps">Typemaps documentation</a>
, for example <tt>$1</tt>, <tt>$input</tt>, <tt>$result</tt> etc.</p>
<p>When generating D wrappers, a few additional macros are available:</p>
<dl>
<dt><tt>$dclassname</tt> (C#: <tt>$csclassname</tt>)</dt>
<dd>
<p>This special variable works similar to <a href="#Typemaps_special_variables">
<tt>$n_type</tt></a> in that it returns the name of a type - it expands
 to the D proxy class name of the type being wrapped. If the type does
 not have an associated proxy class, it expands to the type wrapper
 class name, for example, <tt>SWIGTYPE_p_p_SomeCppClass</tt> is
 generated when wrapping <tt>SomeCppClass **</tt>.</p>
<p>There are two other variants available, <tt>$&amp;dclassname</tt> and <tt>
$*dclassname</tt>. The former adds a level of indirection, while the
 latter removes one. For instance, when wrapping <tt>Foo **</tt>, <tt>
$*dclassname</tt> would be replaced by the proxy class name
 corresponding to <tt>Foo *</tt>.</p>
</dd>
<dt><tt>$dclazzname</tt> (C#: <tt>$csclazzname</tt>)</dt>
<dd>
<p>This special variable expands the fully qualified C++ class into the
 package name, if used by the <a href="#SWIGPlus_nspace"><tt>nspace</tt>
 feature</a>, and the proxy class name, mangled for use as a function
 name. For example, <tt>Namespace1::Namespace2::Klass</tt> is expanded
 into <tt>Namespace1_Namespace2_Klass_</tt>.</p>
<p>This special variable might be useful for calling certain functions
 in the wrapper layer (e.g. upcast wrappers) which are mangled like
 this.</p>
</dd>
<dt><tt>$null</tt></dt>
<dd>
<p>In code inserted into the generated C/C++ wrapper functions, this
 variable is replaced by either <tt>0</tt> or nothing at all, depending
 on whether the function has a return value or not. It can be used to
 bail out early e.g. in case of errors (<tt>return $null;</tt>).</p>
</dd>
<dt><a name="D_dinput"></a><tt>$dinput</tt> (C#: <tt>$csinput</tt>)</dt>
<dd>
<p>This variable is used in <tt><a href="#D_din">din</a></tt> typemaps
 and is replaced by the expression which is to be passed to C/C++.</p>
<p>For example, this input</p>
<div class="code">
<pre>
%typemap(din) SomeClass * &quot;SomeClass.getCPointer($dinput)&quot;

%inline %{
  class SomeClass {};
  void foo(SomeClass *arg);
%}</pre>
</div>
<p>leads to the following D proxy code being generated:</p>
<div class="targetlang">
<pre>
void foo(SomeClass arg) {
  example_im.foo(SomeClass.getCPointer(arg));
}</pre>
</div></dd>
<dt><a name="D_imcall"></a><tt>$imcall</tt> and <tt>$owner</tt> (C#: <tt>
$imcall</tt>)</dt>
<dd>
<p>These variables are used in <tt><a href="#D_dout">dout</a></tt>
 typemaps. <tt>$imcall</tt> contains the call to the intermediary module
 which provides the value to be used, and <tt>$owner</tt> signals if the
 caller is responsible for managing the object lifetime (that is, if the
 called method is a constructor or has been marked via <tt>%newobject</tt>
).</p>
<p>Consider the following example:</p>
<div class="code">
<pre>
%typemap(dout) SomeClass * {
  return new SomeClass($imcall, $owner);
}

%inline %{
  class SomeClass;
  SomeClass *foo();

  %newobject bar();
  SomeClass *bar();
%}
</pre>
</div>
<p>The code generated for <tt>foo()</tt> and <tt>bar()</tt> looks like
 this:</p>
<div class="targetlang">
<pre>
SomeClass foo() {
  return new SomeClass(example_im.foo(), false);
}

SomeClass bar() {
  return new SomeClass(example_im.bar(), true);
}
</pre>
</div></dd>
<dt><tt>$dcall</tt> and <tt>$winput</tt> (C#: <tt>$cscall</tt>, <tt>
$iminput</tt>)</dt>
<dd><a name="D_dpcall"></a>
<p>These variables are used in the director-specific typemaps <a href="#D_ddirectorinout">
<tt>ddirectorin</tt></a> and <a href="#D_ddirectorinout"><tt>
ddirectorout</tt></a>. They are more or less the reverse of the <tt>
$imcall</tt> and <tt>$dinput</tt> macros: <tt>$dcall</tt> contains the
 invocation of the D proxy method of which the return value is to be
 passed back to C++, <tt>$winput</tt> contains the parameter value from
 C++.</p>
</dd>
<dt><tt>$excode</tt></dt>
<dd>
<p>This variable is used in <tt>dout</tt> and <tt>dconstructor</tt>
 typemaps and is filled with the contents of the <tt>excode</tt> typemap
 attribute if an exception could be thrown from the C++ side. See the <a href="#CSharp_exceptions">
C# documentation</a> for details.</p>
</dd>
<dt><tt>$dbaseclass</tt></dt>
<dd>
<p>Currently for internal use only, it contains the D name of the C++
 base class (if any) inside proxy classes.</p>
</dd>
<dt><tt>$directorconnect</tt></dt>
<dd>
<p>This macro is only valid inside the <tt><a href="#D_class_code_typemaps">
dconstructor</a></tt> typemap and contains the value of the <tt>
dconstructor</tt> typemap attribute if the currently wrapped class has
 directors enabled.</p>
<p>This is how the default <tt>dconstructor</tt> typemap looks like (you
 usually do not want to specify a custom one):</p>
<div class="code">
<pre>
%typemap(dconstructor, excode=SWIGEXCODE,
         directorconnect=&quot;\n  swigDirectorConnect();&quot;) SWIGTYPE {
  this($imcall, true);$excode$directorconnect
}
</pre>
</div></dd>
<dt><a name="D_importtype"></a><tt>$importtype(SomeDType)</tt></dt>
<dd>
<p>This macro is used in the <tt>dimports</tt> typemap if a dependency
 on another D type generated by SWIG is added by a custom typemap.</p>
<p>Consider the following code snippet:</p>
<div class="code">
<pre>
%typemap(dinterfaces) SomeClass &quot;AnInterface, AnotherInterface&quot;;
</pre>
</div>
<p>This causes SWIG to add <tt>AnInterface</tt> and <tt>AnotherInterface</tt>
 to the base class list of <tt>SomeClass</tt>:</p>
<div class="targetlang">
<pre>
class SomeClass : AnInterface, AnotherInterface {
  ...
}
</pre>
</div>
<p>For this to work, <tt>AnInterface</tt> and <tt>AnotherInterface</tt>
 have to be in scope. If SWIG is not in split proxy mode, this is
 already the case, but if it is, they have to be added to the import
 list via the <tt>dimports</tt> typemap. Additionally, the import
 statement depends on the package SWIG is configured to emit the modules
 to.</p>
<p>The <tt>$importtype</tt> macro helps you to elegantly solve this
 problem:</p>
<div class="code">
<pre>
%typemap(dimports) RemoteMpe %{
$importtype(AnInterface)
$importtype(AnotherInterface)
%}
</pre>
</div>
<p>If SWIG is in split proxy mode, it expands to an <tt>import</tt>
 statement for the specified type, to nothing if not.</p>
</dd>
<dt><tt>$module</tt></dt>
<dd>
<p>Expands to the name of the main proxy D module.</p>
</dd>
<dt><tt>$imdmodule</tt></dt>
<dd>
<p>Contains the fully qualified name of the intermediary D module.</p>
</dd>
</dl>
<h2><a name="D_features">23.4 D and %feature</a></h2>
<p>The D module defines a number of directives which modify the <a href="#Customization_features">
SWIG features</a> set globally or for a specific declaration:</p>
<dl>
<dt><tt>%dmanifestconst</tt> and <tt>%dconstvalue(value)</tt></dt>
<dd>
<p>Out of the box, SWIG generates accessor methods for C <tt>#defines</tt>
 and C++ constants. The <tt>%dmanifestconst</tt> directive enables
 wrapping these constants as D manifest constants (<tt>const</tt> in D1,
 <tt>enum</tt> in D2).</p>
<p>For this to work, the C/C++ code for the constant value must directly
 compile as D code, though. If this is not the case, you can manually
 override the expression written to the D proxy module using the <tt>
%dconstvalue</tt> directive, passing the new value as parameter.</p>
<p>For <tt>enum</tt>s, again <tt>%dconstvalue</tt> can be used to
 override the value of an enum item if the initializer should not
 compile in D.</p>
</dd>
<dt><tt>%dmethodmodifiers</tt></dt>
<dd>
<p>This directive can be used to override the modifiers for a proxy
 function. For instance, you could make a <tt>public</tt> C++ member
 function <tt>private</tt> in D like this:</p>
<div class="code">
<pre>
%dmethodmodifiers A::foo &quot;private&quot;;

%inline %{
struct A {
  void foo();
};
%}
</pre>
</div></dd>
</dl>
<h2><a name="D_pragmas">23.5 Pragmas</a></h2>
<p>There are a few SWIG pragmas specific to the D module, which you can
 use to influence the D code SWIG generates:</p>
<dl>
<dt><tt>%pragma(d) imdmodulecode</tt></dt>
<dd>
<p>The passed text (D code) is copied verbatim to the intermediary D
 module. For example, it can be (and is, internally) used to emit
 additional private helper code for the use by proxy typemaps.</p>
</dd>
<dt><tt>%pragma(d) imdmoduleimports</tt></dt>
<dd>
<p>Additional code to be emitted to the imports section of the
 intermediary D module (the <a href="#D_importtype">$importtype</a>
 macro can be used here). You probably want to use this in conjunction
 with the <tt>imdmodulecode</tt> pragma.</p>
</dd>
<dt><tt>%pragma(d) proxydmodulecode</tt></dt>
<dd>
<p>Just like <tt>proxydmodulecode</tt>, the argument is copied to the
 proxy D module (if SWIG is in <a href="#D_splitproxy">split proxy mode</a>
 and/or the <tt>nspace</tt> feature is used, it is emitted to the main
 proxy D module only).</p>
</dd>
<dt><tt>%pragma(d) globalproxyimports</tt></dt>
<dd>
<p>The D module currently does not support specifying dependencies on
 external modules (e.g. from the standard library) for the D typemaps.
 To add the import statements to the proxy modules (resp. to<em> all</em>
 proxy modules if in split proxy mode), you can use the <tt>
globalproxyimports</tt> directive.</p>
<p>For example:</p>
<div class="code">
<pre>
%typemap(din) char[] &quot;($dinput ? tango.stdc.stringz.toStringz($dinput) : null)&quot;
%pragma(d) globalproxyimports = &quot;static import tango.stdc.stringz;&quot;;
</pre>
</div></dd>
<dt><tt>%pragma(d) wrapperloadercode</tt></dt>
<dd>
<p>The D code for loading the wrapper library (it is copied to the
 intermediary D module). The <tt>$wrapperloaderbindcode</tt> variable is
 replaced by the list of commands for binding the functions from the
 wrapper library to the symbols in the intermediary D module.</p>
<p>Each time this pragma is specified, the previous value is
 overwritten.</p>
</dd>
<dt><tt>%pragma(d) wrapperloaderbindcommand</tt></dt>
<dd>
<p>The D command to use for binding the wrapper functions from the C/C++
 library to the symbols in the intermediary D module. The <tt>$function</tt>
 variable contains the name of the D function in the wrap module, the <tt>
$symbol</tt> variable is replaced by the name of the symbol in the
 library.</p>
<p>Each time this pragma is specified, the previous value is
 overwritten.</p>
</dd>
</dl>
<h2><a name="D_exceptions">23.6 D Exceptions</a></h2>
<p>Out of the box, C++ exceptions are fundamentally incompatible to
 their equivalent in the D world and cannot simply be propagated to a
 calling D method. There is, however, an easy way to solve this problem:
 Just catch the exception in the C/C++ wrapper layer, pass the contents
 to D, and make the wrapper code rethrow the exception in the D world.</p>
<p>The implementation details of this are a bit crude, but the SWIG D
 module automatically takes care of this, as long as it is able to
 detect that an exception could potentially be thrown (e.g. because the
 C++ method has a <tt>throw(...)</tt> exception specification).</p>
<p>As this feature is implemented in exactly the same way it is for C#,
 please see the <a href="#CSharp_exceptions">C# documentation</a> for a
 more detailed explanation.</p>
<h2><a name="D_directors">23.7 D Directors</a></h2>
<p>When the directors feature is activated, SWIG generates extra code on
 both the C++ and the D side to enable cross-language polymorphism.
 Essentially, this means that if you subclass a proxy class in D, C++
 code can access any overridden virtual methods just as if you created a
 derived class in C++.</p>
<p>There is no D specific documentation yet, but the way the feature is
 implemented is very similar to how it is done in <a href="#Java_directors">
Java</a> and <a href="#CSharp_directors">C#</a>.</p>
<h2><a name="D_other_features">23.8 Other features</a></h2>
<h3><a name="D_nspace">23.8.1 Extended namespace support (nspace)</a></h3>
<p>By default, SWIG flattens all C++ namespaces into a single target
 language namespace, but as for Java and C#, the <a href="#SWIGPlus_nspace">
<tt>nspace</tt></a> feature is supported for D. If it is active, C++
 namespaces are mapped to D packages/modules. Note, however, that like
 for the other languages,<em> free</em> variables and functions are not
 supported yet; currently, they are all allows written to the main proxy
 D module.</p>
<h3><a name="D_native_pointer_support">23.8.2 Native pointer support</a></h3>
<p>Contrary to many of the scripting languages supported by SWIG, D
 fully supports C-style pointers. The D module thus includes a custom
 mechanism to wrap C pointers directly as D pointers where applicable,
 that is, if the type that is pointed to is represented the same in C
 and D (on the bit-level), dubbed a<em> primitive type</em> below.</p>
<p>Central to this custom pointer handling scheme are two typemap
 attributes: the <tt>cprimitive</tt> attribute on the <tt>dtype</tt>
 typemap and the <tt>nativepointer</tt> attribute on all the typemaps
 which influence the D side of the code (<tt>dtype</tt>, <tt>din</tt>, <tt>
dout</tt>, ...). When a D typemap is looked up, the following happens
 behind the scenes:</p>
<p>First, the matching typemap is determined by the usual typemap lookup
 rules. Then, it is checked if the result has the <tt>nativepointer</tt>
 attribute set. If it is present, it means that its value should replace
 the typemap value<em> if and only if</em> the actual type the typemap
 is looked up for is a primitive type, a pointer to a primitive type
 (through an arbitrary level of indirections), or a function pointer
 with only primitive types in its signature.</p>
<p>To determine if a type should be considered primitive, the <tt>
cprimitive</tt> attribute on its <tt>dtype</tt> attribute is used. For
 example, the <tt>dtype</tt> typemap for <tt>float</tt> has <tt>
cprimitive=&quot;1&quot;</tt>, so the code from the <tt>nativepointer</tt>
 attribute is taken into account e.g. for <tt>float **</tt> or the
 function pointer <tt>float (*)(float *)</tt>.</p>
<h3><a name="D_operator_overloading">23.8.3 Operator overloading</a></h3>
<p>The D module comes with basic operator overloading support for both
 D1 and D2. There are, however, a few limitations arising from
 conceptual differences between C++ and D:</p>
<p>The first key difference is that C++ supports free functions as
 operators (along with argument-dependent lookup), while D requires
 operators to be member functions of the class they are operating on.
 SWIG can only automatically generate wrapping code for member function
 operators; if you want to use operators defined as free functions in D,
 you need to handle them manually.</p>
<p>Another set of differences between C++ and D concerns individual
 operators. For example, there are quite a few operators which are
 overloadable in C++, but not in D, for example <tt>&amp;&amp;</tt> and <tt>||</tt>
, but also <tt>!</tt>, and prefix increment/decrement operators in <a href="http://www.digitalmars.com/d/1.0/operatoroverloading.html">
D1</a> resp. their postfix pendants in <a href="http://www.digitalmars.com/d/2.0/operatoroverloading.html">
D2</a>.</p>
<p>There are also some cases where the operators can be translated to D,
 but the differences in the implementation details are big enough that a
 rather involved scheme would be required for automatic wrapping them,
 which has not been implemented yet. This affects, for example, the
 array subscript operator, <tt>[]</tt>, in combination with assignments
 - while <tt>operator []</tt> in C++ simply returns a reference which is
 then written to, D resorts to a separate <tt>opIndexAssign</tt> method
 -, or implicit casting (which was introduced in D2 via <tt>alias this</tt>
). Despite the lack of automatic support, manually handling these cases
 should be perfectly possible.</p>
<h3><a name="D_test_suite">23.8.4 Running the test-suite</a></h3>
<p>As with any other language, the SWIG test-suite can be built for D
 using the <tt>*-d-test-suite</tt> targets of the top-level Makefile. By
 default, D1 is targeted, to build it with D2, use the optional <tt>
D_VERSION</tt> variable, e.g. <tt>make check-d-test-suite D_VERSION=2</tt>
.</p>
<p>Note: If you want to use GDC on Linux or another platform which
 requires you to link <tt>libdl</tt> for dynamically loading the shared
 library, you might have to add <tt>-ldl</tt> manually to the <tt>
d_compile</tt> target in <tt>Examples/Makefile</tt>, because GDC does
 not currently honor the <tt>pragma(lib, ...)</tt> statement.</p>
<h2><a name="D_typemap_examples">23.9 D Typemap examples</a></h2>
<p>There are no D-specific typemap examples yet. However, with the above
 <a href="#D_typemap_name_comparison">name comparison table</a>, you
 should be able to get an idea what can be done by looking at the <a href="#CSharp_typemap_examples">
corresponding C# section</a>.</p>
<h2><a name="D_planned_features">23.10 Work in progress and planned
 features</a></h2>
<p>There are a couple of features which are not implemented yet, but
 would be very useful and might be added in the near future:</p>
<ul>
<li><em>Static linking:</em> Currently, the C wrapper code is compiled
 into a dynamic library, out of which the symbol addresses are looked up
 at runtime by the D part. If statically linking the different languages
 into one binary was supported, a tool-chain capable of performing IPO
 at link time could inline the wrapping code, effectively reducing the
 overhead for simple calls to zero.</li>
<li><em>C array handling:</em> Many data structures in some C/C++
 libraries contain array containing of a pointer to the first element
 and the element count. Currently, one must manually writing wrapper
 code to be able to access these from D. It should be possible to add a
 set of SWIG macros to semi-automatically generate conversion code.</li>
</ul>
<p>Some generated code might also be a bit rough around the edges,
 particularly in the following areas:</p>
<ul>
<li><em>Memory management:</em> Although the currently generated wrapper
 code works fine with regard to the GC for the test-suite, there might
 be issues coming up in real-world multi-threaded usage.</li>
<li><em>D2 support</em>: Originally, the module has been developed for
 the use with D1, D2/Phobos support has been added in later. The basic
 features should work equally well for both, but there<em> could</em> be
 issues concerning const-correctness etc.</li>
</ul>
<HR NOSHADE>
<h1><a name="Go">24 SWIG and Go</a></h1>

<!-- INDEX -->
<div class="sectiontoc">
<ul>
<li><a href="#Go_overview">Overview</a></li>
<li><a href="#Go_examples">Examples</a></li>
<li><a href="#Go_running_swig">Running SWIG with Go</a>
<ul>
<li><a href="#Go_commandline">Go-specific Commandline Options</a></li>
<li><a href="#Go_outputs">Generated Wrapper Files</a></li>
</ul>
</li>
<li><a href="#Go_basic_tour">A tour of basic C/C++ wrapping</a>
<ul>
<li><a href="#Go_package">Go Package Name</a></li>
<li><a href="#Go_names">Go Names</a></li>
<li><a href="#Go_constants">Go Constants</a></li>
<li><a href="#Go_enumerations">Go Enumerations</a></li>
<li><a href="#Go_classes">Go Classes</a>
<ul>
<li><a href="#Go_class_memory">Go Class Memory Management</a></li>
<li><a href="#Go_class_inheritance">Go Class Inheritance</a></li>
</ul>
</li>
<li><a href="#Go_templates">Go Templates</a></li>
<li><a href="#Go_director_classes">Go Director Classes</a>
<ul>
<li><a href="#Go_director_example_cpp_code">Example C++ code</a></li>
<li><a href="#Go_director_enable">Enable director feature</a></li>
<li><a href="#Go_director_ctor_dtor">Constructor and destructor</a></li>
<li><a href="#Go_director_overriding">Override virtual methods</a></li>
<li><a href="#Go_director_base_methods">Call base methods</a></li>
<li><a href="#Go_director_subclass">Subclass via embedding</a></li>
<li><a href="#Go_director_finalizer">Memory management with
 runtime.SetFinalizer</a></li>
<li><a href="#Go_director_foobargo_class">Complete FooBarGo example
 class</a></li>
</ul>
</li>
<li><a href="#Go_primitive_type_mappings">Default Go primitive type
 mappings</a></li>
<li><a href="#Go_output_arguments">Output arguments</a></li>
<li><a href="#Go_adding_additional_code">Adding additional go code</a></li>
<li><a href="#Go_typemaps">Go typemaps</a></li>
</ul>
</li>
</ul>
</div>
<!-- INDEX -->
<p> This chapter describes SWIG's support of Go. For more information on
 the Go programming language see <a href="http://golang.org/">golang.org</a>
.</p>
<h2><a name="Go_overview">24.1 Overview</a></h2>
<p> Go does not support direct calling of functions written in C/C++.
 The <a href="https://golang.org/cmd/cgo/">cgo program</a> may be used
 to generate wrappers to call C code from Go, but there is no convenient
 way to call C++ code. SWIG fills this gap.</p>
<p> There are (at least) two different Go compilers. The first is the gc
 compiler of the <a href="https://golang.org/doc/install">Go
 distribution</a>, normally invoked via the <a href="https://golang.org/cmd/go/">
go tool</a>. The second Go compiler is the <a href="https://golang.org/doc/install/gccgo">
 gccgo compiler</a>, which is a frontend to the GCC compiler suite. The
 interface to C/C++ code is completely different for the two Go
 compilers. SWIG supports both Go compilers, selected by the <tt>-gccgo</tt>
 command line option.</p>
<p> Go is a type-safe compiled language and the wrapper code generated
 by SWIG is type-safe as well. In case of type issues the build will
 fail and hence SWIG's <a href="#Modules_nn2">runtime library</a> and <a href="#Typemaps_runtime_type_checker">
runtime type checking</a> are not used.</p>
<h2><a name="Go_examples">24.2 Examples</a></h2>
<p> Working examples can be found in the <a href="https://github.com/swig/swig/tree/master/Examples/go">
SWIG source tree</a> .</p>
<p> Please note that the examples in the SWIG source tree use makefiles
 with the .i SWIG interface file extension for backwards compatibility
 with Go 1.</p>
<h2><a name="Go_running_swig">24.3 Running SWIG with Go</a></h2>
<p> Most Go programs are built using the <a href="https://golang.org/cmd/go/">
go tool</a>. Since Go 1.1 the go tool has support for SWIG. To use it,
 give your SWIG interface file the extension .swig (for C code) or
 .swigcxx (for C++ code). Put that file in a GOPATH/src directory as
 usual for Go sources. Put other C/C++ code in the same directory with
 extensions of .c and .cxx. The <tt>go build</tt> and <tt>go install</tt>
 commands will automatically run SWIG for you and compile the generated
 wrapper code. To check the SWIG command line options the go tool uses
 run <tt>go build -x</tt>. To access the automatically generated files
 run <tt>go build -work</tt>. You'll find the files under the temporary
 WORK directory.</p>
<p> To manually generate and compile C/C++ wrapper code for Go, use the <tt>
-go</tt> option with SWIG. By default SWIG will generate code for the Go
 compiler of the Go distribution. To generate code for gccgo, you should
 also use the <tt>-gccgo</tt> option.</p>
<p> By default SWIG will generate files that can be used directly by <tt>
go build</tt>. This requires Go 1.2 or later. Put your SWIG interface
 file in a directory under GOPATH/src, and give it a name that does<b>
 not</b> end in the .swig or .swigcxx extension. Typically the SWIG
 interface file extension is .i in this case.</p>
<div class="code">
<pre>
% swig -go example.i
% go install
</pre>
</div>
<p> You will now have a Go package that you can import from other Go
 packages as usual.</p>
<p> SWIG can be used without cgo, via the <tt>-no-cgo</tt> option, but
 more steps are required. This only works with Go versions before 1.5.
 When using Go version 1.2 or later, or when using gccgo, the code
 generated by SWIG can be linked directly into the Go program. A typical
 command sequence when using the Go compiler of the Go distribution
 would look like this:</p>
<div class="code">
<pre>
% swig -go -no-cgo example.i
% gcc -c code.c    # The C library being wrapped.
% gcc -c example_wrap.c
% go tool 6g example.go
% go tool 6c example_gc.c
% go tool pack grc example.a example.6 example_gc.6 code.o example_wrap.o
% go tool 6g main.go
% go tool 6l main.6
</pre>
</div>
<p> You can also put the wrapped code into a shared library, and when
 using the Go versions before 1.2 this is the only supported option. A
 typical command sequence for this approach would look like this:</p>
<div class="code">
<pre>
% swig -go -no-cgo -use-shlib example.i
% gcc -c -fpic example.c
% gcc -c -fpic example_wrap.c
% gcc -shared example.o example_wrap.o -o example.so
% go tool 6g example.go
% go tool 6c example_gc.c
% go tool pack grc example.a example.6 example_gc.6
% go tool 6g main.go  # your code, not generated by SWIG
% go tool 6l main.6
</pre>
</div>
<h3><a name="Go_commandline">24.3.1 Go-specific Commandline Options</a></h3>
<p> These are the command line options for SWIG's Go module. They can
 also be seen by using:</p>
<div class="code">
<pre>
swig -go -help
</pre>
</div>
<table summary="Go-specific options">
<tr><th>Go-specific options</th></tr>
<tr><td>-cgo</td><td>Generate files to be used as input for the Go cgo
 tool. This is the default.</td></tr>
<tr><td>-no-cgo</td><td>Generate files that can be used directly, rather
 than via the Go cgo tool. This option does not work with Go 1.5 or
 later. It is required for versions of Go before 1.2.</td></tr>
<tr><td>-intgosize &lt;s&gt;</td><td>Set the size for the Go type <tt>int</tt>
. This controls the size that the C/C++ code expects to see. The &lt;s&gt;
 argument should be 32 or 64. This option is currently required during
 the transition from Go 1.0 to Go 1.1, as the size of <tt>int</tt> on
 64-bit x86 systems changes between those releases (from 32 bits to 64
 bits). In the future the option may become optional, and SWIG will
 assume that the size of <tt>int</tt> is the size of a C pointer.</td></tr>
<tr><td>-gccgo</td><td>Generate code for gccgo. The default is to
 generate code for the Go compiler of the Go distribution.</td></tr>
<tr><td>-package &lt;name&gt;</td><td>Set the name of the Go package to
 &lt;name&gt;. The default package name is the SWIG module name.</td></tr>
<tr><td>-use-shlib</td><td>Tell SWIG to emit code that uses a shared
 library. This is only meaningful for the Go compiler of the Go
 distribution, which needs to know at compile time whether a shared
 library will be used.</td></tr>
<tr><td>-soname &lt;name&gt;</td><td>Set the runtime name of the shared
 library that the dynamic linker should include at runtime. The default
 is the package name with &quot;.so&quot; appended. This is only used when
 generating code for the Go compiler of the Go distribution; when using
 gccgo, the equivalent name will be taken from the <code>-soname</code>
 option passed to the linker. Using this option implies the -use-shlib
 option.</td></tr>
<tr><td>-go-pkgpath &lt;pkgpath&gt;</td><td>When generating code for gccgo,
 set the pkgpath to use. This corresponds to the <tt>-fgo-pkgpath</tt>
 option to gccgo.</td></tr>
<tr><td>-go-prefix &lt;prefix&gt;</td><td>When generating code for gccgo, set
 the prefix to use. This corresponds to the <tt>-fgo-prefix</tt> option
 to gccgo. If <tt>-go-pkgpath</tt> is used, <tt>-go-prefix</tt> will be
 ignored.</td></tr>
<tr><td>-import-prefix &lt;prefix&gt;</td><td>A prefix to add when turning a
 %import prefix in the SWIG interface file into an import statement in
 the Go file. For example, with <code>-import-prefix mymodule</code>, a
 SWIG interface file <code>%import mypackage</code> will become a Go
 import statement <code>import &quot;mymodule/mypackage&quot;</code>.</td></tr>
</table>
<h3><a name="Go_outputs">24.3.2 Generated Wrapper Files</a></h3>
<p>There are two different approaches to generating wrapper files,
 controlled by SWIG's <tt>-no-cgo</tt> option. The <tt>-no-cgo</tt>
 option only works with version of Go before 1.5. It is required when
 using versions of Go before 1.2.</p>
<p>With or without the <tt>-no-cgo</tt> option, SWIG will generate the
 following files when generating wrapper code:</p>
<ul>
<li> MODULE.go will contain the Go functions that your Go code will
 call. These functions will be wrappers for the C++ functions defined by
 your module. This file should, of course, be compiled with the Go
 compiler.</li>
<li> MODULE_wrap.c or MODULE_wrap.cxx will contain C/C++ functions will
 be invoked by the Go wrapper code. This file should be compiled with
 the usual C or C++ compiler.</li>
<li> MODULE_wrap.h will be generated if you use the directors feature.
 It provides a definition of the generated C++ director classes. It is
 generally not necessary to use this file, but in some special cases it
 may be helpful to include it in your code, compiled with the usual C or
 C++ compiler.</li>
</ul>
<p>When the <tt>-no-cgo</tt> option is used, and the <tt>-gccgo</tt>
 option is not used, SWIG will also generate an additional file:</p>
<ul>
<li> MODULE_gc.c will contain C code which should be compiled with the C
 compiler distributed as part of the gc compiler. It should then be
 combined with the compiled MODULE.go using go tool pack.</li>
</ul>
<h2><a name="Go_basic_tour">24.4 A tour of basic C/C++ wrapping</a></h2>
<p> By default, SWIG attempts to build a natural Go interface to your
 C/C++ code. However, the languages are somewhat different, so some
 modifications have to occur. This section briefly covers the essential
 aspects of this wrapping.</p>
<h3><a name="Go_package">24.4.1 Go Package Name</a></h3>
<p> All Go source code lives in a package. The name of this package will
 default to the name of the module from SWIG's <tt>%module</tt>
 directive. You may override this by using SWIG's <tt>-package</tt>
 command line option.</p>
<h3><a name="Go_names">24.4.2 Go Names</a></h3>
<p> In Go, a function is only visible outside the current package if the
 first letter of the name is uppercase. This is quite different from
 C/C++. Because of this, C/C++ names are modified when generating the Go
 interface: the first letter is forced to be uppercase if it is not
 already. This affects the names of functions, methods, variables,
 constants, enums, and classes.</p>
<p> C/C++ variables are wrapped with setter and getter functions in Go.
 First the first letter of the variable name will be forced to
 uppercase, and then <tt>Get</tt> or <tt>Set</tt> will be prepended. For
 example, if the C/C++ variable is called <tt>var</tt>, then SWIG will
 define the functions <tt>GetVar</tt> and <tt>SetVar</tt>. If a variable
 is declared as <tt>const</tt>, or if SWIG's <a href="#SWIG_readonly_variables">
 <tt>%immutable</tt> directive</a> is used for the variable, then only
 the getter will be defined.</p>
<p> C++ classes will be discussed further below. Here we'll note that
 the first letter of the class name will be forced to uppercase to give
 the name of a type in Go. A constructor will be named <tt>New</tt>
 followed by that name, and the destructor will be named <tt>Delete</tt>
 followed by that name.</p>
<h3><a name="Go_constants">24.4.3 Go Constants</a></h3>
<p> C/C++ constants created via <tt>#define</tt> or the <tt>%constant</tt>
 directive become Go constants, declared with a <tt>const</tt>
 declaration.</p>
<h3><a name="Go_enumerations">24.4.4 Go Enumerations</a></h3>
<p> C/C++ enumeration types will cause SWIG to define an integer type
 with the name of the enumeration (with first letter forced to uppercase
 as usual). The values of the enumeration will become variables in Go;
 code should avoid modifying those variables.</p>
<h3><a name="Go_classes">24.4.5 Go Classes</a></h3>
<p> Go has interfaces, methods and inheritance, but it does not have
 classes in the same sense as C++. This sections describes how SWIG
 represents C++ classes represented in Go.</p>
<p> For a C++ class <tt>ClassName</tt>, SWIG will define two types in
 Go: an underlying type, which will just hold a pointer to the C++ type,
 and an interface type. The interface type will be named <tt>ClassName</tt>
. SWIG will define a function <tt>NewClassName</tt> which will take any
 constructor arguments and return a value of the interface type <tt>
ClassName</tt>. SWIG will also define a destructor <tt>DeleteClassName</tt>
.</p>
<p> SWIG will represent any methods of the C++ class as methods on the
 underlying type, and also as methods of the interface type. Thus C++
 methods may be invoked directly using the usual <tt>val.MethodName</tt>
 syntax. Public members of the C++ class will be given getter and setter
 functions defined as methods of the class.</p>
<p> SWIG will represent static methods of C++ classes as ordinary Go
 functions. SWIG will use names like <tt>ClassNameMethodName</tt>. SWIG
 will give static members getter and setter functions with names like <tt>
GetClassName_VarName</tt>.</p>
<p> Given a value of the interface type, Go code can retrieve the
 pointer to the C++ type by calling the <tt>Swigcptr</tt> method. This
 will return a value of type <tt>SwigcptrClassName</tt>, which is just a
 name for <tt>uintptr</tt>. A Go type conversion can be used to convert
 this value to a different C++ type, but note that this conversion will
 not be type checked and is essentially equivalent to <tt>
reinterpret_cast</tt>. This should only be used for very special cases,
 such as where C++ would use a <tt>dynamic_cast</tt>.</p>
<p>Note that C++ pointers to compound objects are represented in go as
 objects themselves, not as go pointers. So, for example, if you wrap
 the following function:</p>
<div class="code">
<pre>
class MyClass {
  int MyMethod();
  static MyClass *MyFactoryFunction();
};

</pre>
</div>
<p>You will get go code that looks like this:</p>
<div class="code">
<pre>
type MyClass interface {
  Swigcptr() uintptr
  SwigIsMyClass()
  MyMethod() int
}

func MyClassMyFactoryFunction() MyClass {
  // swig magic here
}
</pre>
</div>
<p>Note that the factory function does not return a go pointer; it
 actually returns a go interface. If the returned pointer can be null,
 you can check for this by calling the Swigcptr() method.</p>
<h4><a name="Go_class_memory">24.4.5.1 Go Class Memory Management</a></h4>
<p> Calling <tt>NewClassName</tt> for a C++ class <tt>ClassName</tt>
 will allocate memory using the C++ memory allocator. This memory will
 not be automatically freed by Go's garbage collector as the object
 ownership is not tracked. When you are done with the C++ object you
 must free it using <tt>DeleteClassName</tt>.
<br>
<br> The most Go idiomatic way to manage the memory for some C++ class
 is to call <tt>NewClassName</tt> followed by a <tt><a href="https://golang.org/doc/effective_go.html#defer">
defer</a></tt> of the <tt>DeleteClassName</tt> call. Using <tt>defer</tt>
 ensures that the memory of the C++ object is freed as soon as the
 function containing the <tt>defer</tt> statement returns. Furthermore <tt>
defer</tt> works great for short-lived objects and fits nicely C++'s
 RAII idiom. Example:</p>
<div class="code">
<pre>
func UseClassName(...) ... {
  o := NewClassName(...)
  defer DeleteClassName(o)
  // Use the ClassName object
  return ...
}
</pre>
</div>
<p> With increasing complexity, especially complex C++ object
 hierarchies, the correct placement of <tt>defer</tt> statements becomes
 harder and harder as C++ objects need to be freed in the correct order.
 This problem can be eased by keeping a C++ object function local so
 that it is only available to the function that creates a C++ object and
 functions called by this function. Example:</p>
<div class="code">
<pre>
func WithClassName(constructor args, f func(ClassName, ...interface{}) error, data ...interface{}) error {
  o := NewClassName(constructor args)
  defer DeleteClassName(o)
  return f(o, data...)
}

func UseClassName(o ClassName, data ...interface{}) (err error) {
  // Use the ClassName object and additional data and return error.
}

func main() {
  WithClassName(constructor args, UseClassName, additional data)
}
</pre>
</div>
<p> Using <tt>defer</tt> has limitations though, especially when it
 comes to long-lived C++ objects whose lifetimes are hard to predict.
 For such C++ objects a common technique is to store the C++ object into
 a Go object, and to use the Go function <tt>runtime.SetFinalizer</tt>
 to add a finalizer which frees the C++ object when the Go object is
 freed. It is strongly recommended to read the <a href="https://golang.org/pkg/runtime/#SetFinalizer">
runtime.SetFinalizer</a> documentation before using this technique to
 understand the <tt>runtime.SetFinalizer</tt> limitations.
<br></p>
<p> Common pitfalls with <tt>runtime.SetFinalizer</tt> are:</p>
<ul>
<li> If a hierarchy of C++ objects will be automatically freed by Go
 finalizers then the Go objects that store the C++ objects need to
 replicate the hierarchy of the C++ objects to prevent that C++ objects
 are freed prematurely while other C++ objects still rely on them.</li>
<li> The usage of Go finalizers is problematic with C++'s RAII idiom as
 it isn't predictable when the finalizer will run and this might require
 a Close or Delete method to be added the Go object that stores a C++
 object to mitigate.</li>
<li> The Go finalizer function typically runs in a different OS thread
 which can be problematic with C++ code that uses thread-local storage.</li>
</ul>
<p> <tt>runtime.SetFinalizer</tt> Example:</p>
<div class="code">
<pre>
import (
  &quot;runtime&quot;
  &quot;wrap&quot; // SWIG generated wrapper code
)

type GoClassName struct {
  wcn wrap.ClassName
}

func NewGoClassName() *GoClassName {
  o := &amp;GoClassName{wcn: wrap.NewClassName()}
  runtime.SetFinalizer(o, deleteGoClassName)
  return o
}

func deleteGoClassName(o *GoClassName) {
  // Runs typically in a different OS thread!
  wrap.DeleteClassName(o.wcn)
  o.wcn = nil
}

func (o *GoClassName) Close() {
  // If the C++ object has a Close method.
  o.wcn.Close()

  // If the GoClassName object is no longer in an usable state.
  runtime.SetFinalizer(o, nil) // Remove finalizer.
  deleteGoClassName() // Free the C++ object.
}
</pre>
</div>
<h4><a name="Go_class_inheritance">24.4.5.2 Go Class Inheritance</a></h4>
<p> C++ class inheritance is automatically represented in Go due to its
 use of interfaces. The interface for a child class will be a superset
 of the interface of its parent class. Thus a value of the child class
 type in Go may be passed to a function which expects the parent class.
 Doing the reverse will require an explicit type assertion, which will
 be checked dynamically.</p>
<h3><a name="Go_templates">24.4.6 Go Templates</a></h3>
<p> In order to use C++ templates in Go, you must tell SWIG to create
 wrappers for a particular template instantiation. To do this, use the <tt>
%template</tt> directive.</p>
<h3><a name="Go_director_classes">24.4.7 Go Director Classes</a></h3>
<p> SWIG's director feature permits a Go type to act as the subclass of
 a C++ class. This is complicated by the fact that C++ and Go define
 inheritance differently. SWIG normally represents the C++ class
 inheritance automatically in Go via interfaces but with a Go type
 representing a subclass of a C++ class some manual work is necessary.</p>
<p> This subchapter gives a step by step guide how to properly subclass
 a C++ class with a Go type. In general it is strongly recommended to
 follow this guide completely to avoid common pitfalls with directors in
 Go.</p>
<h4><a name="Go_director_example_cpp_code">24.4.7.1 Example C++ code</a></h4>
<p> The step by step guide is based on two example C++ classes.
 FooBarAbstract is an abstract C++ class and the FooBarCpp class
 inherits from it. This guide explains how to implement a FooBarGo class
 similar to the FooBarCpp class.</p>
<p> <tt>FooBarAbstract</tt> abstract C++ class:</p>
<div class="code">
<pre>
class FooBarAbstract
{
public:
  FooBarAbstract() {};
  virtual ~FooBarAbstract() {};

  std::string FooBar() {
    return this-&gt;Foo() + &quot;, &quot; + this-&gt;Bar();
  };

protected:
  virtual std::string Foo() {
    return &quot;Foo&quot;;
  };

  virtual std::string Bar() = 0;
};
</pre>
</div>
<p> <tt>FooBarCpp</tt> C++ class:</p>
<div class="code">
<pre>
class FooBarCpp : public FooBarAbstract
{
protected:
  virtual std::string Foo() {
    return &quot;C++ &quot; + FooBarAbstract::Foo();
  }

  virtual std::string Bar() {
    return &quot;C++ Bar&quot;;
  }
};
</pre>
</div>
<p> Returned string by the <tt>FooBarCpp::FooBar</tt> method is:</p>
<div class="code">
<pre>
C++ Foo, C++ Bar
</pre>
</div>
<p> The complete example, including the <tt>FooBarGoo</tt> class
 implementation, can be found in <a href="#Go_director_foobargo_class">
the end of the guide</a>.</p>
<h4><a name="Go_director_enable">24.4.7.2 Enable director feature</a></h4>
<p> The director feature is disabled by default. To use directors you
 must make two changes to the interface file. First, add the &quot;directors&quot;
 option to the %module directive, like this:</p>
<div class="code">
<pre>
%module(directors=&quot;1&quot;) modulename
</pre>
</div>
<p> Second, you must use the %feature(&quot;director&quot;) directive to tell SWIG
 which classes should get directors. In the example the FooBarAbstract
 class needs the director feature enabled so that the FooBarGo class can
 inherit from it, like this:</p>
<div class="code">
<pre>
%feature(&quot;director&quot;) FooBarAbstract;
</pre>
</div>
<p> For a more detailed documentation of the director feature and how to
 enable or disable it for specific classes and virtual methods see
 SWIG's Java documentation on directors.</p>
<h4><a name="Go_director_ctor_dtor">24.4.7.3 Constructor and destructor</a>
</h4>
<p> SWIG creates an additional set of constructor and destructor
 functions once the director feature has been enabled for a C++ class. <tt>
NewDirectorClassName</tt> allows overriding virtual methods on the new
 object instance and <tt>DeleteDirectorClassName</tt> needs to be used
 to free a director object instance created with <tt>
NewDirectorClassName</tt>. More on overriding virtual methods follows
 later in this guide under <a href="#Go_director_overriding">overriding
 virtual methods</a>.</p>
<p> The default constructor and destructor functions <tt>NewClassName</tt>
 and <tt>DeleteClassName</tt> can still be used as before so that
 existing code doesn't break just because the director feature has been
 enabled for a C++ class. The behavior is undefined if the default and
 director constructor and destructor functions get mixed and so great
 care needs to be taken that only one of the constructor and destructor
 function pairs is used for any object instance. Both constructor
 functions, the default and the director one, return the same interface
 type. This makes it potentially hard to know which destructor function,
 the default or the director one, needs to be called to delete an object
 instance.</p>
<p> In<b> theory</b> the <tt>DirectorInterface</tt> method could be used
 to determine if an object instance was created via <tt>
NewDirectorClassName</tt>:</p>
<div class="code">
<pre>
if o.DirectorInterface() != nil {
  DeleteDirectorClassName(o)
} else {
  DeleteClassName(o)
}
</pre>
</div>
<p> In<b> practice</b> it is strongly recommended to embed a director
 object instance in a Go struct so that a director object instance will
 be represented as a distinct Go type that subclasses a C++ class. For
 this Go type custom constructor and destructor functions take care of
 the director constructor and destructor function calls and the
 resulting Go class will appear to the user as any other SWIG wrapped
 C++ class. More on properly subclassing a C++ class follows later in
 this guide under <a href="#Go_director_subclass">subclass via embedding</a>
.</p>
<h4><a name="Go_director_overriding">24.4.7.4 Override virtual methods</a>
</h4>
<p> In order to override virtual methods on a C++ class with Go methods
 the <tt>NewDirectorClassName</tt> constructor functions receives a <tt>
DirectorInterface</tt> argument. The methods in the <tt>
DirectorInterface</tt> are a subset of the public and protected virtual
 methods of the C++ class. Virtual methods that have a final specifier
 are unsurprisingly excluded. If the <tt>DirectorInterface</tt> contains
 a method with a matching signature to a virtual method of the C++ class
 then the virtual C++ method will be overwritten with the Go method. As
 Go doesn't support protected methods all overridden protected virtual
 C++ methods will be public in Go.</p>
<p> As an example see part of the <tt>FooBarGo</tt> class:</p>
<div class="code">
<pre>
type overwrittenMethodsOnFooBarAbstract struct {
  fb FooBarAbstract
}

func (om *overwrittenMethodsOnFooBarAbstract) Foo() string {
  ...
}

func (om *overwrittenMethodsOnFooBarAbstract) Bar() string {
  ...
}

func NewFooBarGo() FooBarGo {
  om := &amp;overwrittenMethodsOnFooBarAbstract{}
  fb := NewDirectorFooBarAbstract(om)
  om.fb = fb
  ...
}
</pre>
</div>
<p> The complete example, including the <tt>FooBarGoo</tt> class
 implementation, can be found in <a href="#Go_director_foobargo_class">
the end of the guide</a>. In this part of the example the virtual
 methods <tt>FooBarAbstract::Foo</tt> and <tt>FooBarAbstract::Bar</tt>
 have been overwritten with Go methods similarly to how the <tt>
FooBarAbstract</tt> virtual methods are overwritten by the <tt>FooBarCpp</tt>
 class.</p>
<p> The <tt>DirectorInterface</tt> in the example is implemented by the <tt>
overwrittenMethodsOnFooBarAbstract</tt> Go struct type. A pointer to a <tt>
overwrittenMethodsOnFooBarAbstract</tt> struct instance will be given to
 the <tt>NewDirectorFooBarAbstract</tt> constructor function. The
 constructor return value implements the <tt>FooBarAbstract</tt>
 interface. <tt>overwrittenMethodsOnFooBarAbstract</tt> could in theory
 be any Go type but in practice a struct is used as it typically
 contains at least a value of the C++ class interface so that the
 overwritten methods can use the rest of the C++ class. If the <tt>
FooBarGo</tt> class would receive additional constructor arguments then
 these would also typically be stored in the <tt>
overwrittenMethodsOnFooBarAbstract</tt> struct so that they can be used
 by the Go methods.</p>
<h4><a name="Go_director_base_methods">24.4.7.5 Call base methods</a></h4>
<p> Often a virtual method will be overwritten to extend the original
 behavior of the method in the base class. This is also the case for the
 <tt>FooBarCpp::Foo</tt> method of the example code:</p>
<div class="code">
<pre>
virtual std::string Foo() {
  return &quot;C++ &quot; + FooBarAbstract::Foo();
}
</pre>
</div>
<p> To use base methods the <tt>DirectorClassNameMethodName</tt> wrapper
 functions are automatically generated by SWIG for public and protected
 virtual methods. The <tt>FooBarGo.Foo</tt> implementation in the
 example looks like this:</p>
<div class="code">
<pre>
func (om *overwrittenMethodsOnFooBarAbstract) Foo() string {
  return &quot;Go &quot; + DirectorFooBarAbstractFoo(om.fb)
}
</pre>
</div>
<p> The complete example, including the <tt>FooBarGoo</tt> class
 implementation, can be found in <a href="#Go_director_foobargo_class">
the end of the guide</a>.</p>
<h4><a name="Go_director_subclass">24.4.7.6 Subclass via embedding</a></h4>
<p> <a href="#Go_director_ctor_dtor">As previously mentioned in this
 guide</a> the default and director constructor functions return the
 same interface type. To properly subclass a C++ class with a Go type
 the director object instance returned by the <tt>NewDirectorClassName</tt>
 constructor function should be embedded into a Go struct so that it
 represents a distinct but compatible type in Go's type system. This Go
 struct should be private and the constructor and destructor functions
 should instead work with a public interface type so that the Go class
 that subclasses a C++ class can be used as a compatible drop in.</p>
<p> The subclassing part of the <tt>FooBarGo</tt> class for an example
 looks like this:</p>
<div class="code">
<pre>
type FooBarGo interface {
  FooBarAbstract
  deleteFooBarAbstract()
  IsFooBarGo()
}

type fooBarGo struct {
  FooBarAbstract
}

func (fbgs *fooBarGo) deleteFooBarAbstract() {
  DeleteDirectorFooBarAbstract(fbgs.FooBarAbstract)
}

func (fbgs *fooBarGo) IsFooBarGo() {}

func NewFooBarGo() FooBarGo {
  om := &amp;overwrittenMethodsOnFooBarAbstract{}
  fb := NewDirectorFooBarAbstract(om)
  om.fb = fb

  return &amp;fooBarGo{FooBarAbstract: fb}
}

func DeleteFooBarGo(fbg FooBarGo) {
  fbg.deleteFooBarAbstract()
}
</pre>
</div>
<p> The complete example, including the <tt>FooBarGoo</tt> class
 implementation, can be found in <a href="#Go_director_foobargo_class">
the end of the guide</a>. In this part of the example the private <tt>
fooBarGo</tt> struct embeds <tt>FooBarAbstract</tt> which lets the <tt>
fooBarGo</tt> Go type &quot;inherit&quot; all the methods of the <tt>
FooBarAbstract</tt> C++ class by means of embedding. The public <tt>
FooBarGo</tt> interface type includes the <tt>FooBarAbstract</tt>
 interface and hence <tt>FooBarGo</tt> can be used as a drop in
 replacement for <tt>FooBarAbstract</tt> while the reverse isn't
 possible and would raise a compile time error. Furthermore the
 constructor and destructor functions <tt>NewFooBarGo</tt> and <tt>
DeleteFooBarGo</tt> take care of all the director specifics and to the
 user the class appears as any other SWIG wrapped C++ class.</p>
<h4><a name="Go_director_finalizer">24.4.7.7 Memory management with
 runtime.SetFinalizer</a></h4>
<p> In general all guidelines for <a href="#Go_class_memory">C++ class
 memory management</a> apply as well to director classes. One often
 overlooked limitation with <tt>runtime.SetFinalizer</tt> is that a
 finalizer doesn't run in case of a cycle and director classes typically
 have a cycle. The cycle in the <tt>FooBarGo</tt> class is here:</p>
<div class="code">
<pre>
type overwrittenMethodsOnFooBarAbstract struct {
  fb FooBarAbstract
}

func NewFooBarGo() FooBarGo {
  om := &amp;overwrittenMethodsOnFooBarAbstract{}
  fb := NewDirectorFooBarAbstract(om) // fb.v = om
  om.fb = fb // Backlink causes cycle as fb.v = om!
  ...
}
</pre>
</div>
<p> In order to be able to use <tt>runtime.SetFinalizer</tt>
 nevertheless the finalizer needs to be set on something that isn't in a
 cycle and that references the director object instance. In the <tt>
FooBarGo</tt> class example the <tt>FooBarAbstract</tt> director
 instance can be automatically deleted by setting the finalizer on <tt>
fooBarGo</tt>:</p>
<div class="code">
<pre>
type fooBarGo struct {
  FooBarAbstract
}

type overwrittenMethodsOnFooBarAbstract struct {
  fb FooBarAbstract
}

func NewFooBarGo() FooBarGo {
  om := &amp;overwrittenMethodsOnFooBarAbstract{}
  fb := NewDirectorFooBarAbstract(om)
  om.fb = fb // Backlink causes cycle as fb.v = om!

  fbgs := &amp;fooBarGo{FooBarAbstract: fb}
  runtime.SetFinalizer(fbgs, FooBarGo.deleteFooBarAbstract)
  return fbgs
}
</pre>
</div>
<p> Furthermore if <tt>runtime.SetFinalizer</tt> is in use either the <tt>
DeleteClassName</tt> destructor function needs to be removed or the <tt>
fooBarGo</tt> struct needs additional data to prevent double deletion.
 Please read the <a href="#Go_class_memory">C++ class memory management</a>
 subchapter before using <tt>runtime.SetFinalizer</tt> to know all of
 its gotchas.</p>
<h4><a name="Go_director_foobargo_class">24.4.7.8 Complete FooBarGo
 example class</a></h4>
<p> The complete and annotated <tt>FooBarGo</tt> class looks like this:</p>
<div class="code">
<pre>
// FooBarGo is a superset of FooBarAbstract and hence FooBarGo can be used as a
// drop in replacement for FooBarAbstract but the reverse causes a compile time
// error.
type FooBarGo interface {
  FooBarAbstract
  deleteFooBarAbstract()
  IsFooBarGo()
}

// Via embedding fooBarGo &quot;inherits&quot; all methods of FooBarAbstract.
type fooBarGo struct {
  FooBarAbstract
}

func (fbgs *fooBarGo) deleteFooBarAbstract() {
  DeleteDirectorFooBarAbstract(fbgs.FooBarAbstract)
}

// The IsFooBarGo method ensures that FooBarGo is a superset of FooBarAbstract.
// This is also how the class hierarchy gets represented by the SWIG generated
// wrapper code.  For an instance FooBarCpp has the IsFooBarAbstract and
// IsFooBarCpp methods.
func (fbgs *fooBarGo) IsFooBarGo() {}

// Go type that defines the DirectorInterface. It contains the Foo and Bar
// methods that overwrite the respective virtual C++ methods on FooBarAbstract.
type overwrittenMethodsOnFooBarAbstract struct {
  // Backlink to FooBarAbstract so that the rest of the class can be used by
  // the overridden methods.
  fb FooBarAbstract

  // If additional constructor arguments have been given they are typically
  // stored here so that the overridden methods can use them.
}

func (om *overwrittenMethodsOnFooBarAbstract) Foo() string {
  // DirectorFooBarAbstractFoo calls the base method FooBarAbstract::Foo.
  return &quot;Go &quot; + DirectorFooBarAbstractFoo(om.fb)
}

func (om *overwrittenMethodsOnFooBarAbstract) Bar() string {
  return &quot;Go Bar&quot;
}

func NewFooBarGo() FooBarGo {
  // Instantiate FooBarAbstract with selected methods overridden.  The methods
  // that will be overwritten are defined on
  // overwrittenMethodsOnFooBarAbstract and have a compatible signature to the
  // respective virtual C++ methods. Furthermore additional constructor
  // arguments will be typically stored in the
  // overwrittenMethodsOnFooBarAbstract struct.
  om := &amp;overwrittenMethodsOnFooBarAbstract{}
  fb := NewDirectorFooBarAbstract(om)
  om.fb = fb // Backlink causes cycle as fb.v = om!

  fbgs := &amp;fooBarGo{FooBarAbstract: fb}
  // The memory of the FooBarAbstract director object instance can be
  // automatically freed once the FooBarGo instance is garbage collected by
  // uncommenting the following line.  Please make sure to understand the
  // runtime.SetFinalizer specific gotchas before doing this.  Furthermore
  // DeleteFooBarGo should be deleted if a finalizer is in use or the fooBarGo
  // struct needs additional data to prevent double deletion.
  // runtime.SetFinalizer(fbgs, FooBarGo.deleteFooBarAbstract)
  return fbgs
}

// Recommended to be removed if runtime.SetFinalizer is in use.
func DeleteFooBarGo(fbg FooBarGo) {
  fbg.deleteFooBarAbstract()
}
</pre>
</div>
<p> Returned string by the <tt>FooBarGo.FooBar</tt> method is:</p>
<div class="code">
<pre>
Go Foo, Go Bar
</pre>
</div>
<p> For comparison the <tt>FooBarCpp</tt> class looks like this:</p>
<div class="code">
<pre>
class FooBarCpp : public FooBarAbstract
{
protected:
  virtual std::string Foo() {
    return &quot;C++ &quot; + FooBarAbstract::Foo();
  }

  virtual std::string Bar() {
    return &quot;C++ Bar&quot;;
  }
};
</pre>
</div>
<p> For comparison the returned string by the <tt>FooBarCpp::FooBar</tt>
 method is:</p>
<div class="code">
<pre>
C++ Foo, C++ Bar
</pre>
</div>
<p> The complete source of this example can be found under <a href="https://github.com/swig/swig/tree/master/Examples/go/director">
 SWIG/Examples/go/director/</a>.</p>
<h3><a name="Go_primitive_type_mappings">24.4.8 Default Go primitive
 type mappings</a></h3>
<p> The following table lists the default type mapping from C/C++ to Go.
 This table will tell you which Go type to expect for a function which
 uses a given C/C++ type.</p>
<table BORDER summary="Go primitive type mappings">
<tr><td><b>C/C++ type</b></td><td><b>Go type</b></td></tr>
<tr><td>bool</td><td>bool</td></tr>
<tr><td>char</td><td>byte</td></tr>
<tr><td>signed char</td><td>int8</td></tr>
<tr><td>unsigned char</td><td>byte</td></tr>
<tr><td>short</td><td>int16</td></tr>
<tr><td>unsigned short</td><td>uint16</td></tr>
<tr><td>int</td><td>int</td></tr>
<tr><td>unsigned int</td><td>uint</td></tr>
<tr><td>long</td><td>int64</td></tr>
<tr><td>unsigned long</td><td>uint64</td></tr>
<tr><td>long long</td><td>int64</td></tr>
<tr><td>unsigned long long</td><td>uint64</td></tr>
<tr><td>float</td><td>float32</td></tr>
<tr><td>double</td><td>float64</td></tr>
<tr><td>char *
<br>char []</td><td>string</td></tr>
</table>
<p> Note that SWIG wraps the C <tt>char</tt> type as a character.
 Pointers and arrays of this type are wrapped as strings. The <tt>signed
 char</tt> type can be used if you want to treat <tt>char</tt> as a
 signed number rather than a character. Also note that all const
 references to primitive types are treated as if they are passed by
 value.</p>
<p> These type mappings are defined by the &quot;gotype&quot; typemap. You may
 change that typemap, or add new values, to control how C/C++ types are
 mapped into Go types.</p>
<h3><a name="Go_output_arguments">24.4.9 Output arguments</a></h3>
<p>Because of limitations in the way output arguments are processed in
 swig, a function with output arguments will not have multiple return
 values. Instead, you must pass a pointer into the C++ function to tell
 it where to store the output value. In go, you supply a slice in the
 place of the output argument.</p>
<p>For example, suppose you were trying to wrap the modf() function in
 the C math library which splits x into integral and fractional parts
 (and returns the integer part in one of its parameters):</p>
<div class="code">
<pre>
double modf(double x, double *ip);
</pre>
</div>
<p>You could wrap it with SWIG as follows:</p>
<div class="code">
<pre>
%include &lt;typemaps.i&gt;
double modf(double x, double *OUTPUT);
</pre>
</div>
<p>or you can use the <code>%apply</code> directive:</p>
<div class="code">
<pre>
%include &lt;typemaps.i&gt;
%apply double *OUTPUT { double *ip };
double modf(double x, double *ip);
</pre>
</div>
<p>In Go you would use it like this:</p>
<div class="code">
<pre>
ptr := []float64{0.0}
fraction := modulename.Modf(5.0, ptr)
</pre>
</div>
<p>Since this is ugly, you may want to wrap the swig-generated API with
 some <a href="#Go_adding_additional_code">additional functions written
 in go</a> that hide the ugly details.</p>
<p>There are no <code>char&nbsp;*OUTPUT</code> typemaps. However you can
 apply the <code>signed&nbsp;char&nbsp;*</code> typemaps instead:</p>
<div class="code">
<pre>
%include &lt;typemaps.i&gt;
%apply signed char *OUTPUT {char *output};
void f(char *output);
</pre>
</div>
<h3><a name="Go_adding_additional_code">24.4.10 Adding additional go
 code</a></h3>
<p>Often the APIs generated by swig are not very natural in go,
 especially if there are output arguments. You can insert additional go
 wrapping code to add new APIs with <code>%insert(go_wrapper)</code>,
 like this:</p>
<div class="code">
<pre>
%include &lt;typemaps.i&gt;
// Change name of what swig generates to Wrapped_modf.  This function will
// have the following signature in go:
//   func Wrapped_modf(float64, []float64) float64
%rename(wrapped_modf) modf(double x, double *ip);

%apply double *OUTPUT { double *ip };
double modf(double x, double *ip);

%insert(go_wrapper) %{

// The improved go interface to this function, which has two return values,
// in the more natural go idiom:
func Modf(x float64) (fracPart float64, intPart float64) {
  ip := []float64{0.0}
  fracPart = Wrapped_modf(x, ip)
  intPart = ip[0]
  return
}

%}
</pre>
</div>
<p>For classes, since swig generates an interface, you can add
 additional methods by defining another interface that includes the
 swig-generated interface. For example,</p>
<div class="code">
<pre>
%rename(Wrapped_MyClass) MyClass;
%rename(Wrapped_GetAValue) MyClass::GetAValue(int *x);
%apply int *OUTPUT { int *x };

class MyClass {
 public:
  MyClass();
  int AFineMethod(const char *arg); // Swig's wrapping is fine for this one.
  bool GetAValue(int *x);
};

%insert(go_wrapper) %{

type MyClass interface {
  Wrapped_MyClass
  GetAValue() (int, bool)
}

func (arg SwigcptrWrapped_MyClass) GetAValue() (int, bool) {
  ip := []int{0}
  ok := arg.Wrapped_GetAValue(ip)
  return ip[0], ok
}

%}
</pre>
</div>
<p>Of course, if you have to rewrite most of the methods, instead of
 just a few, then you might as well define your own struct that includes
 the swig-wrapped object, instead of adding methods to the
 swig-generated object.</p>
<p>If you need to import other go packages, you can do this with <code>
%go_import</code>. For example,</p>
<div class="code">
<pre>
%go_import(&quot;fmt&quot;, _ &quot;unusedPackage&quot;, rp &quot;renamed/package&quot;)

%insert(go_wrapper) %{

func foo() {
  fmt.Println(&quot;Some string:&quot;, rp.GetString())
}

// Importing the same package twice is permitted,
// Go code will be generated with only the first instance of the import.
%go_import(&quot;fmt&quot;)

%insert(go_wrapper) %{

func bar() {
  fmt.Println(&quot;Hello world!&quot;)
}

%}
</pre>
</div>
<h3><a name="Go_typemaps">24.4.11 Go typemaps</a></h3>
<p> You can use the <tt>%typemap</tt> directive to modify SWIG's default
 wrapping behavior for specific C/C++ types. You need to be familiar
 with the material in the general &quot;<a href="#Typemaps">Typemaps</a>&quot;
 chapter. That chapter explains how to define a typemap. This section
 describes some specific typemaps used for Go.</p>
<p> In general type conversion code may be written either in C/C++ or in
 Go. The choice to make normally depends on where memory should be
 allocated. To allocate memory controlled by the Go garbage collector,
 write Go code. To allocate memory in the C/C++ heap, write C code.</p>
<table BORDER summary="Go Typemaps">
<tr><td><b>Typemap</b></td><td><b>Description</b></td></tr>
<tr><td>gotype</td><td> The Go type to use for a C++ type. This type
 will appear in the generated Go wrapper function. If this is not
 defined SWIG will use a default as <a href="#Go_primitive_type_mappings">
described above</a>.</td></tr>
<tr><td>imtype</td><td> An intermediate Go type used by the &quot;goin&quot;,
 &quot;goout&quot;, &quot;godirectorin&quot;, and &quot;godirectorout&quot; typemaps. If this typemap
 is not defined for a C/C++ type, the gotype typemape will be used. This
 is useful when gotype is best converted to C/C++ using Go code.</td></tr>
<tr><td>goin</td><td> Go code to convert from gotype to imtype when
 calling a C/C++ function. SWIG will then internally convert imtype to a
 C/C++ type and pass it down. If this is not defined, or is the empty
 string, no conversion is done.</td></tr>
<tr><td>in</td><td> C/C++ code to convert the internally generated C/C++
 type, based on imtype, into the C/C++ type that a function call
 expects. If this is not defined the value will simply be cast to the
 desired type.</td></tr>
<tr><td>out</td><td> C/C++ code to convert the C/C++ type that a
 function call returns into the internally generated C/C++ type, based
 on imtype, that will be returned to Go. If this is not defined the
 value will simply be cast to the desired type.</td></tr>
<tr><td>goout</td><td> Go code to convert a value returned from a C/C++
 function from imtype to gotype. If this is not defined, or is the empty
 string, no conversion is done.</td></tr>
<tr><td>argout</td><td> C/C++ code to adjust an argument value when
 returning from a function. This is called after the real C/C++ function
 has run. This uses the internally generated C/C++ type, based on
 imtype. This is only useful for a pointer type of some sort. If this is
 not defined nothing will be done.</td></tr>
<tr><td>goargout</td><td> Go code to adjust an argument value when
 returning from a function. This is called after the real C/C++ function
 has run. The value will be in imtype. This is only useful for a pointer
 type of some sort. If this is not defined, or is the empty string,
 nothing will be done.</td></tr>
<tr><td>directorin</td><td> C/C++ code to convert the C/C++ type used to
 call a director method into the internally generated C/C++ type, based
 on imtype, that will be passed to Go. If this is not defined the value
 will simply be cast to the desired type.</td></tr>
<tr><td>godirectorin</td><td> Go code to convert a value used to call a
 director method from imtype to gotype. If this is not defined, or is
 the empty string, no conversion is done.</td></tr>
<tr><td>godirectorout</td><td> Go code to convert a value returned from
 a director method from gotype to imtype. If this is not defined, or is
 the empty string, no conversion is done.</td></tr>
<tr><td>directorout</td><td> C/C++ code to convert a value returned from
 a director method from the internally generated C/C++ type, based on
 imtype, into the type that the method should return If this is not
 defined the value will simply be cast to the desired type.</td></tr>
</table>
<HR NOSHADE>
<h1><a name="Guile">25 SWIG and Guile</a></h1>

<!-- INDEX -->
<div class="sectiontoc">
<ul>
<li><a href="#Guile_nn1">Supported Guile Versions</a></li>
<li><a href="#Guile_nn2">Meaning of &quot;Module&quot;</a></li>
<li><a href="#Guile_nn3">Old GH Guile API</a></li>
<li><a href="#Guile_nn4">Linkage</a>
<ul>
<li><a href="#Guile_nn5">Simple Linkage</a></li>
<li><a href="#Guile_nn6">Passive Linkage</a></li>
<li><a href="#Guile_nn7">Native Guile Module Linkage</a></li>
<li><a href="#Guile_nn8">Old Auto-Loading Guile Module Linkage</a></li>
<li><a href="#Guile_nn9">Hobbit4D Linkage</a></li>
</ul>
</li>
<li><a href="#Guile_nn10">Underscore Folding</a></li>
<li><a href="#Guile_nn11">Typemaps</a></li>
<li><a href="#Guile_nn12">Representation of pointers as smobs</a>
<ul>
<li><a href="#Guile_nn14">Smobs</a></li>
<li><a href="#Guile_nn15">Garbage Collection</a></li>
</ul>
</li>
<li><a href="#Guile_nn16">Native Guile pointers</a></li>
<li><a href="#Guile_nn17">Exception Handling</a></li>
<li><a href="#Guile_nn18">Procedure documentation</a></li>
<li><a href="#Guile_nn19">Procedures with setters</a></li>
<li><a href="#Guile_nn20">GOOPS Proxy Classes</a>
<ul>
<li><a href="#Guile_nn21">Naming Issues</a></li>
<li><a href="#Guile_nn22">Linking</a></li>
</ul>
</li>
</ul>
</div>
<!-- INDEX -->
<p> This section details guile-specific support in SWIG.</p>
<h2><a name="Guile_nn1">25.1 Supported Guile Versions</a></h2>
<p> SWIG works with Guile versions 1.8.x and 2.0.x. Support for version
 1.6.x has been dropped. The last version of SWIG that still works with
 Guile version 1.6.x is SWIG 2.0.9.</p>
<p> Note that starting with guile 2.0, the guile sources can be compiled
 for improved performance. This is currently not tested with swig so
 your mileage may vary. To be safe set environment variable
 GUILE_AUTO_COMPILE to 0 when using swig generated guile code.</p>
<h2><a name="Guile_nn2">25.2 Meaning of &quot;Module&quot;</a></h2>
<p> There are three different concepts of &quot;module&quot; involved, defined
 separately for SWIG, Guile, and Libtool. To avoid horrible confusion,
 we explicitly prefix the context, e.g., &quot;guile-module&quot;.</p>
<h2><a name="Guile_nn3">25.3 Old GH Guile API</a></h2>
<p>Guile 1.8 and older could be interfaced using two different api's,
 the SCM or the GH API. The GH interface to guile is deprecated. Read
 more about why in the <a href="http://www.gnu.org/software/guile/docs/docs-1.6/guile-ref/GH.html#GH">
Guile manual</a>.</p>
<p>Support for the guile GH wrapper code generation has been dropped
 from SWIG. The last version of SWIG that can still generate guile GH
 wrapper code is 2.0.9. Please use that version if you really need the
 GH wrapper code.</p>
<h2><a name="Guile_nn4">25.4 Linkage</a></h2>
<p> Guile support is complicated by a lack of user community
 cohesiveness, which manifests in multiple shared-library usage
 conventions. A set of policies implementing a usage convention is
 called a<b> linkage</b>.</p>
<h3><a name="Guile_nn5">25.4.1 Simple Linkage</a></h3>
<p> The default linkage is the simplest; nothing special is done. In
 this case the function <code>SWIG_init()</code> is exported. Simple
 linkage can be used in several ways:</p>
<ul>
<li><b>Embedded Guile, no modules.</b> You want to embed a Guile
 interpreter into your program; all bindings made by SWIG shall show up
 in the root module. Then call <code>SWIG_init()</code> in the <code>
inner_main()</code> function. See the &quot;simple&quot; and &quot;matrix&quot; examples
 under <code>Examples/guile</code>.</li>
<li>
<p><b>Dynamic module mix-in.</b> You want to create a Guile module using
 <code>define-module</code>, containing both Scheme code and bindings
 made by SWIG; you want to load the SWIG modules as shared libraries
 into Guile.</p>
<div class="targetlang">
<pre>
(define-module (my module))
(define my-so (dynamic-link &quot;./libexample.so&quot;))
(dynamic-call &quot;SWIG_init&quot; my-so) ; make SWIG bindings
;; Scheme definitions can go here
</pre>
</div>
<p> Newer Guile versions provide a shorthand for <code>dynamic-link</code>
 and <code>dynamic-call</code>:</p>
<div class="targetlang">
<pre>
(load-extension &quot;./libexample.so&quot; &quot;SWIG_init&quot;)
</pre>
</div>
<p> A more portable approach would be to drop the shared library
 extension:</p>
<div class="targetlang">
<pre>
(load-extension &quot;./libexample&quot; &quot;SWIG_init&quot;)
</pre>
</div>
<p> You need to explicitly export those bindings made by SWIG that you
 want to import into other modules:</p>
<div class="targetlang">
<pre>
(export foo bar)
</pre>
</div>
<p> In this example, the procedures <code>foo</code> and <code>bar</code>
 would be exported. Alternatively, you can export all bindings with the
 following module-system hack:</p>
<div class="targetlang">
<pre>
(module-map (lambda (sym var)
              (module-export! (current-module) (list sym)))
            (current-module))
</pre>
</div>
<p>SWIG can also generate this Scheme stub (from <code>define-module</code>
 up to <code>export</code>) semi-automagically if you pass it the
 command-line argument <code>-scmstub</code>. The code will be exported
 in a file called <code><i>module</i>.scm</code> in the directory
 specified by <code>-outdir</code> or the current directory if <code>
-outdir</code> is not specified. Since SWIG doesn't know how to load
 your extension module (with <code>dynamic-link</code> or <code>
load-extension</code>), you need to supply this information by including
 a directive like this in the interface file:</p>
<div class="code">
<pre>
%scheme %{ (load-extension &quot;./libexample.so&quot; &quot;SWIG_init&quot;) %}
</pre>
</div>
<p> (The <code>%scheme</code> directive allows to insert arbitrary
 Scheme code into the generated file <code><var>module.scm</var></code>;
 it is placed between the <code>define-module</code> form and the <code>
export</code> form.)</p>
</li>
</ul>
<p>If you want to include several SWIG modules, you would need to rename
 <code>SWIG_init</code> via a preprocessor define to avoid symbol
 clashes. For this case, however, passive linkage is available.</p>
<h3><a name="Guile_nn6">25.4.2 Passive Linkage</a></h3>
<p>Passive linkage is just like simple linkage, but it generates an
 initialization function whose name is derived from the module and
 package name (see below).</p>
<p>You should use passive linkage rather than simple linkage when you
 are using multiple modules.</p>
<h3><a name="Guile_nn7">25.4.3 Native Guile Module Linkage</a></h3>
<p>SWIG can also generate wrapper code that does all the Guile module
 declarations on its own if you pass it the <code>-Linkage module</code>
 command-line option.</p>
<p>The module name is set with the <code>-package</code> and <code>
-module</code> command-line options. Suppose you want to define a module
 with name <code>(my lib foo)</code>; then you would have to pass the
 options <code>-package<var> my</var>/<var>lib</var> -module<var> foo</var>
</code>. Note that the last part of the name can also be set via the
 SWIG directive <code>%module</code>.</p>
<p>You can use this linkage in several ways:</p>
<ul>
<li><b>Embedded Guile with SWIG modules.</b> You want to embed a Guile
 interpreter into your program; the SWIG bindings shall be put into
 different modules. Simply call the function <code>scm_init_<var>my</var>
_<var>modules</var>_<var>foo</var>_module</code> in the <code>
inner_main()</code> function.</li>
<li><b>Dynamic Guile modules.</b> You want to load the SWIG modules as
 shared libraries into Guile; all bindings are automatically put in
 newly created Guile modules.<div class="targetlang">
<pre>
(define my-so (dynamic-link &quot;./libfoo&quot;))
;; create new module and put bindings there:
(dynamic-call &quot;scm_init_my_modules_foo_module&quot; my-so) 
</pre>
</div> Newer Guile versions have a shorthand procedure for this:<div class="targetlang">
<pre>
(load-extension &quot;./libfoo.so&quot; &quot;scm_init_my_modules_foo_module&quot;)
</pre>
</div></li>
</ul>
<h3><a name="Guile_nn8">25.4.4 Old Auto-Loading Guile Module Linkage</a></h3>
<p>Guile used to support an autoloading facility for object-code
 modules. This support has been marked deprecated in version 1.4.1 and
 is going to disappear sooner or later. SWIG still supports building
 auto-loading modules if you pass it the <code>-Linkage ltdlmod</code>
 command-line option.</p>
<p>Auto-loading worked like this: Suppose a module with name <code>(my
 lib foo)</code> is required and not loaded yet. Guile will then search
 all directories in its search path for a Scheme file <code>
my/modules/foo.scm</code> or a shared library <code><var>my</var>/<var>
modules</var>/lib<var>foo</var>.so</code> (or <code><var>my</var>/<var>
modules</var>/lib<var>foo</var>.la</code>; see the GNU libtool
 documentation). If a shared library is found that contains the symbol <code>
scm_init_<var>my</var>_<var>modules</var>_<var>foo</var>_module</code>,
 the library is loaded, and the function at that symbol is called with
 no arguments in order to initialize the module.</p>
<p>When invoked with the <code>-Linkage ltdlmod</code> command-line
 option, SWIG generates an exported module initialization function with
 an appropriate name.</p>
<h3><a name="Guile_nn9">25.4.5 Hobbit4D Linkage</a></h3>
<p> The only other linkage supported at this time creates shared object
 libraries suitable for use by hobbit's <code>(hobbit4d link)</code>
 guile module. This is called the &quot;hobbit&quot; linkage, and requires also
 using the &quot;-package&quot; command line option to set the part of the module
 name before the last symbol. For example, both command lines:</p>
<div class="shell">
<pre>
swig -guile -package my/lib foo.i
swig -guile -package my/lib -module foo foo.i
</pre>
</div>
<p> would create module <code>(my lib foo)</code> (assuming in the first
 case foo.i declares the module to be &quot;foo&quot;). The installed files are
 my/lib/libfoo.so.X.Y.Z and friends. This scheme is still very
 experimental; the (hobbit4d link) conventions are not well understood.</p>
<h2><a name="Guile_nn10">25.5 Underscore Folding</a></h2>
<p> Underscores are converted to dashes in identifiers. Guile support
 may grow an option to inhibit this folding in the future, but no one
 has complained so far.</p>
<p>You can use the SWIG directives <code>%name</code> and <code>%rename</code>
 to specify the Guile name of the wrapped functions and variables (see
 CHANGES).</p>
<h2><a name="Guile_nn11">25.6 Typemaps</a></h2>
<p> The Guile module handles all types via typemaps. This information is
 read from <code>Lib/guile/typemaps.i</code>. Some non-standard typemap
 substitutions are supported:</p>
<ul>
<li><code>$descriptor</code> expands to a type descriptor for use with
 the <code>SWIG_NewPointerObj()</code> and <code>SWIG_ConvertPtr</code>
 functions.</li>
<li>For pointer types, <code>$*descriptor</code> expands to a descriptor
 for the direct base type (i.e., one pointer is stripped), whereas <code>
$basedescriptor</code> expands to a descriptor for the base type (i.e.,
 all pointers are stripped).</li>
</ul>
<p>A function returning <code>void</code> (more precisely, a function
 whose <code>out</code> typemap returns <code>SCM_UNSPECIFIED</code>) is
 treated as returning no values. In <code>argout</code> typemaps, one
 can use the macro <code>GUILE_APPEND_RESULT</code> in order to append a
 value to the list of function return values.</p>
<p>Multiple values can be passed up to Scheme in one of three ways:</p>
<ul>
<li>
<p><em>Multiple values as lists.</em> By default, if more than one value
 is to be returned, a list of the values is created and returned; to
 switch back to this behavior, use</p>
<div class="code">
<pre>
%values_as_list;</pre>
</div></li>
<li>
<p><em>Multiple values as vectors.</em> By issuing</p>
<div class="code">
<pre>
%values_as_vector;</pre>
</div>
<p> vectors instead of lists will be used.</p>
</li>
<li>
<p><em>Multiple values for multiple-value continuations.</em><strong>
 This is the most elegant way.</strong> By issuing</p>
<div class="code">
<pre>
%multiple_values;</pre>
</div>
<p> multiple values are passed to the multiple-value continuation, as
 created by <code>call-with-values</code> or the convenience macro <code>
receive</code>. The latter is available if you issue <code>(use-modules
 (srfi srfi-8))</code>. Assuming that your <code>divide</code> function
 wants to return two values, a quotient and a remainder, you can write:</p>
<div class="targetlang">
<pre>
(receive (quotient remainder)
    (divide 35 17)
  <var>body</var>...)
</pre>
</div>
<p> In <code><var>body</var></code>, the first result of <code>divide</code>
 will be bound to the variable <code>quotient</code>, and the second
 result to <code>remainder</code>.</p>
</li>
</ul>
<p> See also the &quot;multivalue&quot; example.</p>
<p>Constants are exported as a function that returns the value. The
 %feature(&quot;constasvar&quot;) can be applied to any constant, immutable
 variable, or enum. Instead of exporting the constant as a function that
 must be called, the constant will appear as a scheme variable. See <a href="#Customization_features">
Features and the %feature directive</a> for info on how to apply the
 %feature.</p>
<h2><a name="Guile_nn12">25.7 Representation of pointers as smobs</a></h2>
<p> For pointer types, SWIG uses Guile smobs. SWIG smobs print like
 this: <code>#&lt;swig struct xyzzy * 0x1234affe&gt;</code> Two of them are <code>
equal?</code> if and only if they have the same type and value.</p>
<p> To construct a Scheme object from a C pointer, the wrapper code
 calls the function <code>SWIG_NewPointerObj()</code>, passing a pointer
 to a struct representing the pointer type. The type index to store in
 the upper half of the CAR is read from this struct. To get the pointer
 represented by a smob, the wrapper code calls the function <code>
SWIG_ConvertPtr()</code>, passing a pointer to a struct representing the
 expected pointer type. See also <a href="#Typemaps_runtime_type_checker">
The run-time type checker</a>. If the Scheme object passed was not a
 SWIG smob representing a compatible pointer, a <code>wrong-type-arg</code>
 exception is raised.</p>
<h3><a name="Guile_nn14">25.7.1 Smobs</a></h3>
<p> In earlier versions of SWIG, C pointers were represented as Scheme
 strings containing a hexadecimal rendering of the pointer value and a
 mangled type name. As Guile allows registering user types, so-called
 &quot;smobs&quot; (small objects), a much cleaner representation has been
 implemented now. The details will be discussed in the following.</p>
<p>The whole type system, when it is first initialized, creates two
 smobs named &quot;swig&quot; and &quot;collected_swig&quot;. The swig smob is used for
 non-garbage collected smobs, while the collected_swig smob is used as
 described below. Each smob has the same format, which is a double cell
 created by SCM_NEWSMOB2() The first word of data is the pointer to the
 object and the second word of data is the swig_type_info * structure
 describing this type. If a generated GOOPS module has been loaded,
 smobs will be wrapped by the corresponding GOOPS class.</p>
<h3><a name="Guile_nn15">25.7.2 Garbage Collection</a></h3>
<p>Garbage collection is a feature of Guile since version 1.6. As SWIG
 now requires Guile &gt; 1.8, it is automatically included. Garbage
 collection works like this. Every swig_type_info structure stores in
 its clientdata field a pointer to the destructor for this type. The
 destructor is the generated wrapper around the delete function. So swig
 still exports a wrapper for the destructor, it just does not call
 scm_c_define_gsubr() for the wrapped delete function. So the only way
 to delete an object is from the garbage collector, since the delete
 function is not available to scripts. How swig determines if a type
 should be garbage collected is exactly like described in <a href="#Customization_ownership">
 Object ownership and %newobject</a> in the SWIG manual. All typemaps
 use an $owner var, and the guile module replaces $owner with 0 or 1
 depending on feature:new.</p>
<h2><a name="Guile_nn16">25.8 Native Guile pointers</a></h2>
<p> In addition to SWIG smob pointers, <a href="https://www.gnu.org/software/guile/manual/html_node/Foreign-Pointers.html">
Guile's native pointer type</a> are accepted as arguments to wrapped
 SWIG functions. This can be useful for passing <a href="https://www.gnu.org/software/guile/manual/html_node/Void-Pointers-and-Byte-Access.html#">
pointers to bytevector data</a> to wrapped functions.</p>
<h2><a name="Guile_nn17">25.9 Exception Handling</a></h2>
<p> SWIG code calls <code>scm_error</code> on exception, using the
 following mapping:<div class="code">
<pre>
      MAP(SWIG_MemoryError,     &quot;swig-memory-error&quot;);
      MAP(SWIG_IOError,         &quot;swig-io-error&quot;);
      MAP(SWIG_RuntimeError,    &quot;swig-runtime-error&quot;);
      MAP(SWIG_IndexError,      &quot;swig-index-error&quot;);
      MAP(SWIG_TypeError,       &quot;swig-type-error&quot;);
      MAP(SWIG_DivisionByZero,  &quot;swig-division-by-zero&quot;);
      MAP(SWIG_OverflowError,   &quot;swig-overflow-error&quot;);
      MAP(SWIG_SyntaxError,     &quot;swig-syntax-error&quot;);
      MAP(SWIG_ValueError,      &quot;swig-value-error&quot;);
      MAP(SWIG_SystemError,     &quot;swig-system-error&quot;);
</pre>
</div></p>
<p> The default when not specified here is to use &quot;swig-error&quot;. See
 Lib/exception.i for details.</p>
<h2><a name="Guile_nn18">25.10 Procedure documentation</a></h2>
<p>If invoked with the command-line option <code>-procdoc<var> file</var>
</code>, SWIG creates documentation strings for the generated wrapper
 functions, describing the procedure signature and return value, and
 writes them to<var> file</var>.</p>
<p>SWIG can generate documentation strings in three formats, which are
 selected via the command-line option <code>-procdocformat<var> format</var>
</code>:</p>
<ul>
<li><code>guile-1.4</code> (default): Generates a format suitable for
 Guile 1.4.</li>
<li><code>plain</code>: Generates a format suitable for Guile 1.4.1 and
 later.</li>
<li><code>texinfo</code>: Generates texinfo source, which must be run
 through texinfo in order to get a format suitable for Guile 1.4.1 and
 later.</li>
</ul>
<p>You need to register the generated documentation file with Guile like
 this:<div class="targetlang">
<pre>
(use-modules (ice-9 documentation))
(set! documentation-files 
      (cons &quot;<var>file</var>&quot; documentation-files))
</pre>
</div></p>
<p>Documentation strings can be configured using the Guile-specific
 typemap argument <code>doc</code>. See <code>Lib/guile/typemaps.i</code>
 for details.</p>
<h2><a name="Guile_nn19">25.11 Procedures with setters</a></h2>
<p>For global variables, SWIG creates a single wrapper procedure <code>(<var>
variable</var> :optional value)</code>, which is used for both getting
 and setting the value. For struct members, SWIG creates two wrapper
 procedures <code>(<var>struct</var>-<var>member</var>-get pointer)</code>
 and <code>(<var>struct-member</var>-set pointer value)</code>.</p>
<p>If invoked with the command-line option <code>-emit-setters</code> (<em>
recommended</em>), SWIG will additionally create procedures with
 setters. For global variables, the procedure-with-setter <code><var>
variable</var></code> is created, so you can use <code>(<var>variable</var>
)</code> to get the value and <code>(set! (<var>variable</var>)<var>
 value</var>)</code> to set it. For struct members, the
 procedure-with-setter <code><var>struct</var>-<var>member</var></code>
 is created, so you can use <code>(<var>struct</var>-<var>member</var><var>
 pointer</var>)</code> to get the value and <code>(set! (<var>struct</var>
-<var>member</var><var> pointer</var>)<var> value</var>)</code> to set
 it.</p>
<p>If invoked with the command-line option <code>-only-setters</code>,
 SWIG will<em> only</em> create procedures with setters, i.e., for
 struct members, the procedures <code>(<var>struct</var>-<var>member</var>
-get pointer)</code> and <code>(<var>struct-member</var>-set pointer
 value)</code> are<em> not</em> generated.</p>
<h2><a name="Guile_nn20">25.12 GOOPS Proxy Classes</a></h2>
<p>SWIG can also generate classes and generic functions for use with
 Guile's Object-Oriented Programming System (GOOPS). GOOPS is a
 sophisticated object system in the spirit of the Common Lisp Object
 System (CLOS).</p>
<p>To enable GOOPS support, pass the <code>-proxy</code> argument to
 swig. This will export the GOOPS wrapper definitions into the <code><i>
module</i>.scm</code> file in the directory specified by -outdir or the
 current directory. GOOPS support requires either passive or module
 linkage.</p>
<p>The generated file will contain definitions of GOOPS classes
 mimicking the C++ class hierarchy.</p>
<p>Enabling GOOPS support implies <code>-emit-setters</code>.</p>
<p>If <code>-emit-slot-accessors</code> is also passed as an argument,
 then the generated file will contain accessor methods for all the slots
 in the classes and for global variables. The input class</p>
<div class="code">
<pre>
  class Foo {
    public:
      Foo(int i) : a(i) {}
      int a;
      int getMultBy(int i) { return a * i; }
      Foo getFooMultBy(int i) { return Foo(a * i); }
  }; 
  Foo getFooPlus(int i) { return Foo(a + i); }
</pre>
</div>
<p> will produce (if <code>-emit-slot-accessors</code> is not passed as
 a parameter)</p>
<div class="targetlang">
<pre>
(define-class &lt;Foo&gt; (&lt;swig&gt;)
  (a #:allocation #:swig-virtual 
     #:slot-ref primitive:Foo-a-get 
     #:slot-set! primitive:Foo-a-set)
  #:metaclass &lt;swig-metaclass&gt;
  #:new-function primitive:new-Foo
)
(define-method (getMultBy (swig_smob &lt;Foo&gt;) i)
  (primitive:Foo-getMultBy  (slot-ref swig_smob 'smob) i))
(define-method (getFooMultBy (swig_smob &lt;Foo&gt;) i)
  (make &lt;Foo&gt; #:init-smob (primitive:Foo-getFooMultBy  (slot-ref swig_smob 'smob) i)))

(define-method (getFooPlus i)
  (make &lt;Foo&gt; #:init-smob (primitive:getFooPlus i)))

(export &lt;Foo&gt; getMultBy getFooMultBy getFooPlus )
</pre>
</div>
<p> and will produce (if <code>-emit-slot-accessors</code> is passed as
 a parameter)</p>
<div class="targetlang">
<pre>
(define-class &lt;Foo&gt; (&lt;swig&gt;)
  (a #:allocation #:swig-virtual 
     #:slot-ref primitive:Foo-a-get 
     #:slot-set! primitive:Foo-a-set 
     <b>#:accessor a</b>)
  #:metaclass &lt;swig-metaclass&gt;
  #:new-function primitive:new-Foo
)
(define-method (getMultBy (swig_smob &lt;Foo&gt;) i)
  (primitive:Foo-getMultBy  (slot-ref swig_smob 'smob) i))
(define-method (getFooMultBy (swig_smob &lt;Foo&gt;) i)
  (make &lt;Foo&gt; #:init-smob (primitive:Foo-getFooMultBy  (slot-ref swig_smob 'smob) i)))

(define-method (getFooPlus i)
  (make &lt;Foo&gt; #:init-smob (primitive:getFooPlus i)))

(export &lt;Foo&gt; <b>a</b> getMultBy getFooMultBy getFooPlus )
</pre>
</div>
<p> which can then be used by this code</p>
<div class="targetlang">
<pre>
;; not using getters and setters
(define foo (make &lt;Foo&gt; #:args '(45)))
(slot-ref foo 'a)
(slot-set! foo 'a 3)
(getMultBy foo 4)
(define foo2 (getFooMultBy foo 7))
(slot-ref foo 'a)
(slot-ref (getFooPlus foo 4) 'a)

;; using getters and setters
(define foo (make &lt;Foo&gt; #:args '(45)))
(a foo)
(set! (a foo) 5)
(getMultBy foo 4)
(a (getFooMultBy foo 7))
</pre>
</div>
<p>Notice that constructor arguments are passed as a list after the <code>
#:args</code> keyword. Hopefully in the future the following will be
 valid <code>(make &lt;Foo&gt; #:a 5 #:b 4)</code></p>
<p>Also note that the order the declarations occur in the .i file make a
 difference. For example,</p>
<div class="code">
<pre>
%module test

%{ #include &quot;foo.h&quot; %}

%inline %{
  int someFunc(Foo &amp;a) {
    ...
  }
%}

%include &quot;foo.h&quot;
</pre>
</div>
<p> This is a valid SWIG file it will work as you think it will for
 primitive support, but the generated GOOPS file will be broken. Since
 the <code>someFunc</code> definition is parsed by SWIG before all the
 declarations in foo.h, the generated GOOPS file will contain the
 definition of <code>someFunc()</code> before the definition of &lt;Foo&gt;.
 The generated GOOPS file would look like</p>
<div class="targetlang">
<pre>
;;...

(define-method (someFunc (swig_smob &lt;Foo&gt;))
  (primitive:someFunc (slot-ref swig_smob 'smob)))

;;...

(define-class &lt;Foo&gt; (&lt;swig&gt;)
  ;;...
)

;;...
</pre>
</div>
<p> Notice that &lt;Foo&gt; is used before it is defined. The fix is to just
 put the <code>%import &quot;foo.h&quot;</code> before the <code>%inline</code>
 block.</p>
<h3><a name="Guile_nn21">25.12.1 Naming Issues</a></h3>
<p>As you can see in the example above, there are potential naming
 conflicts. The default exported accessor for the <code>Foo::a</code>
 variable is named <code>a</code>. The name of the wrapper global
 function is <code>getFooPlus</code>. If the <code>-useclassprefix</code>
 option is passed to swig, the name of all accessors and member
 functions will be prepended with the class name. So the accessor will
 be called <code>Foo-a</code> and the member functions will be called <code>
Foo-getMultBy</code>. Also, if the <code>-goopsprefix goops:</code>
 argument is passed to swig, every identifier will be prefixed by <code>
goops:</code></p>
<p>Two guile-modules are created by SWIG. The first module contains the
 primitive definitions of all the wrapped functions and variables, and
 is located either in the _wrap.cxx file (with <code>-Linkage module</code>
) or in the scmstub file (if <code>-Linkage passive -scmstub</code>).
 The name of this guile-module is the swig-module name (given on the
 command line with the -module argument or with the %module directive)
 concatenated with the string &quot;-primitive&quot;. For example, if <code>
%module Test</code> is set in the swig interface file, the name of the
 guile-module in the scmstub or <code>-Linkage module</code> will be <code>
Test-primitive</code>. Also, the scmstub file will be named <code>
Test-primitive.scm</code>. The string &quot;primitive&quot; can be changed by the <code>
-primsuffix</code> swig argument. So the same interface, with the <code>
-primsuffix base</code> will produce a module called <code>Test-base</code>
. The second generated guile-module contains all the GOOPS class
 definitions and is located in a file named<i> module</i>.scm in the
 directory specified with -outdir or the current directory. The name of
 this guile-module is the name of the swig-module (given on the command
 line or with the <code>%module</code> directive). In the previous
 example, the GOOPS definitions will be in a file named Test.scm.</p>
<p>Because of the naming conflicts, you can't in general use both the <code>
-primitive</code> and the GOOPS guile-modules at the same time. To do
 this, you need to rename the exported symbols from one or both
 guile-modules. For example,</p>
<div class="targetlang">
<pre>
(use-modules ((Test-primitive) #:renamer (symbol-prefix-proc 'primitive:)))
(use-modules ((Test) #:renamer (symbol-prefix-proc 'goops:)))
</pre>
</div>
<h3><a name="Guile_nn22">25.12.2 Linking</a></h3>
<p>The guile-modules generated above all need to be linked together.
 GOOPS support requires either passive or module linkage. The exported
 GOOPS guile-module will be the name of the swig-module and should be
 located in a file called<i> Module</i>.scm. This should be installed on
 the autoload path for guile, so that <code>(use-modules (<i>Package
 Module</i>))</code> will load everything needed. Thus, the top of the
 GOOPS guile-module will contain code to load everything needed by the
 interface (the shared library, the scmstub module, etc.). The <code>
%goops</code> directive inserts arbitrary code into the generated GOOPS
 guile-module, and should be used to load the dependent libraries.</p>
<p>This breaks up into three cases</p>
<ul>
<li><b>Passive Linkage without -scmstub</b>: Note that this linkage
 style has the potential for naming conflicts, since the primitive
 exported function and variable names are not wrapped in a guile-module
 and might conflict with names from the GOOPS guile-module (see above).
 Pass the -goopsprefix argument to solve this problem. If the <code>
-exportprimitive</code> option is passed to SWIG the <code>(export ...)</code>
 code that would be exported into the scmstub file is exported at the
 bottom of the generated GOOPS guile-module. The <code>%goops</code>
 directive should contain code to load the shared library.<div class="code">
<pre>
%goops %{ (load-extension &quot;./libfoo.so&quot; &quot;scm_init_my_modules_foo_module&quot;) %}
</pre>
</div>
<p> Produces the following code at the top of the generated GOOPS
 guile-module (with the <code>-package my/modules -module foo</code>
 command line arguments)</p>
<div class="targetlang">
<pre>
(define-module (my modules foo))

;; %goops directive goes here
(load-extension &quot;./libfoo.so&quot; &quot;scm_init_my_modules_foo_module&quot;) 

(use-modules (oop goops) (Swig common))
</pre>
</div></li>
<li>
<p><b>Passive Linkage with -scmstub</b>: Here, the name of the scmstub
 file should be <code>Module-primitive.scm</code> (with<i> primitive</i>
 replaced with whatever is given with the <code>-primsuffix</code>
 argument. The code to load the shared library should be located in the <code>
%scheme</code> directive, which will then be added to the scmstub file.
 SWIG will automatically generate the line <code>(use-modules (<i>
Package</i><i> Module-primitive</i>))</code> into the GOOPS
 guile-module. So if<i> Module-primitive.scm</i> is on the autoload path
 for guile, the <code>%goops</code> directive can be empty. Otherwise,
 the <code>%goops</code> directive should contain whatever code is
 needed to load the<i> Module-primitive.scm</i> file into guile.</p>
<div class="targetlang">
<pre>
%scheme %{ (load-extension &quot;./libfoo.so&quot; &quot;scm_init_my_modules_foo_module&quot;) %}
// only include the following definition if (my modules foo) cannot
// be loaded automatically
%goops %{ 
  (primitive-load &quot;/path/to/foo-primitive.scm&quot;) 
  (primitive-load &quot;/path/to/Swig/common.scm&quot;)
%}
</pre>
</div>
<p> Produces the following code at the top of the generated GOOPS
 guile-module</p>
<div class="targetlang">
<pre>
(define-module (my modules foo))

;; %goops directive goes here (if any)
(primitive-load &quot;/path/to/foo-primitive.scm&quot;)
(primitive-load &quot;/path/to/Swig/common.scm&quot;)

(use-modules (oop goops) (Swig common))
(use-modules ((my modules foo-primitive) :renamer (symbol-prefix-proc
                                                       'primitive:)))

</pre>
</div></li>
<li>
<p><b>Module Linkage</b>: This is very similar to passive linkage with a
 scmstub file. SWIG will also automatically generate the line <code>
(use-modules (<i>Package</i><i> Module-primitive</i>))</code> into the
 GOOPS guile-module. Again the <code>%goops</code> directive should
 contain whatever code is needed to get that module loaded into guile.</p>
<div class="code">
<pre>
%goops %{ (load-extension &quot;./libfoo.so&quot; &quot;scm_init_my_modules_foo_module&quot;) %}
</pre>
</div>
<p> Produces the following code at the top of the generated GOOPS
 guile-module</p>
<div class="targetlang">
<pre>
(define-module (my modules foo))

;; %goops directive goes here (if any)
(load-extension &quot;./libfoo.so&quot; &quot;scm_init_my_modules_foo_module&quot;) 

(use-modules (oop goops) (Swig common))
(use-modules ((my modules foo-primitive) :renamer (symbol-prefix-proc
                                                         'primitive:)))

</pre>
</div></li>
</ul>
<p><b>(Swig common)</b>: The generated GOOPS guile-module also imports
 definitions from the (Swig common) guile-module. This module is
 included with SWIG and should be installed by SWIG into the autoload
 path for guile (based on the configure script and whatever arguments
 are passed). If it is not, then the <code>%goops</code> directive also
 needs to contain code to load the <code>common.scm</code> file into
 guile. Also note that if you are trying to install the generated
 wrappers on a computer without SWIG installed, you will need to include
 the common.swg file along with the install.</p>
<p><b>Multiple Modules</b>: Type dependencies between modules is
 supported. For example, if <code>mod1</code> includes definitions of
 some classes, and <code>mod2</code> includes some classes derived from
 classes in <code>mod1</code>, the generated GOOPS file for <code>mod2</code>
 will declare the correct superclasses. The only problem is that since <code>
mod2</code> uses symbols from <code>mod1</code>, the <code>mod2</code>
 GOOPS file must include a <code>(use-modules (mod2))</code>. Currently,
 SWIG does not automatically export this line; it must be included in
 the <code>%goops</code> directive of <code>mod2</code>. Maybe in the
 future SWIG can detect dependencies and export this line. (how do other
 language modules handle this problem?)</p>
<HR NOSHADE>
<h1><a name="Java">26 SWIG and Java</a></h1>

<!-- INDEX -->
<div class="sectiontoc">
<ul>
<li><a href="#Java_overview">Overview</a></li>
<li><a href="#Java_preliminaries">Preliminaries</a>
<ul>
<li><a href="#Java_running_swig">Running SWIG</a></li>
<li><a href="#Java_commandline">Additional Commandline Options</a></li>
<li><a href="#Java_getting_right_headers">Getting the right header files</a>
</li>
<li><a href="#Java_compiling_dynamic">Compiling a dynamic module</a></li>
<li><a href="#Java_using_module">Using your module</a></li>
<li><a href="#Java_dynamic_linking_problems">Dynamic linking problems</a>
</li>
<li><a href="#Java_compilation_problems_cpp">Compilation problems and
 compiling with C++</a></li>
<li><a href="#Java_building_windows">Building on Windows</a>
<ul>
<li><a href="#Java_visual_studio">Running SWIG from Visual Studio</a></li>
<li><a href="#Java_nmake">Using NMAKE</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#Java_basic_tour">A tour of basic C/C++ wrapping</a>
<ul>
<li><a href="#Java_module_packages_classes">Modules, packages and
 generated Java classes</a></li>
<li><a href="#Java_functions">Functions</a></li>
<li><a href="#Java_global_variables">Global variables</a></li>
<li><a href="#Java_constants">Constants</a></li>
<li><a href="#Java_enumerations">Enumerations</a>
<ul>
<li><a href="#Java_anonymous_enums">Anonymous enums</a></li>
<li><a href="#Java_typesafe_enums">Typesafe enums</a></li>
<li><a href="#Java_proper_enums">Proper Java enums</a></li>
<li><a href="#Java_typeunsafe_enums">Type unsafe enums</a></li>
<li><a href="#Java_simple_enums">Simple enums</a></li>
</ul>
</li>
<li><a href="#Java_pointers">Pointers</a></li>
<li><a href="#Java_structures">Structures</a></li>
<li><a href="#Java_classes">C++ classes</a></li>
<li><a href="#Java_inheritance">C++ inheritance</a></li>
<li><a href="#Java_pointers_refs_arrays">Pointers, references, arrays
 and pass by value</a>
<ul>
<li><a href="#Java_null_pointers">Null pointers</a></li>
</ul>
</li>
<li><a href="#Java_overloaded_functions">C++ overloaded functions</a></li>
<li><a href="#Java_default_arguments">C++ default arguments</a></li>
<li><a href="#Java_namespaces">C++ namespaces</a></li>
<li><a href="#Java_templates">C++ templates</a></li>
<li><a href="#Java_smart_pointers">C++ Smart Pointers</a>
<ul>
<li><a href="#Java_smart_pointers_shared_ptr">The shared_ptr Smart
 Pointer</a></li>
<li><a href="#Java_smart_pointers_generic">Generic Smart Pointers</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#Java_further_details">Further details on the generated
 Java classes</a>
<ul>
<li><a href="#Java_imclass">The intermediary JNI class</a>
<ul>
<li><a href="#Java_imclass_pragmas">The intermediary JNI class pragmas</a>
</li>
</ul>
</li>
<li><a href="#Java_module_class">The Java module class</a>
<ul>
<li><a href="#Java_module_class_pragmas">The Java module class pragmas</a>
</li>
</ul>
</li>
<li><a href="#Java_proxy_classes">Java proxy classes</a>
<ul>
<li><a href="#Java_memory_management">Memory management</a></li>
<li><a href="#Java_inheritance_mirroring">Inheritance</a></li>
<li><a href="#Java_proxy_classes_gc">Proxy classes and garbage
 collection</a></li>
<li><a href="#Java_pgcpp">The premature garbage collection prevention
 parameter for proxy class marshalling</a></li>
<li><a href="#Java_multithread_libraries">Single threaded applications
 and thread safety</a></li>
</ul>
</li>
<li><a href="#Java_type_wrapper_classes">Type wrapper classes</a></li>
<li><a href="#Java_enum_classes">Enum classes</a>
<ul>
<li><a href="#Java_typesafe_enums_classes">Typesafe enum classes</a></li>
<li><a href="#Java_proper_enums_classes">Proper Java enum classes</a></li>
<li><a href="#Java_typeunsafe_enums_classes">Type unsafe enum classes</a>
</li>
</ul>
</li>
<li><a href="#Java_interfaces">Interfaces</a></li>
</ul>
</li>
<li><a href="#Java_directors">Cross language polymorphism using
 directors</a>
<ul>
<li><a href="#Java_enabling_directors">Enabling directors</a></li>
<li><a href="#Java_directors_classes">Director classes</a></li>
<li><a href="#Java_directors_overhead">Overhead and code bloat</a></li>
<li><a href="#Java_directors_example">Simple directors example</a></li>
<li><a href="#Java_directors_threading">Director threading issues</a></li>
<li><a href="#Java_directors_performance">Director performance tuning</a>
</li>
<li><a href="#Java_exceptions_from_directors">Java exceptions from
 directors</a>
<ul>
<li><a href="#Java_customizing_director_exceptions">Customizing director
 exceptions</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#Java_allprotected">Accessing protected members</a></li>
<li><a href="#Java_common_customization">Common customization features</a>
<ul>
<li><a href="#Java_helper_functions">C/C++ helper functions</a></li>
<li><a href="#Java_class_extension">Class extension with %extend</a></li>
<li><a href="#Java_proxycode">Class extension with %proxycode</a></li>
<li><a href="#Java_exception_handling">Exception handling with
 %exception and %javaexception</a></li>
<li><a href="#Java_method_access">Method access with
 %javamethodmodifiers</a></li>
</ul>
</li>
<li><a href="#Java_tips_techniques">Tips and techniques</a>
<ul>
<li><a href="#Java_input_output_parameters">Input and output parameters
 using primitive pointers and references</a></li>
<li><a href="#Java_simple_pointers">Simple pointers</a></li>
<li><a href="#Java_c_arrays">Wrapping C arrays with Java arrays</a></li>
<li><a href="#Java_unbounded_c_arrays">Unbounded C Arrays</a></li>
<li><a href="#Java_binary_char">Binary data vs Strings</a></li>
<li><a href="#Java_heap_allocations">Overriding new and delete to
 allocate from Java heap</a></li>
</ul>
</li>
<li><a href="#Java_typemaps">Java typemaps</a>
<ul>
<li><a href="#Java_default_primitive_type_mappings">Default primitive
 type mappings</a></li>
<li><a href="#Java_default_non_primitive_typemaps">Default typemaps for
 non-primitive types</a></li>
<li><a href="#Java_jvm64">Sixty four bit JVMs</a></li>
<li><a href="#Java_what_is_typemap">What is a typemap?</a></li>
<li><a href="#Java_typemaps_c_to_java_types">Typemaps for mapping C/C++
 types to Java types</a></li>
<li><a href="#Java_typemap_attributes">Java typemap attributes</a></li>
<li><a href="#Java_special_variables">Java special variables</a></li>
<li><a href="#Java_typemaps_for_c_and_cpp">Typemaps for both C and C++
 compilation</a></li>
<li><a href="#Java_code_typemaps">Java code typemaps</a></li>
<li><a href="#Java_directors_typemaps">Director specific typemaps</a></li>
</ul>
</li>
<li><a href="#Java_typemap_examples">Typemap Examples</a>
<ul>
<li><a href="#Java_simpler_enum_classes">Simpler Java enums for enums
 without initializers</a></li>
<li><a href="#Java_exception_typemap">Handling C++ exception
 specifications as Java exceptions</a></li>
<li><a href="#Java_nan_exception_typemap">NaN Exception - exception
 handling for a particular type</a></li>
<li><a href="#Java_converting_java_string_arrays">Converting Java String
 arrays to char **</a></li>
<li><a href="#Java_expanding_java_object">Expanding a Java object to
 multiple arguments</a></li>
<li><a href="#Java_using_typemaps_return_arguments">Using typemaps to
 return arguments</a></li>
<li><a href="#Java_adding_downcasts">Adding Java downcasts to
 polymorphic return types</a></li>
<li><a href="#Java_adding_equals_method">Adding an equals method to the
 Java classes</a></li>
<li><a href="#Java_void_pointers">Void pointers and a common Java base
 class</a></li>
<li><a href="#Java_struct_pointer_pointer">Struct pointer to pointer</a></li>
<li><a href="#Java_memory_management_member_variables">Memory management
 when returning references to member variables</a></li>
<li><a href="#Java_memory_management_objects">Memory management for
 objects passed to the C++ layer</a></li>
<li><a href="#Java_date_marshalling">Date marshalling using the javain
 typemap and associated attributes</a></li>
</ul>
</li>
<li><a href="#Java_directors_faq">Living with Java Directors</a></li>
<li><a href="#Java_odds_ends">Odds and ends</a>
<ul>
<li><a href="#Java_javadoc_comments">JavaDoc comments</a></li>
<li><a href="#Java_functional_interface">Functional interface without
 proxy classes</a></li>
<li><a href="#Java_using_own_jni_functions">Using your own JNI functions</a>
</li>
<li><a href="#Java_performance">Performance concerns and hints</a></li>
<li><a href="#Java_debugging">Debugging</a></li>
</ul>
</li>
<li><a href="#Java_examples">Java Examples</a></li>
</ul>
</div>
<!-- INDEX -->
<p> This chapter describes SWIG's support of Java. It covers most SWIG
 features, but certain low-level details are covered in less depth than
 in earlier chapters.</p>
<h2><a name="Java_overview">26.1 Overview</a></h2>
<p> The 100% Pure Java effort is a commendable concept, however in the
 real world programmers often either need to re-use their existing code
 or in some situations want to take advantage of Java but are forced
 into using some native (C/C++) code. The Java extension to SWIG makes
 it very easy to plumb in existing C/C++ code for access from Java, as
 SWIG writes the Java Native Interface (JNI) code for you. It is
 different to using the 'javah' tool as SWIG will wrap existing C/C++
 code, whereas javah takes 'native' Java function declarations and
 creates C/C++ function prototypes. SWIG wraps C/C++ code using Java
 proxy classes and is very useful if you want to have access to large
 amounts of C/C++ code from Java. If only one or two JNI functions are
 needed then using SWIG may be overkill. SWIG enables a Java program to
 easily call into C/C++ code from Java. Historically, SWIG was not able
 to generate any code to call into Java code from C++. However, SWIG now
 supports full cross language polymorphism and code is generated to call
 up from C++ to Java when wrapping C++ virtual methods via the director
 feature.</p>
<p> Java is one of the few non-scripting language modules in SWIG. As
 SWIG utilizes the type safety that the Java language offers, it takes a
 somewhat different approach to that used for scripting languages. In
 particular runtime type checking and the runtime library are not used
 by Java. This should be borne in mind when reading the rest of the SWIG
 documentation. This chapter on Java is relatively self contained and
 will provide you with nearly everything you need for using SWIG and
 Java. However, the &quot;<a href="#SWIG">SWIG Basics</a>&quot; chapter will be a
 useful read in conjunction with this one.</p>
<p> This chapter starts with a few practicalities on running SWIG and
 compiling the generated code. If you are looking for the minimum amount
 to read, have a look at the sections up to and including the <a href="#Java_basic_tour">
tour of basic C/C++ wrapping</a> section which explains how to call the
 various C/C++ code constructs from Java. Following this section are
 details of the C/C++ code and Java classes that SWIG generates. Due to
 the complexities of C and C++ there are different ways in which C/C++
 code could be wrapped and called from Java. SWIG is a powerful tool and
 the rest of the chapter details how the default code wrapping can be
 tailored. Various customisation tips and techniques using SWIG
 directives are covered. The latter sections cover the advanced
 techniques of using typemaps for complete control of the wrapping
 process.</p>
<h2><a name="Java_preliminaries">26.2 Preliminaries</a></h2>
<p> SWIG 1.1 works with JDKs from JDK 1.1 to JDK1.4 (Java 2 SDK1.4) and
 should also work with any later versions. Given the choice, you should
 probably use the latest version of Sun's JDK. The SWIG Java module is
 known to work using Sun's JVM on Solaris, Linux and the various
 flavours of Microsoft Windows including Cygwin. The Kaffe JVM is known
 to give a few problems and at the time of writing was not a fully
 fledged JVM with full JNI support. The generated code is also known to
 work on vxWorks using WindRiver's PJava 3.1. The best way to determine
 whether your combination of operating system and JDK will work is to
 test the examples and test-suite that comes with SWIG. Run <tt>make -k
 check</tt> from the SWIG root directory after installing SWIG on Unix
 systems.</p>
<p> The Java module requires your system to support shared libraries and
 dynamic loading. This is the commonly used method to load JNI code so
 your system will more than likely support this.</p>
<p> Android uses Java JNI and also works with SWIG. Please read the <a href="#Android">
Android chapter</a> in conjunction with this one if you are targeting
 Android.</p>
<h3><a name="Java_running_swig">26.2.1 Running SWIG</a></h3>
<p> Suppose that you defined a SWIG module such as the following:</p>
<div class="code">
<pre>
/* File: example.i */
%module test
%{
#include &quot;stuff.h&quot;
%}
int fact(int n);
</pre>
</div>
<p> To build a Java module, run SWIG using the <tt>-java</tt> option :</p>
<div class="code">
<pre>
%swig -java example.i
</pre>
</div>
<p> If building C++, add the <tt>-c++</tt> option:</p>
<div class="code">
<pre>
$ swig -c++ -java example.i
</pre>
</div>
<p> This creates two different files; a C/C++ source file <tt>
example_wrap.c</tt> or <tt>example_wrap.cxx</tt> and numerous Java
 files. The generated C/C++ source file contains the JNI wrapper code
 that needs to be compiled and linked with the rest of your C/C++
 application.</p>
<p> The name of the wrapper file is derived from the name of the input
 file. For example, if the input file is <tt>example.i</tt>, the name of
 the wrapper file is <tt>example_wrap.c</tt>. To change this, you can
 use the <tt>-o</tt> option. It is also possible to change the <a href="#SWIG_output">
output directory</a> that the Java files are generated into using <tt>
-outdir</tt>.</p>
<p> The module name, specified with <tt>%module</tt>, determines the
 name of various generated classes as discussed <a href="#Java_module_packages_classes">
later</a>. Note that the module name does not define a Java package and
 by default, the generated Java classes do not have a Java package. The <tt>
-package</tt> option described below can specify a Java package name to
 use.</p>
<p> The following sections have further practical examples and details
 on how you might go about compiling and using the generated files.</p>
<h3><a name="Java_commandline">26.2.2 Additional Commandline Options</a></h3>
<p> The following table lists the additional commandline options
 available for the Java module. They can also be seen by using:</p>
<div class="code">
<pre>
swig -java -help 
</pre>
</div>
<table summary="Java specific options">
<tr><th>Java specific options</th></tr>
<tr><td>-nopgcpp</td><td>suppress the premature garbage collection
 prevention parameter</td></tr>
<tr><td>-noproxy</td><td>generate the low-level functional interface
 instead of proxy classes</td></tr>
<tr><td>-package &lt;name&gt;</td><td>set name of the Java package to &lt;name&gt;</td>
</tr>
</table>
<p> Their use will become clearer by the time you have finished reading
 this section on SWIG and Java.</p>
<h3><a name="Java_getting_right_headers">26.2.3 Getting the right header
 files</a></h3>
<p> In order to compile the C/C++ wrappers, the compiler needs the <tt>
jni.h</tt> and <tt>jni_md.h</tt> header files which are part of the JDK.
 They are usually in directories like this:</p>
<div class="code">
<pre>
/usr/java/include
/usr/java/include/&lt;operating_system&gt;
</pre>
</div>
<p> The exact location may vary on your machine, but the above locations
 are typical.</p>
<h3><a name="Java_compiling_dynamic">26.2.4 Compiling a dynamic module</a>
</h3>
<p> The JNI code exists in a dynamic module or shared library (DLL on
 Windows) and gets loaded by the JVM. Assuming you have code you need to
 link to in a file called <tt>example.c</tt>, in order to build a shared
 library file, you need to compile your module in a manner similar to
 the following (shown for Solaris):</p>
<div class="code">
<pre>
$ swig -java example.i
$ gcc -fPIC -c example_wrap.c -I/usr/java/include -I/usr/java/include/solaris
$ gcc -fPIC -c example.c
$ ld -G example_wrap.o example.o -o libexample.so
</pre>
</div>
<p> The exact commands for doing this vary from platform to platform.
 However, SWIG tries to guess the right options when it is installed.
 Therefore, you may want to start with one of the examples in the <tt>
Examples/java</tt> directory. If that doesn't work, you will need to
 read the man-pages for your compiler and linker to get the right set of
 options. You might also check the <a href="https://github.com/swig/swig/wiki">
SWIG Wiki</a> for additional information.</p>
<p><b> Important</b>
<br> If you are going to use optimisations turned on with gcc (for
 example -O2), ensure you also compile with -fno-strict-aliasing. The
 GCC optimisations have become more aggressive from gcc-4.0 onwards and
 will result in code that fails with strict aliasing optimisations
 turned on. See the <a href="#Java_typemaps_c_to_java_types">C/C++ to
 Java typemaps</a> section for more details.</p>
<p> The name of the shared library output file is important. If the name
 of your SWIG module is &quot;<tt>example</tt>&quot;, the name of the
 corresponding shared library file should be &quot;<tt>libexample.so</tt>&quot;
 (or equivalent depending on your machine, see <a href="#Java_dynamic_linking_problems">
Dynamic linking problems</a> for more information). The name of the
 module is specified using the <tt>%module</tt> directive or <tt>-module</tt>
 command line option.</p>
<h3><a name="Java_using_module">26.2.5 Using your module</a></h3>
<p> To load your shared native library module in Java, simply use Java's
 <tt>System.loadLibrary</tt> method in a Java class:</p>
<div class="code">
<pre>
// runme.java

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

  public static void main(String argv[]) {
    System.out.println(example.fact(4));
  }
}
</pre>
</div>
<p> Compile all the Java files and run:</p>
<div class="code">
<pre>
$ javac *.java
$ java runme
24
$
</pre>
</div>
<p> If it doesn't work have a look at the following section which
 discusses problems loading the shared library.</p>
<h3><a name="Java_dynamic_linking_problems">26.2.6 Dynamic linking
 problems</a></h3>
<p> As shown in the previous section the code to load a native library
 (shared library) is <tt>System.loadLibrary(&quot;name&quot;)</tt>. This can fail
 with an UnsatisfiedLinkError exception and can be due to a number of
 reasons.</p>
<p> You may get an exception similar to this:</p>
<div class="code">
<pre>
$ java runme
Exception in thread &quot;main&quot; java.lang.UnsatisfiedLinkError: no example in java.library.path
        at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1312)
        at java.lang.Runtime.loadLibrary0(Runtime.java:749)
        at java.lang.System.loadLibrary(System.java:820)
        at runme.&lt;clinit&gt;(runme.java:5)
</pre>
</div>
<p> The most common cause for this is an incorrect naming of the native
 library for the name passed to the <tt>loadLibrary</tt> function. The
 string passed to the <tt>loadLibrary</tt> function must not include the
 file extension name in the string, that is<i> .dll</i> or<i> .so</i>.
 The string must be<i> name</i> and not<i> libname</i> for all
 platforms. On Windows the native library must then be called<i>
 name.dll</i> and on most Unix systems it must be called<i> libname.so</i>
.</p>
<p> Another common reason for the native library not loading is because
 it is not in your path. On Windows make sure the<i> path</i>
 environment variable contains the path to the native library. On Unix
 make sure that your<i> LD_LIBRARY_PATH</i> contains the path to the
 native library. Adding paths to<i> LD_LIBRARY_PATH</i> can slow down
 other programs on your system so you may want to consider alternative
 approaches. For example you could recompile your native library with
 extra path information using <tt>-rpath</tt> if you're using GNU, see
 the GNU linker documentation (<tt>ld</tt> man page). You could use a
 command such as <tt>ldconfig</tt> (Linux) or <tt>crle</tt> (Solaris) to
 add additional search paths to the default system configuration (this
 requires root access and you will need to read the man pages).</p>
<p> The native library will also not load if there are any unresolved
 symbols in the compiled C/C++ code. The following exception is
 indicative of this:</p>
<div class="code">
<pre>
$ java runme
Exception in thread &quot;main&quot; java.lang.UnsatisfiedLinkError: libexample.so: undefined
symbol: fact
        at java.lang.ClassLoader$NativeLibrary.load(Native Method)
        at java.lang.ClassLoader.loadLibrary0(ClassLoader.java, Compiled Code)
        at java.lang.ClassLoader.loadLibrary(ClassLoader.java, Compiled Code)
        at java.lang.Runtime.loadLibrary0(Runtime.java, Compiled Code)
        at java.lang.System.loadLibrary(System.java, Compiled Code)
        at runme.&lt;clinit&gt;(runme.java:5)
$
</pre>
</div>
<p> This error usually indicates that you forgot to include some object
 files or libraries in the linking of the native library file. Make sure
 you compile both the SWIG wrapper file and the code you are wrapping
 into the native library file. If you forget to compile and link in the
 SWIG wrapper file into your native library file, you will get a message
 similar to the following:</p>
<div class="code">
<pre>
$ java runme
Exception in thread &quot;main&quot; java.lang.UnsatisfiedLinkError: exampleJNI.gcd(II)I
        at exampleJNI.gcd(Native Method)
        at example.gcd(example.java:12)
        at runme.main(runme.java:18)
</pre>
</div>
<p> where <tt>gcd</tt> is the missing JNI function that SWIG generated
 into the wrapper file. Also make sure you pass all of the required
 libraries to the linker. The <tt>java -verbose:jni</tt> commandline
 option is also a great way to get more information on unresolved
 symbols. One last piece of advice is to beware of the common faux pas
 of having more than one native library version in your path.</p>
<p> In summary, ensure that you are using the correct C/C++ compiler and
 linker combination and options for successful native library loading.
 If you are using the examples that ship with SWIG, then the
 Examples/Makefile must have these set up correctly for your system. The
 SWIG installation package makes a best attempt at getting these correct
 but does not get it right 100% of the time. The <a href="https://github.com/swig/swig/wiki">
SWIG Wiki</a> also has some settings for commonly used compiler and
 operating system combinations. The following section also contains some
 C++ specific linking problems and solutions.</p>
<h3><a name="Java_compilation_problems_cpp">26.2.7 Compilation problems
 and compiling with C++</a></h3>
<p> On most machines, shared library files should be linked using the
 C++ compiler. For example:</p>
<div class="code">
<pre>
% swig -c++ -java example.i
% g++ -c -fpic example.cxx
% g++ -c -fpic example_wrap.cxx -I/usr/java/j2sdk1.4.1/include -I/usr/java/j2sdk1.4.1/include/linux
% g++ -shared example.o example_wrap.o -o libexample.so
</pre>
</div>
<p> In addition to this, you may need to include additional library
 files to make it work. For example, if you are using the Sun C++
 compiler on Solaris, you often need to add an extra library <tt>-lCrun</tt>
 like this:</p>
<div class="code">
<pre>
% swig -c++ -java example.i
% CC -c example.cxx
% CC -c example_wrap.cxx -I/usr/java/include -I/usr/java/include/solaris
% CC -G example.o example_wrap.o -L/opt/SUNWspro/lib -o libexample.so -lCrun
</pre>
</div>
<p> If you aren't entirely sure about the linking for C++, you might
 look at an existing C++ program. On many Unix machines, the <tt>ldd</tt>
 command will list library dependencies. This should give you some clues
 about what you might have to include when you link your shared library.
 For example:</p>
<div class="code">
<pre>
$ ldd swig
        libstdc++-libc6.1-1.so.2 =&gt; /usr/lib/libstdc++-libc6.1-1.so.2 (0x40019000)
        libm.so.6 =&gt; /lib/libm.so.6 (0x4005b000)
        libc.so.6 =&gt; /lib/libc.so.6 (0x40077000)
        /lib/ld-linux.so.2 =&gt; /lib/ld-linux.so.2 (0x40000000)
$
</pre>
</div>
<p> Finally make sure the version of JDK header files matches the
 version of Java that you are running as incompatibilities could lead to
 compilation problems or unpredictable behaviour.</p>
<h3><a name="Java_building_windows">26.2.8 Building on Windows</a></h3>
<p> Building on Windows is roughly similar to the process used with
 Unix. You will want to produce a DLL that can be loaded by the Java
 Virtual Machine. This section covers the process of using SWIG with
 Microsoft Visual C++ 6 although the procedure may be similar with other
 compilers. In order for everything to work, you will need to have a JDK
 installed on your machine in order to read the JNI header files.</p>
<h4><a name="Java_visual_studio">26.2.8.1 Running SWIG from Visual
 Studio</a></h4>
<p> If you are developing your application within Microsoft Visual
 studio, SWIG can be invoked as a custom build option. The Examples\java
 directory has a few <a href="#Windows_examples">Windows Examples</a>
 containing Visual Studio project (.dsp) files. The process to re-create
 the project files for a C project are roughly:</p>
<ul>
<li>Open up a new workspace and use the AppWizard to select a DLL
 project.</li>
<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>
<li>Select the SWIG interface file and go to the settings menu. Under
 settings, select the &quot;Custom Build&quot; option.</li>
<li>Enter &quot;SWIG&quot; in the description field.</li>
<li>Enter &quot;<tt>swig -java -o $(ProjDir)\$(InputName)_wrap.c $(InputPath)</tt>
&quot; in the &quot;Build command(s) field&quot;</li>
<li>Enter &quot;<tt>$(ProjDir)\$(InputName)_wrap.c</tt>&quot; in the &quot;Output
 files(s) field&quot;.</li>
<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 &quot;Additional include directories&quot;, eg
 &quot;C:\jdk1.3\include, C:\jdk1.3\include\win32&quot;.</li>
<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>
<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>
<li>Finally, add the java compilation as a post build rule in the
 Post-build step tab in project settings, eg, &quot;c:\jdk1.3\bin\javac
 *.java&quot;</li>
<li>Build your project.</li>
</ul>
<p> Note: If using C++, choose a C++ suffix for the wrapper file, for
 example <tt>example_wrap.cxx</tt>. Use <tt>_wrap.cxx</tt> instead of <tt>
_wrap.c</tt> in the instructions above and add -c++ when invoking swig.</p>
<p> Now, assuming all went well, SWIG will be automatically invoked when
 you build your project. When doing a build, any changes made to the
 interface file will result in SWIG being automatically invoked to
 produce a new version of the wrapper file.</p>
<p> The Java classes that SWIG output should also be compiled into
 .class files. To run the native code in the DLL (example.dll), make
 sure that it is in your path then run your Java program which uses it,
 as described in the previous section. If the library fails to load have
 a look at <a href="#Java_dynamic_linking_problems">Dynamic linking
 problems</a>.</p>
<h4><a name="Java_nmake">26.2.8.2 Using NMAKE</a></h4>
<p> Alternatively, a Makefile for use by NMAKE can be written. Make sure
 the environment variables for MSVC++ are available and the MSVC++ tools
 are in your path. Now, just write a short Makefile like this :</p>
<div class="code">
<pre>
# Makefile for using SWIG and Java for C code

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

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

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

# C Library needed to build a DLL

DLLIBC        = msvcrt.lib oldnames.lib  

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

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

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

# C compiler flags

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

java::
        swig -java -o $(WRAPFILE) $(INTERFACE)
        $(CC) $(CFLAGS) $(JAVA_INCLUDE) $(SRCS) $(WRAPFILE)
        set LIB=$(TOOLS)\lib
        $(LINK) $(LOPT) -out:example.dll $(LIBS) example.obj example_wrap.obj
        javac *.java
</pre>
</div>
<p> To build the DLL and compile the java code, run NMAKE (you may need
 to run <tt>vcvars32</tt> first). This is a pretty simplistic Makefile,
 but hopefully its enough to get you started. Of course you may want to
 make changes for it to work for C++ by adding in the -c++ command line
 option for swig and replacing .c with .cxx.</p>
<h2><a name="Java_basic_tour">26.3 A tour of basic C/C++ wrapping</a></h2>
<p> By default, SWIG attempts to build a natural Java interface to your
 C/C++ code. Functions are wrapped as functions, classes are wrapped as
 classes, variables are wrapped with JavaBean type getters and setters
 and so forth. This section briefly covers the essential aspects of this
 wrapping.</p>
<h3><a name="Java_module_packages_classes">26.3.1 Modules, packages and
 generated Java classes</a></h3>
<p> The SWIG <tt>%module</tt> directive specifies the name of the Java
 module. When you specify `<tt>%module example</tt>', the<i> module name</i>
 determines the name of some of the generated files in the module. The
 generated code consists of a<i> module class</i> file <tt>example.java</tt>
, an<i> intermediary JNI class</i> file, <tt>exampleJNI.java</tt> as
 well as numerous other Java<i> proxy class</i> files. Each proxy class
 is named after the structs, unions and classes you are wrapping. You
 may also get a<i> constants interface</i> file if you are wrapping any
 unnamed enumerations or constants, for example <tt>
exampleConstants.java</tt>. When choosing a module name, make sure you
 don't use the same name as one of the generated proxy class files nor a
 Java keyword. Sometimes a C/C++ type cannot be wrapped by a proxy
 class, for example a pointer to a primitive type. In these situations a<i>
 type wrapper class</i> is generated. Wrapping an enum generates an<i>
 enum class</i>, either a proper Java enum or a Java class that
 simulates the enums pattern. Details of all these generated classes
 will unfold as you read this section.</p>
<p> The JNI (C/C++) code is generated into a file which also contains
 the module name, for example <tt>example_wrap.cxx</tt> or <tt>
example_wrap.c</tt>. These C or C++ files complete the contents of the
 module.</p>
<p> The generated Java classes can be placed into a Java package by
 using the <tt>-package</tt> commandline option. This is often combined
 with the <tt>-outdir</tt> to specify a package directory for generating
 the Java files.</p>
<div class="code">
<pre>
swig -java -package com.bloggs.swig -outdir com/bloggs/swig example.i
</pre>
</div>
<p> SWIG won't create the directory, so make sure it exists beforehand.</p>
<h3><a name="Java_functions">26.3.2 Functions</a></h3>
<p> There is no such thing as a global Java function so global C
 functions are wrapped as static methods in the module class. For
 example,</p>
<div class="code">
<pre>
%module example
int fact(int n);

</pre>
</div>
<p> creates a static function that works exactly like you think it
 might:</p>
<div class="code">
<pre>
public class example {
  public static int fact(int n) {
    // makes call using JNI to the C function
  }
}
</pre>
</div>
<p> The Java class <tt>example</tt> is the<i> module class</i>. The
 function can be used as follows from Java:</p>
<div class="code">
<pre>
System.out.println(example.fact(4));
</pre>
</div>
<h3><a name="Java_global_variables">26.3.3 Global variables</a></h3>
<p> C/C++ global variables are fully supported by SWIG. Java does not
 allow the overriding of the dot operator so all variables are accessed
 through getters and setters. Again because there is no such thing as a
 Java global variable, access to C/C++ global variables is done through
 static getter and setter functions in the module class.</p>
<div class="code">
<pre>
// SWIG interface file with global variables
%module example
...
%inline %{
extern int My_variable;
extern double density;
%}
...
</pre>
</div>
<p> Now in Java :</p>
<div class="code">
<pre>
// Print out value of a C global variable
System.out.println(&quot;My_variable = &quot; + example.getMy_variable());
// Set the value of a C global variable
example.setDensity(0.8442);
</pre>
</div>
<p> The value returned by the getter will always be up to date even if
 the value is changed in C. Note that the getters and setters produced
 follow the JavaBean property design pattern. That is the first letter
 of the variable name is capitalized and preceded with set or get. If
 you have the misfortune of wrapping two variables that differ only in
 the capitalization of their first letters, use %rename to change one of
 the variable names. For example:</p>
<div class="code">
<pre>
%rename Clash RenamedClash;
float Clash;
int clash;
</pre>
</div>
<p> If a variable is declared as <tt>const</tt>, it is wrapped as a
 read-only variable. That is only a getter is produced.</p>
<p> To make ordinary variables read-only, you can use the <tt>%immutable</tt>
 directive. For example:</p>
<div class="code">
<pre>
%{
extern char *path;
%}
%immutable;
extern char *path;
%mutable;
</pre>
</div>
<p> The <tt>%immutable</tt> directive stays in effect until it is
 explicitly disabled or cleared using <tt>%mutable</tt>. See the <a href="#SWIG_readonly_variables">
Creating read-only variables</a> section for further details.</p>
<p> If you just want to make a specific variable immutable, supply a
 declaration name. For example:</p>
<div class="code">
<pre>
%{
extern char *path;
%}
%immutable path;
...
extern char *path;      // Read-only (due to %immutable)
</pre>
</div>
<h3><a name="Java_constants">26.3.4 Constants</a></h3>
<p> C/C++ constants are wrapped as Java static final variables. To
 create a constant, use <tt>#define</tt> or the <tt>%constant</tt>
 directive. For example:</p>
<div class="code">
<pre>
#define PI 3.14159
#define VERSION &quot;1.0&quot;
%constant int FOO = 42;
%constant const char *path = &quot;/usr/local&quot;;
</pre>
</div>
<p> By default the generated static final variables are initialized by
 making a JNI call to get their value. The constants are generated into
 the constants interface and look like this:</p>
<div class="code">
<pre>
public interface exampleConstants {
  public final static double PI = exampleJNI.PI_get();
  public final static String VERSION = exampleJNI.VERSION_get();
  public final static int FOO = exampleJNI.FOO_get();
  public final static String path = exampleJNI.path_get();
}
</pre>
</div>
<p> Note that SWIG has inferred the C type and used an appropriate Java
 type that will fit the range of all possible values for the C type. By
 default SWIG generates<b> runtime constants</b>. They are not<b>
 compiler constants</b> that can, for example, be used in a switch
 statement. This can be changed by using the <tt>%javaconst(flag)</tt>
 directive. It works like all the other <a href="#Customization_features">
%feature directives</a>. The default is <tt>%javaconst(0)</tt>. It is
 possible to initialize all wrapped constants from pure Java code by
 placing a <tt>%javaconst(1)</tt><b> before</b> SWIG parses the
 constants. Putting it at the top of your interface file would ensure
 this. Here is an example:</p>
<div class="code">
<pre>
%javaconst(1);
%javaconst(0) BIG;
%javaconst(0) LARGE;

#define EXPRESSION (0x100+5)
#define BIG 1000LL
#define LARGE 2000ULL
</pre>
</div>
<p> generates:</p>
<div class="code">
<pre>
public interface exampleConstants {
  public final static int EXPRESSION = (0x100+5);
  public final static long BIG = exampleJNI.BIG_get();
  public final static java.math.BigInteger LARGE = exampleJNI.LARGE_get();
}
</pre>
</div>
<p> Note that SWIG has inferred the C <tt>long long</tt> type from <tt>
BIG</tt> and used an appropriate Java type (<tt>long</tt>) as a Java <tt>
long</tt> is the smallest sized Java type that will take all possible
 values for a C <tt>long long</tt>. Similarly for <tt>LARGE</tt>.</p>
<p> Be careful using the <tt>%javaconst(1)</tt> directive as not all C
 code will compile as Java code. For example neither the <tt>1000LL</tt>
 value for <tt>BIG</tt> nor <tt>2000ULL</tt> for <tt>LARGE</tt> above
 would generate valid Java code. The example demonstrates how you can
 target particular constants (<tt>BIG</tt> and <tt>LARGE</tt>) with <tt>
%javaconst</tt>. SWIG doesn't use <tt>%javaconst(1)</tt> as the default
 as it tries to generate code that will always compile. However, using a
 <tt>%javaconst(1)</tt> at the top of your interface file is strongly
 recommended as the preferred compile time constants will be generated
 and most C constants will compile as Java code and in any case the odd
 constant that doesn't can be fixed using <tt>%javaconst(0)</tt>.</p>
<p> There is an alternative directive which can be used for these rare
 constant values that won't compile as Java code. This is the <tt>
%javaconstvalue(value)</tt> directive, where <tt>value</tt> is a Java
 code replacement for the C constant and can be either a string or a
 number. This is useful if you do not want to use either the parsed C
 value nor a JNI call, such as when the C parsed value will not compile
 as Java code and a compile time constant is required. The same example
 demonstrates this:</p>
<div class="code">
<pre>
%javaconst(1);
%javaconstvalue(&quot;new java.math.BigInteger(\&quot;2000\&quot;)&quot;) LARGE;
%javaconstvalue(1000) BIG;

#define EXPRESSION (0x100+5)
#define BIG 1000LL
#define LARGE 2000ULL
</pre>
</div>
<p> Note the string quotes for <tt>&quot;2000&quot;</tt> are escaped. The
 following is then generated:</p>
<div class="code">
<pre>
public interface exampleConstants {
  public final static int EXPRESSION = (0x100+5);
  public final static long BIG = 1000;
  public final static java.math.BigInteger LARGE = new java.math.BigInteger(&quot;2000&quot;);
}
</pre>
</div>
<p> Note: declarations declared as <tt>const</tt> are wrapped as
 read-only variables and will be accessed using a getter as described in
 the previous section. They are not wrapped as constants. The exception
 to this rule are static const integral values defined within a
 class/struct, where they are wrapped as constants, eg:.</p>
<div class="code">
<pre>
struct Maths {
  static const int FIVE = 5;
};
</pre>
</div>
<p><b> Compatibility Note:</b> In SWIG-1.3.19 and earlier releases, the
 constants were generated into the module class and the constants
 interface didn't exist. Backwards compatibility is maintained as the
 module class implements the constants interface (even though some
 consider this type of interface implementation to be bad practice):</p>
<div class="code">
<pre>
public class example implements exampleConstants {
}
</pre>
</div>
<p> You thus have the choice of accessing these constants from either
 the module class or the constants interface, for example, <tt>
example.EXPRESSION</tt> or <tt>exampleConstants.EXPRESSION</tt>. Or if
 you decide this practice isn't so bad and your own class implements <tt>
exampleConstants</tt>, you can of course just use <tt>EXPRESSION</tt>.</p>
<h3><a name="Java_enumerations">26.3.5 Enumerations</a></h3>
<p> SWIG handles both named and unnamed (anonymous) enumerations. There
 is a choice of approaches to wrapping named C/C++ enums. This is due to
 historical reasons as SWIG's initial support for enums was limited and
 Java did not originally have support for enums. Each approach has
 advantages and disadvantages and it is important for the user to decide
 which is the most appropriate solution. There are four approaches of
 which the first is the default approach based on the so called Java
 typesafe enum pattern. The second generates proper Java enums. The
 final two approaches use simple integers for each enum item. Before
 looking at the various approaches for wrapping named C/C++ enums,
 anonymous enums are considered.</p>
<h4><a name="Java_anonymous_enums">26.3.5.1 Anonymous enums</a></h4>
<p> There is no name for anonymous enums and so they are handled like
 constants. For example:</p>
<div class="code">
<pre>
enum { ALE, LAGER=10, STOUT, PILSNER, PILZ=PILSNER };
</pre>
</div>
<p> is wrapped into the constants interface, in a similar manner as
 constants (see previous section):</p>
<div class="code">
<pre>
public interface exampleConstants {
  public final static int ALE = exampleJNI.ALE_get();
  public final static int LAGER = exampleJNI.LAGER_get();
  public final static int STOUT = exampleJNI.STOUT_get();
  public final static int PILSNER = exampleJNI.PILSNER_get();
  public final static int PILZ = exampleJNI.PILZ_get();
}
</pre>
</div>
<p> The <tt>%javaconst(flag)</tt> and <tt>%javaconstvalue(value)</tt>
 directive introduced in the previous section on constants can also be
 used with enums. As is the case for constants, the default is <tt>
%javaconst(0)</tt> as not all C values will compile as Java code.
 However, it is strongly recommended to add in a <tt>%javaconst(1)</tt>
 directive at the top of your interface file as it is only on very rare
 occasions that this will produce code that won't compile under Java.
 Using <tt>%javaconst(1)</tt> will ensure compile time constants are
 generated, thereby allowing the enum values to be used in Java switch
 statements. Example usage:</p>
<div class="code">
<pre>
%javaconst(1);
%javaconst(0) PILSNER;
enum { ALE, LAGER=10, STOUT, PILSNER, PILZ=PILSNER };
</pre>
</div>
<p> generates:</p>
<div class="code">
<pre>
public interface exampleConstants {
  public final static int ALE = 0;
  public final static int LAGER = 10;
  public final static int STOUT = LAGER + 1;
  public final static int PILSNER = exampleJNI.PILSNER_get();
  public final static int PILZ = PILSNER;
}
</pre>
</div>
<p> As in the case of constants, you can access them through either the
 module class or the constants interface, for example, <tt>example.ALE</tt>
 or <tt>exampleConstants.ALE</tt>.</p>
<h4><a name="Java_typesafe_enums">26.3.5.2 Typesafe enums</a></h4>
<p> This is the default approach to wrapping named enums. The typesafe
 enum pattern is a relatively well known construct to work around the
 lack of enums in versions of Java prior to JDK 1.5. It basically
 defines a class for the enumeration and permits a limited number of
 final static instances of the class. Each instance equates to an enum
 item within the enumeration. The implementation is in the
 &quot;enumtypesafe.swg&quot; file. Let's look at an example:</p>
<div class="code">
<pre>
%include &quot;enumtypesafe.swg&quot; // optional as typesafe enums are the default
enum Beverage { ALE, LAGER=10, STOUT, PILSNER, PILZ=PILSNER };
</pre>
</div>
<p>will generate:</p>
<div class="code">
<pre>
public final class Beverage {
  public final static Beverage ALE = new Beverage(&quot;ALE&quot;);
  public final static Beverage LAGER = new Beverage(&quot;LAGER&quot;, exampleJNI.LAGER_get());
  public final static Beverage STOUT = new Beverage(&quot;STOUT&quot;);
  public final static Beverage PILSNER = new Beverage(&quot;PILSNER&quot;);
  public final static Beverage PILZ = new Beverage(&quot;PILZ&quot;, exampleJNI.PILZ_get());
  [... additional support methods omitted for brevity ...]
}
</pre>
</div>
<p> See <a href="#Java_typesafe_enums_classes">Typesafe enum classes</a>
 to see the omitted support methods. Note that the enum item with an
 initializer (LAGER) is initialized with the enum value obtained via a
 JNI call. However, as with anonymous enums and constants, use of the <tt>
%javaconst</tt> directive is strongly recommended to change this
 behaviour:</p>
<div class="code">
<pre>
%include &quot;enumtypesafe.swg&quot; // optional as typesafe enums are the default
%javaconst(1);
enum Beverage { ALE, LAGER=10, STOUT, PILSNER, PILZ=PILSNER };
</pre>
</div>
<p> will generate:</p>
<div class="code">
<pre>
public final class Beverage {
  public final static Beverage ALE = new Beverage(&quot;ALE&quot;);
  public final static Beverage LAGER = new Beverage(&quot;LAGER&quot;, 10);
  public final static Beverage STOUT = new Beverage(&quot;STOUT&quot;);
  public final static Beverage PILSNER = new Beverage(&quot;PILSNER&quot;);
  public final static Beverage PILZ = new Beverage(&quot;PILZ&quot;, PILSNER);
  [... additional support methods omitted for brevity ...]
}
</pre>
</div>
<p> The generated code is easier to read and more efficient as a true
 constant is used instead of a JNI call. As is the case for constants,
 the default is <tt>%javaconst(0)</tt> as not all C values will compile
 as Java code. However, it is recommended to add in a <tt>%javaconst(1)</tt>
 directive at the top of your interface file as it is only on very rare
 occasions that this will produce code that won't compile under Java.
 The <tt>%javaconstvalue(value)</tt> directive can also be used for
 typesafe enums. Note that global enums are generated into a Java class
 within whatever package you are using. C++ enums defined within a C++
 class are generated into a static final inner Java class within the
 Java proxy class.</p>
<p> Typesafe enums have their advantages over using plain integers in
 that they can be used in a typesafe manner. However, there are
 limitations. For example, they cannot be used in switch statements and
 serialization is an issue. Please look at the following references for
 further information: <a href="http://java.sun.com/developer/Books/shiftintojava/page1.html#replaceenums">
Replace Enums with Classes</a> in<i> Effective Java Programming</i> on
 the Sun website, <a href="https://www.javaworld.com/article/2076970/create-enumerated-constants-in-java.html">
Create enumerated constants in Java</a> JavaWorld article, <a href="https://www.javaworld.com/article/2077499/java-tip-133--more-on-typesafe-enums.html">
Java Tip 133: More on typesafe enums</a> and <a href="https://www.javaworld.com/article/2077487/java-tip-122--beware-of-java-typesafe-enumerations.html">
Java Tip 122: Beware of Java typesafe enumerations</a> JavaWorld tips.</p>
<p> Note that the syntax required for using typesafe enums is the same
 as that for proper Java enums. This is useful during the period that a
 project has to support legacy versions of Java. When upgrading to JDK
 1.5 or later, proper Java enums could be used instead, without users
 having to change their code. The following section details proper Java
 enum generation.</p>
<h4><a name="Java_proper_enums">26.3.5.3 Proper Java enums</a></h4>
<p> Proper Java enums were only introduced in JDK 1.5 so this approach
 is only compatible with more recent versions of Java. Java enums have
 been designed to overcome all the limitations of both typesafe and type
 unsafe enums and should be the choice solution, provided older versions
 of Java do not have to be supported. In this approach, each named C/C++
 enum is wrapped by a Java enum. Java enums, by default, do not support
 enums with initializers. Java enums are in many respects similar to
 Java classes in that they can be customised with additional methods.
 SWIG takes advantage of this feature to facilitate wrapping C/C++ enums
 that have initializers. In order to wrap all possible C/C++ enums using
 proper Java enums, the &quot;enums.swg&quot; file must be used. Let's take a look
 at an example.</p>
<div class="code">
<pre>
%include &quot;enums.swg&quot;
%javaconst(1);
enum Beverage { ALE, LAGER=10, STOUT, PILSNER, PILZ=PILSNER };
</pre>
</div>
<p> will generate:</p>
<div class="code">
<pre>
public enum Beverage {
  ALE,
  LAGER(10),
  STOUT,
  PILSNER,
  PILZ(PILSNER);
  [... additional support methods omitted for brevity ...]
}
</pre>
</div>
<p> See <a href="#Java_proper_enums_classes">Proper Java enum classes</a>
 to see the omitted support methods. The generated Java enum has
 numerous additional methods to support enums with initializers, such as
 <tt>LAGER</tt> above. Note that as with the typesafe enum pattern, enum
 items with initializers are by default initialized with the enum value
 obtained via a JNI call. However, this is not the case above as we have
 used the recommended <tt>%javaconst(1)</tt> to avoid the JNI call. The <tt>
%javaconstvalue(value)</tt> directive covered in the <a href="#Java_constants">
Constants</a> section can also be used for proper Java enums.</p>
<p> The additional support methods need not be generated if none of the
 enum items have initializers and this is covered later in the <a href="#Java_simpler_enum_classes">
Simpler Java enums for enums without initializers</a> section.</p>
<h4><a name="Java_typeunsafe_enums">26.3.5.4 Type unsafe enums</a></h4>
<p> In this approach each enum item in a named enumeration is wrapped as
 a static final integer in a class named after the C/C++ enum name. This
 is a commonly used pattern in Java to simulate C/C++ enums, but it is
 not typesafe. However, the main advantage over the typesafe enum
 pattern is enum items can be used in switch statements. In order to use
 this approach, the &quot;enumtypeunsafe.swg&quot; file must be used. Let's take a
 look at an example.</p>
<div class="code">
<pre>
%include &quot;enumtypeunsafe.swg&quot;
%javaconst(1);
enum Beverage { ALE, LAGER=10, STOUT, PILSNER, PILZ=PILSNER };
</pre>
</div>
<p> will generate:</p>
<div class="code">
<pre>
public final class Beverage {
  public final static int ALE = 0;
  public final static int LAGER = 10;
  public final static int STOUT = LAGER + 1;
  public final static int PILSNER = STOUT + 1;
  public final static int PILZ = PILSNER;
}
</pre>
</div>
<p> As is the case previously, the default is <tt>%javaconst(0)</tt> as
 not all C/C++ values will compile as Java code. However, again it is
 recommended to add in a <tt>%javaconst(1)</tt> directive. and the <tt>
%javaconstvalue(value)</tt> directive covered in the <a href="#Java_constants">
Constants</a> section can also be used for type unsafe enums. Note that
 global enums are generated into a Java class within whatever package
 you are using. C++ enums defined within a C++ class are generated into
 a static final inner Java class within the Java proxy class.</p>
<p> Note that unlike typesafe enums, this approach requires users to
 mostly use different syntax compared with proper Java enums. Thus the
 upgrade path to proper enums provided in JDK 1.5 is more painful.</p>
<h4><a name="Java_simple_enums">26.3.5.5 Simple enums</a></h4>
<p> This approach is similar to the type unsafe approach. Each enum item
 is also wrapped as a static final integer. However, these integers are
 not generated into a class named after the C/C++ enum. Instead, global
 enums are generated into the constants interface. Also, enums defined
 in a C++ class have their enum items generated directly into the Java
 proxy class rather than an inner class within the Java proxy class. In
 fact, this approach is effectively wrapping the enums as if they were
 anonymous enums and the resulting code is as per <a href="#Java_anonymous_enums">
anonymous enums</a>. The implementation is in the &quot;enumsimple.swg&quot; file.</p>
<p><b> Compatibility Note:</b> SWIG-1.3.21 and earlier versions wrapped
 all enums using this approach. The type unsafe approach is preferable
 to this one and this simple approach is only included for backwards
 compatibility with these earlier versions of SWIG.</p>
<h3><a name="Java_pointers">26.3.6 Pointers</a></h3>
<p> C/C++ pointers are fully supported by SWIG. Furthermore, SWIG has no
 problem working with incomplete type information. Here is a rather
 simple interface:</p>
<div class="code">
<pre>
%module example

FILE *fopen(const char *filename, const char *mode);
int fputs(const char *, FILE *);
int fclose(FILE *);
</pre>
</div>
<p> When wrapped, you will be able to use the functions in a natural way
 from Java. For example:</p>
<div class="code">
<pre>
SWIGTYPE_p_FILE f = example.fopen(&quot;junk&quot;, &quot;w&quot;);
example.fputs(&quot;Hello World\n&quot;, f);
example.fclose(f);
</pre>
</div>
<p> C pointers in the Java module are stored in a Java <tt>long</tt> and
 cross the JNI boundary held within this 64 bit number. Many other SWIG
 language modules use an encoding of the pointer in a string. These
 scripting languages use the SWIG runtime type checker for dynamic type
 checking as they do not support static type checking by a compiler. In
 order to implement static type checking of pointers within Java, they
 are wrapped by a simple Java class. In the example above the <tt>FILE *</tt>
 pointer is wrapped with a<i> type wrapper class</i> called <tt>
SWIGTYPE_p_FILE</tt>.</p>
<p> Once obtained, a type wrapper object can be freely passed around to
 different C functions that expect to receive an object of that type.
 The only thing you can't do is dereference the pointer from Java. Of
 course, that isn't much of a concern in this example.</p>
<p> As much as you might be inclined to modify a pointer value directly
 from Java, don't. The value is not necessarily the same as the logical
 memory address of the underlying object. The value will vary depending
 on the native byte-ordering of the platform (i.e., big-endian vs.
 little-endian). Most JVMs are 32 bit applications so any JNI code must
 also be compiled as 32 bit. The net result is pointers in JNI code are
 also 32 bits and are stored in the high order 4 bytes on big-endian
 machines and in the low order 4 bytes on little-endian machines. By
 design it is also not possible to manually cast a pointer to a new type
 by using Java casts as it is particularly dangerous especially when
 casting C++ objects. If you need to cast a pointer or change its value,
 consider writing some helper functions instead. For example:</p>
<div class="code">
<pre>
%inline %{
/* C-style cast */
Bar *FooToBar(Foo *f) {
  return (Bar *) f;
}

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

Foo *IncrFoo(Foo *f, int i) {
  return f+i;
}
%}
</pre>
</div>
<p> Also, if working with C++, you should always try to use the new C++
 style casts. For example, in the above code, the C-style cast may
 return a bogus result whereas as the C++-style cast will return a NULL
 pointer if the conversion can't be performed.</p>
<h3><a name="Java_structures">26.3.7 Structures</a></h3>
<p> If you wrap a C structure, it is wrapped by a Java class with
 getters and setters for access to the member variables. For example,</p>
<div class="code">
<pre>
struct Vector {
  double x, y, z;
};

</pre>
</div>
<p> is used as follows:</p>
<div class="code">
<pre>
Vector v = new Vector();
v.setX(3.5);
v.setY(7.2);
double x = v.getX();
double y = v.getY();
</pre>
</div>
<p> The variable setters and getters are also based on the JavaBean
 design pattern already covered under the Global variables section.
 Similar access is provided for unions and the public data members of
 C++ classes.</p>
<p> This object is actually an instance of a Java class that has been
 wrapped around a pointer to the C structure. This instance doesn't
 actually do anything--it just serves as a proxy. The pointer to the C
 object is held in the Java proxy class in much the same way as pointers
 are held by type wrapper classes. Further details about Java proxy
 classes are covered a little later.</p>
<p> <tt>const</tt> members of a structure are read-only. Data members
 can also be forced to be read-only using the <tt>%immutable</tt>
 directive. For example:</p>
<div class="code">
<pre>
struct Foo {
  ...
  %immutable;
  int x;        /* Read-only members */
  char *name;
  %mutable;
  ...
};
</pre>
</div>
<p> When <tt>char *</tt> members of a structure are wrapped, the
 contents are assumed to be dynamically allocated using <tt>malloc</tt>
 or <tt>new</tt> (depending on whether or not SWIG is run with the -c++
 option). When the structure member is set, the old contents will be
 released and a new value created. If this is not the behavior you want,
 you will have to use a typemap (described later).</p>
<p> If a structure contains arrays, access to those arrays is managed
 through pointers. For example, consider this:</p>
<div class="code">
<pre>
struct Bar {
  int  x[16];
};
</pre>
</div>
<p> If accessed in Java, you will see behavior like this:</p>
<div class="code">
<pre>
Bar b = new Bar();
SWIGTYPE_p_int x = b.getX();
</pre>
</div>
<p> This pointer can be passed around to functions that expect to
 receive an <tt>int *</tt> (just like C). You can also set the value of
 an array member using another pointer. For example:</p>
<div class="code">
<pre>
Bar b = new Bar();
SWIGTYPE_p_int x = b.getX();
Bar c = new Bar();
c.setX(x);                    // Copy contents of b.x to c.x
</pre>
</div>
<p> For array assignment (setters not getters), SWIG copies the entire
 contents of the array starting with the data pointed to by <tt>b.x</tt>
. In this example, 16 integers would be copied. Like C, SWIG makes no
 assumptions about bounds checking---if you pass a bad pointer, you may
 get a segmentation fault or access violation. The default wrapping
 makes it hard to set or get just one element of the array and so array
 access from Java is somewhat limited. This can be changed easily though
 by using the approach outlined later in the <a href="#Java_c_arrays">
Wrapping C arrays with Java arrays</a> and <a href="#Java_unbounded_c_arrays">
Unbounded C Arrays</a> sections.</p>
<p> When a member of a structure is itself a structure, it is handled as
 a pointer. For example, suppose you have two structures like this:</p>
<div class="code">
<pre>
struct Foo {
  int a;
};

struct Bar {
  Foo f;
};
</pre>
</div>
<p> Now, suppose that you access the <tt>f</tt> member of <tt>Bar</tt>
 like this:</p>
<div class="code">
<pre>
Bar b = new Bar();
Foo x = b.getF();
</pre>
</div>
<p> In this case, <tt>x</tt> is a pointer that points to the <tt>Foo</tt>
 that is inside <tt>b</tt>. This is the same value as generated by this
 C code:</p>
<div class="code">
<pre>
Bar b;
Foo *x = &amp;b-&gt;f;       /* Points inside b */
</pre>
</div>
<p> Because the pointer points inside the structure, you can modify the
 contents and everything works just like you would expect. For example:</p>
<div class="code">
<pre>
Bar b = new Bar();
b.getF().setA(3);   // Modify b.f.a
Foo x = b.getF();                   
x.setA(3);          // Modify x.a - this is the same as b.f.a
</pre>
</div>
<h3><a name="Java_classes">26.3.8 C++ classes</a></h3>
<p> C++ classes are wrapped by Java classes as well. For example, if you
 have this class,</p>
<div class="code">
<pre>
class List {
public:
  List();
  ~List();
  int  search(char *item);
  void insert(char *item);
  void remove(char *item);
  char *get(int n);
  int  length;
};
</pre>
</div>
<p> you can use it in Java like this:</p>
<div class="code">
<pre>
List l = new List();
l.insert(&quot;Ale&quot;);
l.insert(&quot;Stout&quot;);
l.insert(&quot;Lager&quot;);
String item = l.get(2);
int length = l.getLength();
</pre>
</div>
<p> Class data members are accessed in the same manner as C structures.</p>
<p> Static class members are unsurprisingly wrapped as static members of
 the Java class:</p>
<div class="code">
<pre>
class Spam {
public:
  static void foo();
  static int bar;
};
</pre>
</div>
<p> The static members work like any other Java static member:</p>
<div class="code">
<pre>
Spam.foo();
int bar = Spam.getBar();
</pre>
</div>
<h3><a name="Java_inheritance">26.3.9 C++ inheritance</a></h3>
<p> SWIG is fully aware of issues related to C++ inheritance. Therefore,
 if you have classes like this</p>
<div class="code">
<pre>
class Foo {
...
};

class Bar : public Foo {
...
};
</pre>
</div>
<p> those classes are wrapped into a hierarchy of Java classes that
 reflect the same inheritance structure:</p>
<div class="code">
<pre>
Bar b = new Bar();
Class c = b.getClass();
System.out.println(c.getSuperclass().getName());
</pre>
</div>
<p> will of course display:</p>
<div class="code">
<pre>
Foo
</pre>
</div>
<p> Furthermore, if you have functions like this</p>
<div class="code">
<pre>
void spam(Foo *f);
</pre>
</div>
<p> then the Java function <tt>spam()</tt> accepts instances of <tt>Foo</tt>
 or instances of any other proxy classes derived from <tt>Foo</tt>.</p>
<p> Note that Java does not support multiple inheritance so any multiple
 inheritance in the C++ code is not going to work. A warning is given
 when multiple inheritance is detected and only the first base class is
 used.</p>
<h3><a name="Java_pointers_refs_arrays">26.3.10 Pointers, references,
 arrays and pass by value</a></h3>
<p> In C++, there are many different ways a function might receive and
 manipulate objects. For example:</p>
<div class="code">
<pre>
void spam1(Foo *x);      // Pass by pointer
void spam2(Foo &amp;x);      // Pass by reference
void spam3(Foo x);       // Pass by value
void spam4(Foo x[]);     // Array of objects
</pre>
</div>
<p> In Java, there is no detailed distinction like this--specifically,
 there are only instances of classes. There are no pointers nor
 references. Because of this, SWIG unifies all of these types together
 in the wrapper code. For instance, if you actually had the above
 functions, it is perfectly legal to do this from Java:</p>
<div class="code">
<pre>
Foo f = new Foo();  // Create a Foo
example.spam1(f);   // Ok. Pointer
example.spam2(f);   // Ok. Reference
example.spam3(f);   // Ok. Value.
example.spam4(f);   // Ok. Array (1 element)
</pre>
</div>
<p> Similar behavior occurs for return values. For example, if you had
 functions like this,</p>
<div class="code">
<pre>
Foo *spam5();
Foo &amp;spam6();
Foo  spam7();
</pre>
</div>
<p> then all three functions will return a pointer to some <tt>Foo</tt>
 object. Since the third function (spam7) returns a value, newly
 allocated memory is used to hold the result and a pointer is returned
 (Java will release this memory when the returned object's finalizer is
 run by the garbage collector).</p>
<h4><a name="Java_null_pointers">26.3.10.1 Null pointers</a></h4>
<p> Working with null pointers is easy. A Java <tt>null</tt> can be used
 whenever a method expects a proxy class or typewrapper class. However,
 it is not possible to pass null to C/C++ functions that take parameters
 by value or by reference. If you try you will get a
 NullPointerException.</p>
<div class="code">
<pre>
example.spam1(null);   // Pointer - ok
example.spam2(null);   // Reference - NullPointerException
example.spam3(null);   // Value - NullPointerException
example.spam4(null);   // Array - ok
</pre>
</div>
<p> For <tt>spam1</tt> and <tt>spam4</tt> above the Java <tt>null</tt>
 gets translated into a NULL pointer for passing to the C/C++ function.
 The converse also occurs, that is, NULL pointers are translated into <tt>
null</tt> Java objects when returned from a C/C++ function.</p>
<h3><a name="Java_overloaded_functions">26.3.11 C++ overloaded functions</a>
</h3>
<p> C++ overloaded functions, methods, and constructors are mostly
 supported by SWIG. For example, if you have two functions like this:</p>
<div class="code">
<pre>
%module example

void foo(int);
void foo(char *c);
</pre>
</div>
<p> You can use them in Java in a straightforward manner:</p>
<div class="code">
<pre>
example.foo(3);           // foo(int)
example.foo(&quot;Hello&quot;);     // foo(char *c)
</pre>
</div>
<p> Similarly, if you have a class like this,</p>
<div class="code">
<pre>
class Foo {
public:
  Foo();
  Foo(const Foo &amp;);
  ...
};
</pre>
</div>
<p> you can write Java code like this:</p>
<div class="code">
<pre>
Foo f = new Foo();        // Create a Foo
Foo g = new Foo(f);       // Copy f
</pre>
</div>
<p> Overloading support is not quite as flexible as in C++. Sometimes
 there are methods that SWIG cannot disambiguate as there can be more
 than one C++ type mapping onto a single Java type. For example:</p>
<div class="code">
<pre>
void spam(int);
void spam(unsigned short);
</pre>
</div>
<p> Here both int and unsigned short map onto a Java int. Here is
 another example:</p>
<div class="code">
<pre>
void foo(Bar *b);
void foo(Bar &amp;b);
</pre>
</div>
<p> If declarations such as these appear, you will get a warning message
 like this:</p>
<div class="code">
<pre>
example.i:12: Warning 515: Overloaded method spam(unsigned short) ignored.
Method spam(int) at example.i:11 used.
</pre>
</div>
<p> To fix this, you either need to either <a href="#SWIG_rename_ignore">
rename or ignore</a> one of the methods. For example:</p>
<div class="code">
<pre>
%rename(spam_ushort) spam(unsigned short);
...
void spam(int);    
void spam(unsigned short);   // Now renamed to spam_ushort
</pre>
</div>
<p> or</p>
<div class="code">
<pre>
%ignore spam(unsigned short);
...
void spam(int);    
void spam(unsigned short);   // Ignored
</pre>
</div>
<h3><a name="Java_default_arguments">26.3.12 C++ default arguments</a></h3>
<p> Any function with a default argument is wrapped by generating an
 additional function for each argument that is defaulted. For example,
 if we have the following C++:</p>
<div class="code">
<pre>
%module example

void defaults(double d=10.0, int i=0);
</pre>
</div>
<p> The following methods are generated in the Java module class:</p>
<div class="code">
<pre>
public class example {
  public static void defaults(double d, int i) { ... }
  public static void defaults(double d) { ... }
  public static void defaults() { ... }
}
</pre>
</div>
<p> It is as if SWIG had parsed three separate overloaded methods. The
 same approach is taken for static methods, constructors and member
 methods.</p>
<p><b> Compatibility note:</b> Versions of SWIG prior to SWIG-1.3.23
 wrapped these with a single wrapper method and so the default values
 could not be taken advantage of from Java. Further details on default
 arguments and how to restore this approach are given in the more
 general <a href="#SWIGPlus_default_args">Default arguments</a> section.</p>
<h3><a name="Java_namespaces">26.3.13 C++ namespaces</a></h3>
<p> SWIG is aware of named C++ namespaces and they can be mapped to Java
 packages, however, the default wrapping flattens the namespaces,
 effectively ignoring them. So by default, the namespace names do not
 appear in the module nor do namespaces result in a module that is
 broken up into submodules or packages. For example, if you have a file
 like this,</p>
<div class="code">
<pre>
%module example

namespace foo {
  int fact(int n);
  struct Vector {
    double x, y, z;
  };
};
</pre>
</div>
<p> it works in Java as follows:</p>
<div class="code">
<pre>
int f = example.fact(3);
Vector v = new Vector();
v.setX(3.4);
double y = v.getY();
</pre>
</div>
<p> If your program has more than one namespace, name conflicts (if any)
 can be resolved using <tt>%rename</tt> For example:</p>
<div class="code">
<pre>
%rename(Bar_spam) Bar::spam;

namespace Foo {
  int spam();
}

namespace Bar {
  int spam();
}
</pre>
</div>
<p> If you have more than one namespace and you want to keep their
 symbols separate, consider wrapping them as separate SWIG modules. Each
 SWIG module can be placed into a separate package.</p>
<p> The default behaviour described above can be improved via the <a href="#SWIGPlus_nspace">
nspace feature</a>. Note that it only works for classes, structs, unions
 and enums declared within a named C++ namespace. When the nspace
 feature is used, the C++ namespaces are converted into Java packages of
 the same name. Proxy classes are thus declared within a package and
 this proxy makes numerous calls to the JNI intermediary class which is
 declared in the unnamed package by default. As Java does not support
 types declared in a named package accessing types declared in an
 unnamed package, the <tt>-package</tt> commandline option described
 earlier generally should be used to provide a parent package. So if
 SWIG is run using the <tt>-package com.myco</tt> option, a wrapped
 class, <tt>MyWorld::Material::Color</tt>, can then be accessed as <tt>
com.myco.MyWorld.Material.Color</tt>. If you don't specify a package,
 you will get the following warning:</p>
<div class="shell">
<pre>
example.i:16: Warning 826: The nspace feature is used on 'MyWorld::Material::Color' without -package. The generated code 
may not compile as Java does not support types declared in a named package accessing types declared in an unnamed package.
</pre>
</div>
<p> If it is undesirable to have a single top level package, the nspace
 feature may be used without the <tt>-package</tt> commandline option
 (and the resulting warning ignored) if all of the types exposed using
 SWIG are placed in a package using the nspace feature and the
 'jniclasspackage' pragma is used to specify a package for the JNI
 intermediary class.</p>
<p> If the resulting use of the nspace feature and hence packages
 results in a proxy class in one package deriving or using a proxy class
 from another package, you will need to open up the visibility for the
 pointer constructor and <tt>getCPtr</tt> method from the default
 'protected' to 'public' with the <tt>SWIG_JAVABODY_PROXY</tt> macro.
 See <a href="#Java_code_typemaps">Java code typemaps</a>.</p>
<h3><a name="Java_templates">26.3.14 C++ templates</a></h3>
<p> C++ templates don't present a huge problem for SWIG. However, in
 order to create wrappers, you have to tell SWIG to create wrappers for
 a particular template instantiation. To do this, you use the <tt>
%template</tt> directive. For example:</p>
<div class="code">
<pre>
%module example
%{
#include &lt;utility&gt;
%}

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

%template(pairii) pair&lt;int, int&gt;;
</pre>
</div>
<p> In Java:</p>
<div class="code">
<pre>
pairii p = new pairii(3, 4);
int first = p.getFirst();
int second = p.getSecond();
</pre>
</div>
<p> Obviously, there is more to template wrapping than shown in this
 example. More details can be found in the <a href="#SWIGPlus">SWIG and
 C++</a> chapter.</p>
<h3><a name="Java_smart_pointers">26.3.15 C++ Smart Pointers</a></h3>
<h4><a name="Java_smart_pointers_shared_ptr">26.3.15.1 The shared_ptr
 Smart Pointer</a></h4>
<p> The C++11 standard provides <tt>std::shared_ptr</tt> which was
 derived from the Boost implementation, <tt>boost::shared_ptr</tt>. Both
 of these are available for Java in the SWIG library and usage is
 outlined in the <a href="#Library_std_shared_ptr">shared_ptr smart
 pointer</a> library section.</p>
<h4><a name="Java_smart_pointers_generic">26.3.15.2 Generic Smart
 Pointers</a></h4>
<p> In certain C++ programs, it is common to use classes that have been
 wrapped by so-called &quot;smart pointers.&quot; Generally, this involves the use
 of a template class that implements <tt>operator-&gt;()</tt> like this:</p>
<div class="code">
<pre>
template&lt;class T&gt; class SmartPtr {
  ...
  T *operator-&gt;();
  ...
}
</pre>
</div>
<p> Then, if you have a class like this,</p>
<div class="code">
<pre>
class Foo {
public:
  int x;
  int bar();
};
</pre>
</div>
<p> A smart pointer would be used in C++ as follows:</p>
<div class="code">
<pre>
SmartPtr&lt;Foo&gt; p = CreateFoo();   // Created somehow (not shown)
...
p-&gt;x = 3;                        // Foo::x
int y = p-&gt;bar();                // Foo::bar
</pre>
</div>
<p> To wrap this in Java, simply tell SWIG about the <tt>SmartPtr</tt>
 class and the low-level <tt>Foo</tt> object. Make sure you instantiate <tt>
SmartPtr</tt> using <tt>%template</tt> if necessary. For example:</p>
<div class="code">
<pre>
%module example
...
%template(SmartPtrFoo) SmartPtr&lt;Foo&gt;;
...
</pre>
</div>
<p> Now, in Java, everything should just &quot;work&quot;:</p>
<div class="code">
<pre>
SmartPtrFoo p = example.CreateFoo(); // Create a smart-pointer somehow
p.setX(3);                           // Foo::x
int y = p.bar();                     // Foo::bar
</pre>
</div>
<p> If you ever need to access the underlying pointer returned by <tt>
operator-&gt;()</tt> itself, simply use the <tt>__deref__()</tt> method.
 For example:</p>
<div class="code">
<pre>
Foo f = p.__deref__();               // Returns underlying Foo *
</pre>
</div>
<h2><a name="Java_further_details">26.4 Further details on the generated
 Java classes</a></h2>
<p> In the previous section, a high-level view of Java wrapping was
 presented. A key component of this wrapping is that structures and
 classes are wrapped by Java proxy classes and type wrapper classes are
 used in situations where no proxies are generated. This provides a very
 natural, type safe Java interface to the C/C++ code and fits in with
 the Java programming paradigm. However, a number of low-level details
 were omitted. This section provides a brief overview of how the proxy
 classes work and then covers the type wrapper classes. Finally enum
 classes are covered. First, the crucial intermediary JNI class is
 considered.</p>
<h3><a name="Java_imclass">26.4.1 The intermediary JNI class</a></h3>
<p> In the <a href="#SWIG">&quot;SWIG basics&quot;</a> and <a href="#SWIGPlus">
&quot;SWIG and C++&quot;</a> chapters, details of low-level structure and class
 wrapping are described. To summarize those chapters, if you have a
 global function and class like this</p>
<div class="code">
<pre>
class Foo {
public:
  int x;
  int spam(int num, Foo* foo);
};
void egg(Foo* chips);
</pre>
</div>
<p> then SWIG transforms the class into a set of low-level procedural
 wrappers. These procedural wrappers essentially perform the equivalent
 of this C++ code:</p>
<div class="code">
<pre>
Foo *new_Foo() {
  return new Foo();
}
void delete_Foo(Foo *f) {
  delete f;
}
int Foo_x_get(Foo *f) {
  return f-&gt;x;
}
void Foo_x_set(Foo *f, int value) {
  f-&gt;x = value;
}
int Foo_spam(Foo *f, int num, Foo* foo) {
  return f-&gt;spam(num, foo);
}
</pre>
</div>
<p> These procedural function names don't actually exist, but their
 functionality appears inside the generated JNI functions. The JNI
 functions have to follow a particular naming convention so the function
 names are actually:</p>
<div class="code">
<pre>
SWIGEXPORT jlong JNICALL Java_exampleJNI_new_1Foo(JNIEnv *jenv, jclass jcls);
SWIGEXPORT void JNICALL Java_exampleJNI_delete_1Foo(JNIEnv *jenv, jclass jcls,
                                                    jlong jarg1);
SWIGEXPORT void JNICALL Java_exampleJNI_Foo_1x_1set(JNIEnv *jenv, jclass jcls,
                                                    jlong jarg1, jobject jarg1_, jint jarg2);
SWIGEXPORT jint JNICALL Java_exampleJNI_Foo_1x_1get(JNIEnv *jenv, jclass jcls,
                                                    jlong jarg1, jobject jarg1_);
SWIGEXPORT jint JNICALL Java_exampleJNI_Foo_1spam(JNIEnv *jenv, jclass jcls,
                                                  jlong jarg1, jobject jarg1_, jint jarg2,
                                                  jlong jarg3, jobject jarg3_);
SWIGEXPORT void JNICALL Java_exampleJNI_egg(JNIEnv *jenv, jclass jcls,
                                            jlong jarg1, jobject jarg1_);
</pre>
</div>
<p> For every JNI C function there has to be a static native Java
 function. These appear in the intermediary JNI class:</p>
<div class="code">
<pre>
class exampleJNI {
  public final static native long new_Foo();
  public final static native void delete_Foo(long jarg1);
  public final static native void Foo_x_set(long jarg1, Foo jarg1_, int jarg2);
  public final static native int Foo_x_get(long jarg1, Foo jarg1_);
  public final static native int Foo_spam(long jarg1, Foo jarg1_, int jarg2,
                                          long jarg3, Foo jarg3_);
  public final static native void egg(long jarg1, Foo jarg1_);
}
</pre>
</div>
<p> This class contains the complete Java - C/C++ interface so all
 function calls go via this class. As this class acts as a go-between
 for all JNI calls to C/C++ code from the Java <a href="#Java_proxy_classes">
proxy classes</a>, <a href="#Java_type_wrapper_classes">type wrapper
 classes</a> and <a href="#Java_module_class">module class</a>, it is
 known as the intermediary JNI class.</p>
<p> You may notice that SWIG uses a Java long wherever a pointer or
 class object needs to be marshalled across the Java-C/C++ boundary.
 This approach leads to minimal JNI code which makes for better
 performance as JNI code involves a lot of string manipulation. SWIG
 favours generating Java code over JNI code as Java code is compiled
 into byte code and avoids the costly string operations needed in JNI
 code. This approach has a downside though as the proxy class might get
 collected before the native method has completed. You might notice
 above that there is an additional parameters with a underscore postfix,
 eg <tt>jarg1_</tt>. These are added in order to prevent <a href="#Java_pgcpp">
premature garbage collection when marshalling proxy classes</a>.</p>
<p> The functions in the intermediary JNI class cannot be accessed
 outside of its package. Access to them is gained through the module
 class for globals otherwise the appropriate proxy class.</p>
 <a name="Java_module_directive"></a>
<p> The name of the intermediary JNI class can be changed from its
 default, that is, the module name with JNI appended after it. The
 module directive attribute <tt>jniclassname</tt> is used to achieve
 this:</p>
<div class="code">
<pre>
%module (jniclassname=&quot;name&quot;) modulename
</pre>
</div>
<p> If <tt>name</tt> is the same as <tt>modulename</tt> then the module
 class name gets changed from <tt>modulename</tt> to <tt>
modulenameModule</tt>.</p>
<h4><a name="Java_imclass_pragmas">26.4.1.1 The intermediary JNI class
 pragmas</a></h4>
<p> The intermediary JNI class can be tailored through the use of
 pragmas, but is not commonly done. The pragmas for this class are:</p>
<table BORDER summary="Intermediary JNI class pragmas">
<tr VALIGN="TOP"><td><b>Pragma</b></td><td><b>Description</b></td></tr>
<tr><td>jniclassbase</td><td>Base class for the intermediary JNI class</td>
</tr>
<tr><td>jniclasspackage</td><td>Package in which to place the
 intermediary JNI class</td></tr>
<tr><td>jniclassclassmodifiers</td><td>Class modifiers and class type
 for the intermediary JNI class</td></tr>
<tr><td>jniclasscode</td><td>Java code is copied verbatim into the
 intermediary JNI class</td></tr>
<tr><td>jniclassimports</td><td>Java code, usually one or more import
 statements, placed before the intermediary JNI class definition</td></tr>
<tr><td>jniclassinterfaces</td><td>Comma separated interface classes for
 the intermediary JNI class</td></tr>
</table>
<p> The pragma code appears in the generated intermediary JNI class
 where you would expect:</p>
<div class="code">
<pre>
[ jniclassimports pragma ]
[ jniclassclassmodifiers pragma ] jniclassname extends [ jniclassbase pragma ]
                                          implements [ jniclassinterfaces pragma ] {
[ jniclasscode pragma ]
... SWIG generated native methods ...
}
</pre>
</div>
<p> The <tt>jniclasscode</tt> pragma is quite useful for adding in a
 static block for loading the shared library / dynamic link library and
 demonstrates how pragmas work:</p>
<div class="code">
<pre>
%pragma(java) jniclasscode=%{
  static {
    try {
      System.loadLibrary(&quot;example&quot;);
    } catch (UnsatisfiedLinkError e) {
      System.err.println(&quot;Native code library failed to load. \n&quot; + e);
      System.exit(1);
    }
  }
%}
</pre>
</div>
<p> Pragmas will take either <tt>&quot;&quot;</tt> or <tt>%{ %}</tt> as
 delimiters. For example, let's change the intermediary JNI class access
 to just the default package-private access.</p>
<div class="code">
<pre>
%pragma(java) jniclassclassmodifiers=&quot;class&quot;
</pre>
</div>
<p> All the methods in the intermediary JNI class will then not be
 callable outside of the package as the method modifiers have been
 changed from public access to default access. This is useful if you
 want to prevent users calling these low level functions.</p>
<h3><a name="Java_module_class">26.4.2 The Java module class</a></h3>
<p> All global functions and variable getters/setters appear in the
 module class. For our example, there is just one function:</p>
<div class="code">
<pre>
public class example {
  public static void egg(Foo chips) {
    exampleJNI.egg(Foo.getCPtr(chips), chips);
  }
}
</pre>
</div>
<p> The module class is necessary as there is no such thing as a global
 in Java so all the C globals are put into this class. They are
 generated as static functions and so must be accessed as such by using
 the module name in the static function call:</p>
<div class="code">
<pre>
example.egg(new Foo());
</pre>
</div>
<p> The primary reason for having the module class wrapping the calls in
 the intermediary JNI class is to implement static type checking. In
 this case only a <tt>Foo</tt> can be passed to the <tt>egg</tt>
 function, whereas any <tt>long</tt> can be passed to the <tt>egg</tt>
 function in the intermediary JNI class.</p>
<h4><a name="Java_module_class_pragmas">26.4.2.1 The Java module class
 pragmas</a></h4>
<p> The module class can be tailored through the use of pragmas, in the
 same manner as the intermediary JNI class. The pragmas are similarly
 named and are used in the same way. The complete list follows:</p>
<table BORDER summary="Java module class pragmas">
<tr VALIGN="TOP"><td><b>Pragma</b></td><td><b>Description</b></td></tr>
<tr><td>modulebase</td><td>Base class for the module class</td></tr>
<tr><td>moduleclassmodifiers</td><td>Class modifiers and class type for
 the module class</td></tr>
<tr><td>modulecode</td><td>Java code is copied verbatim into the module
 class</td></tr>
<tr><td>moduleimports</td><td>Java code, usually one or more import
 statements, placed before the module class definition</td></tr>
<tr><td>moduleinterfaces</td><td>Comma separated interface classes for
 the module class</td></tr>
</table>
<p> The pragma code appears in the generated module class like this:</p>
<div class="code">
<pre>
[ moduleimports pragma ]
[ modulemodifiers pragma ] modulename extends [ modulebase pragma ]
                                      implements [ moduleinterfaces pragma ] {
[ modulecode pragma ]
... SWIG generated wrapper functions ...
}
</pre>
</div>
<p> See <a href="#Java_imclass_pragmas">The intermediary JNI class
 pragmas</a> section for further details on using pragmas.</p>
<h3><a name="Java_proxy_classes">26.4.3 Java proxy classes</a></h3>
<p> A Java proxy class is generated for each structure, union or C++
 class that is wrapped. Proxy classes have also been called <a href="http://java.sun.com/docs/books/jni/html/stubs.html">
peer classes</a>. The default proxy class for our previous example looks
 like this:</p>
<div class="code">
<pre>
public class Foo {
  private transient long swigCPtr;
  protected transient boolean swigCMemOwn;

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

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

  protected void finalize() {
    delete();
  }

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

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

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

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

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

}
</pre>
</div>
<p> This class merely holds a pointer to the underlying C++ object (<tt>
swigCPtr</tt>). It also contains all the methods in the C++ class it is
 proxying plus getters and setters for public member variables. These
 functions call the native methods in the intermediary JNI class. The
 advantage of having this extra layer is the type safety that the proxy
 class functions offer. It adds static type checking which leads to
 fewer surprises at runtime. For example, you can see that if you
 attempt to use the <tt>spam()</tt> function it will only compile when
 the parameters passed are an <tt>int</tt> and a <tt>Foo</tt>. From a
 user's point of view, it makes the class work as if it were a Java
 class:</p>
<div class="code">
<pre>
Foo f = new Foo();
f.setX(3);
int y = f.spam(5, new Foo());
</pre>
</div>
<h4><a name="Java_memory_management">26.4.3.1 Memory management</a></h4>
<p> Each proxy class has an ownership flag <tt>swigCMemOwn</tt>. The
 value of this flag determines who is responsible for deleting the
 underlying C++ object. If set to <tt>true</tt>, the proxy class's
 finalizer will destroy the C++ object when the proxy class is garbage
 collected. If set to false, then the destruction of the proxy class has
 no effect on the C++ object.</p>
<p> When an object is created by a constructor or returned by value,
 Java automatically takes ownership of the result. On the other hand,
 when pointers or references are returned to Java, there is often no way
 to know where they came from. Therefore, the ownership is set to false.
 For example:</p>
<div class="code">
<pre>
class Foo {
public:
  Foo();
  Foo bar1();
  Foo &amp;bar2();
  Foo *bar2();
};
</pre>
</div>
<p> In Java:</p>
<div class="code">
<pre>
Foo f = new Foo();   //  f.swigCMemOwn = true
Foo f1 = f.bar1();   // f1.swigCMemOwn = true
Foo f2 = f.bar2();   // f2.swigCMemOwn = false
Foo f3 = f.bar3();   // f3.swigCMemOwn = false
</pre>
</div>
<p> This behavior for pointers and references is especially important
 for classes that act as containers. For example, if a method returns a
 pointer to an object that is contained inside another object, you
 definitely don't want Java to assume ownership and destroy it!</p>
<p> For the most part, memory management issues remain hidden. However,
 there are situations where you might have to manually change the
 ownership of an object. For instance, consider code like this:</p>
<div class="code">
<pre>
class Obj {};
class Node {
  Obj *value;
public:
  void set_value(Obj *v) { value = v; }
};
</pre>
</div>
<p> Now, consider the following Java code:</p>
<div class="code">
<pre>
Node n = new Node();    // Create a node
{
  Obj o = new Obj();    // Create an object
  n.set_value(o);       // Set value
}                       // o goes out of scope
</pre>
</div>
<p> In this case, the Node <tt>n</tt> is holding a reference to <tt>o</tt>
 internally. However, SWIG has no way to know that this has occurred.
 The Java proxy class still thinks that it has ownership of <tt>o</tt>.
 As <tt>o</tt> has gone out of scope, it could be garbage collected in
 which case the C++ destructor will be invoked and <tt>n</tt> will then
 be holding a stale-pointer to <tt>o</tt>. If you're lucky, you will
 only get a segmentation fault.</p>
<p> To work around this, the ownership flag of <tt>o</tt> needs changing
 to <tt>false</tt>. The ownership flag is a private member variable of
 the proxy class so this is not possible without some customization of
 the proxy class. This can be achieved by using a typemap to customise
 the proxy class with pure Java code as detailed later in the section on
 <a href="#Java_typemaps">Java typemaps</a>.</p>
<p> Sometimes a function will create memory and return a pointer to a
 newly allocated object. SWIG has no way of knowing this so by default
 the proxy class does not manage the returned object. However, you can
 tell the proxy class to manage the memory if you specify the <tt>
%newobject</tt> directive. Consider:</p>
<div class="code">
<pre>
class Obj {...};
class Factory {
public:
  static Obj *createObj() { return new Obj(); }
};
</pre>
</div>
<p> If we call the factory function, then we have to manually delete the
 memory:</p>
<div class="code">
<pre>
Obj obj = Factory.createObj();   // obj.swigCMemOwn = false
...
obj.delete();
</pre>
</div>
<p> Now add in the %newobject directive:</p>
<div class="code">
<pre>
%newobject Factory::createObj();

class Obj {...};
class Factory {
public:
  static Obj *createObj() { return new Obj(); }
};
</pre>
</div>
<p> A call to <tt>delete()</tt> is no longer necessary as the garbage
 collector will make the C++ destructor call because <tt>swigCMemOwn</tt>
 is now true.</p>
<div class="code">
<pre>
Obj obj = Factory.createObj();   // obj.swigCMemOwn = true;
...
</pre>
</div>
<p> Some memory management issues are quite tricky to fix and may only
 be noticeable after using for a long time. One such issue is premature
 garbage collection of an object created from Java and resultant usage
 from C++ code. The section on typemap examples cover two such
 scenarios, <a href="#Java_memory_management_objects">Memory management
 for objects passed to the C++ layer</a> and <a href="#Java_memory_management_member_variables">
Memory management when returning references to member variables</a></p>
<h4><a name="Java_inheritance_mirroring">26.4.3.2 Inheritance</a></h4>
<p> Java proxy classes will mirror C++ inheritance chains. For example,
 given the base class <tt>Base</tt> and its derived class <tt>Derived</tt>
:</p>
<div class="code">
<pre>
class Base {
public:
  virtual double foo();
};

class Derived : public Base {
public:
  virtual double foo();
};
</pre>
</div>
<p> The base class is generated much like any other proxy class seen so
 far:</p>
<div class="code">
<pre>
public class Base {
  private transient long swigCPtr;
  protected transient boolean swigCMemOwn;

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

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

  protected void finalize() {
    delete();
  }

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

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

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

}
</pre>
</div>
<p> The <tt>Derived</tt> class extends <tt>Base</tt> mirroring the C++
 class inheritance hierarchy.</p>
<div class="code">
<pre>
public class Derived extends Base {
  private transient long swigCPtr;

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

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

  protected void finalize() {
    delete();
  }

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

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

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

}
</pre>
</div>
<p> Note the memory ownership is controlled by the base class. However
 each class in the inheritance hierarchy has its own pointer value which
 is obtained during construction. The <tt>SWIGDerivedUpcast()</tt> call
 converts the pointer from a <tt>Derived *</tt> to a <tt>Base *</tt>.
 This is a necessity as C++ compilers are free to implement pointers in
 the inheritance hierarchy with different values.</p>
<p> It is of course possible to extend <tt>Base</tt> using your own Java
 classes. If <tt>Derived</tt> is provided by the C++ code, you could for
 example add in a pure Java class <tt>Extended</tt> derived from <tt>
Base</tt>. There is a caveat and that is any C++ code will not know
 about your pure Java class <tt>Extended</tt> so this type of derivation
 is restricted. However, true cross language polymorphism can be
 achieved using the <a href="#Java_directors">directors</a> feature.</p>
<h4><a name="Java_proxy_classes_gc">26.4.3.3 Proxy classes and garbage
 collection</a></h4>
<p> By default each proxy class has a <tt>delete()</tt> and a <tt>
finalize()</tt> method. The <tt>finalize()</tt> method calls <tt>
delete()</tt> which frees any malloc'd memory for wrapped C structs or
 calls the C++ class destructors. The idea is for <tt>delete()</tt> to
 be called when you have finished with the C/C++ object. Ideally you
 need not call <tt>delete()</tt>, but rather leave it to the garbage
 collector to call it from the finalizer. When a program exits, the
 garbage collector does not guarantee to call all finalizers. An insight
 into the reasoning behind this can be obtained from <a href="https://www.hpl.hp.com/techreports/2002/HPL-2002-335.html">
Hans Boehm's Destructors, Finalizers, and Synchronization</a> paper.
 Depending on what the finalizers do and which operating system you use,
 this may or may not be a problem.</p>
<p> If the <tt>delete()</tt> call into JNI code is just for memory
 handling, there is not a problem when run on most operating systems,
 for example Windows and Unix. Say your JNI code creates memory on the
 heap which your finalizers should clean up, the finalizers may or may
 not be called before the program exits. In Windows and Unix all memory
 that a process uses is returned to the system on exit, so this isn't a
 problem. This is not the case in some operating systems like vxWorks.
 If however, your finalizer calls into JNI code invoking the C++
 destructor which in turn releases a TCP/IP socket for example, there is
 no guarantee that it will be released. Note that with long running
 programs the garbage collector will eventually run, thereby calling any
 unreferenced object's finalizers.</p>
<p> Some not so ideal solutions are:</p>
<ol>
<li>
<p> Call the <tt>System.runFinalizersOnExit(true)</tt> or <tt>
Runtime.getRuntime().runFinalizersOnExit(true)</tt> to ensure the
 finalizers are called before the program exits. The catch is that this
 is a deprecated function call as the documentation says:</p>
<div class="code"><i> This method is inherently unsafe. It may result in
 finalizers being called on live objects while other threads are
 concurrently manipulating those objects, resulting in erratic behavior
 or deadlock.</i></div>
<p>In many cases you will be lucky and find that it works, but it is not
 to be advocated. Have a look at <a href="https://www.oracle.com/technetwork/java/index.html">
Java web site</a> and search for <tt>runFinalizersOnExit</tt>.</p>
</li>
<li>
<p> From jdk1.3 onwards a new function, <tt>addShutdownHook()</tt>, was
 introduced which is guaranteed to be called when your program exits.
 You can encourage the garbage collector to call the finalizers, for
 example, add this static block to the class that has the <tt>main()</tt>
 function:</p>
<div class="code">
<pre>
  static {
    Runtime.getRuntime().addShutdownHook( 
      new Thread() {
        public void run() { System.gc(); System.runFinalization(); }
      }
    );
  }
</pre>
</div>
<p>Although this usually works, the documentation doesn't guarantee that
 <tt>runFinalization()</tt> will actually call the finalizers. As the
 shutdown hook is guaranteed you could also make a JNI call to clean up
 any resources that are being tracked by the C/C++ code.</p>
</li>
<li>
<p>Call the <tt>delete()</tt> function manually which will immediately
 invoke the C++ destructor. As a suggestion it may be a good idea to set
 the object to null so that should the object be inadvertently used
 again a Java null pointer exception is thrown, the alternative would
 crash the JVM by using a null C pointer. For example given a SWIG
 generated class A:</p>
<div class="code">
<pre>
A myA = new A();
// use myA ...
myA.delete();
// any use of myA here would crash the JVM 
myA=null;
// any use of myA here would cause a Java null pointer exception to be thrown
</pre>
</div>
<p> The SWIG generated code ensures that the memory is not deleted
 twice, in the event the finalizers get called in addition to the manual
 <tt>delete()</tt> call.</p>
</li>
<li>
<p> Write your own object manager in Java. You could derive all SWIG
 classes from a single base class which could track which objects have
 had their finalizers run, then call the rest of them on program
 termination. The section on <a href="#Java_typemaps">Java typemaps</a>
 details how to specify a pure Java base class.</p>
</li>
</ol>
<p> See the <a href="http://www.devx.com/Java/Article/30192">How to
 Handle Java Finalization's Memory-Retention Issues</a> article for
 alternative approaches to managing memory by avoiding finalizers
 altogether.</p>
<h4><a name="Java_pgcpp">26.4.3.4 The premature garbage collection
 prevention parameter for proxy class marshalling</a></h4>
<p> As covered earlier, the C/C++ struct/class pointer is stored in the
 proxy class as a Java long and when needed is passed into the native
 method where it is cast into the appropriate type. This approach
 provides very fast marshalling but could be susceptible to premature
 garbage collection. Consider the following C++ code:</p>
<div class="code">
<pre>
class Wibble {
};
void wobble(Wibble &amp;w);
</pre>
</div>
<p> The module class contains the Java wrapper for the global <tt>wobble</tt>
 method:</p>
<div class="code">
<pre>
public class example {
  ...
  public static void wobble(Wibble w) {
    exampleJNI.wobble(Wibble.getCPtr(w), w);
  }
}
</pre>
</div>
<p> where <tt>example</tt> is the name of the module. All native methods
 go through the intermediary class which has the native method declared
 as such:</p>
<div class="code">
<pre>
public class exampleJNI {
  ...
  public final static native void wobble(long jarg1, Wibble jarg1_);
}
</pre>
</div>
<p> The second parameter, <tt>jarg1_</tt>, is the premature garbage
 collection prevention parameter and is added to the native method
 parameter list whenever a C/C++ struct or class is marshalled as a Java
 long. In order to understand why, consider the alternative where the
 intermediary class method is declared without the additional parameter:</p>
<div class="code">
<pre>
public class exampleJNI {
  ...
  public final static native void wobble(long jarg1);
}
</pre>
</div>
<p> and the following simple call to <tt>wobble</tt>:</p>
<div class="code">
<pre>
{
  Wibble w = new Wibble();
  example.wobble(w);
}
</pre>
</div>
<p> The hotspot compiler effectively sees something like:</p>
<div class="code">
<pre>
{
  Wibble w = new Wibble();
  long w_ptr = Wibble.getCPtr(w);
  // w is no longer reachable
  exampleJNI.wobble(w_ptr);
}
</pre>
</div>
<p> The <tt>Wibble</tt> object is no longer reachable after the point
 shown as in this bit of code, the <tt>Wibble</tt> object is not
 referenced again after this point. This means that it is a candidate
 for garbage collection. Should <tt>wobble</tt> be a long running
 method, it is quite likely that the finalizer for the <tt>Wibble</tt>
 instance will be called. This in turn will call its underlying C++
 destructor which is obviously disastrous while the method <tt>wobble</tt>
 is running using this object. Even if <tt>wobble</tt> is not a long
 running method, it is possible for the <tt>Wibble</tt> instance to be
 finalized. By passing the <tt>Wibble</tt> instance into the native
 method, it will not be finalized as the JVM guarantees not to finalize
 any objects until the native method returns. Effectively, the code then
 becomes</p>
<div class="code">
<pre>
{
  Wibble w = new Wibble();
  long w_ptr = Wibble.getCPtr(w);
  exampleJNI.wobble(w_ptr, w);
  // w is no longer reachable
}
</pre>
</div>
<p> and therefore there is no possibility of premature garbage
 collection. In practice, this premature garbage collection was only
 ever observed in Sun's server JVM from jdk-1.3 onwards and in Sun's
 client JVM from jdk-1.6 onwards.</p>
<p> The premature garbage collection prevention parameter for proxy
 classes is generated by default whenever proxy classes are passed by
 value, reference or with a pointer. The implementation for this extra
 parameter generation requires the &quot;jtype&quot; typemap to contain <tt>long</tt>
 and the &quot;jstype&quot; typemap to contain the name of a proxy class.</p>
<p> The additional parameter does impose a slight performance overhead
 and the parameter generation can be suppressed globally with the <tt>
-nopgcpp</tt> commandline option. More selective suppression is possible
 with the 'nopgcpp' attribute in the &quot;jtype&quot; <a href="#Java_typemaps">
Java typemap</a>. The attribute is a flag and so should be set to &quot;1&quot; to
 enable the suppression, or it can be omitted or set to &quot;0&quot; to disable.
 For example:</p>
<div class="code">
<pre>
%typemap(jtype, nopgcpp=&quot;1&quot;) Wibble &amp; &quot;long&quot;
</pre>
</div>
<p><b> Compatibility note:</b> The generation of this additional
 parameter did not occur in versions prior to SWIG-1.3.30.</p>
<h4><a name="Java_multithread_libraries">26.4.3.5 Single threaded
 applications and thread safety</a></h4>
<p> Single threaded Java applications using JNI need to consider thread
 safety. The same applies for the C# module where the .NET wrappers use
 PInvoke. Consider the C++ class:</p>
<div class="code">
<pre>
class Test {
  string str;
public:
  Test() : str(&quot;initial&quot;) {}
};
</pre>
</div>
<p> and the Java proxy class generated by SWIG:</p>
<div class="code">
<pre>
public class Test {
  private transient long swigCPtr;
  protected transient boolean swigCMemOwn;

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

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

  protected void finalize() {
    delete();
  }

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

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

}
</pre>
</div>
<p> It has two methods that call JNI methods, namely, <tt>
exampleJNI.new_Test()</tt> for the C++ constructor and <tt>
exampleJNI.delete_Test()</tt> for the C++ destructor. If the garbage
 collector collects an instance of this class, ie <tt>delete()</tt> is
 not explicitly called, then the C++ destructor will be run in a
 different thread to the main thread. This is because when an object is
 marked for garbage collection, any objects with finalizers are added to
 a finalization queue and the objects in the finalization queue have
 their <tt>finalize()</tt> methods run in a separate finalization
 thread. Therefore, if the C memory allocator is not thread safe, then
 the heap will get corrupted sooner or later, when a concurrent C++
 delete and new are executed. It is thus essential, even in single
 threaded usage, to link to the C multi-thread runtime libraries, for
 example, use the /MD option for Visual C++ on Windows. Alternatively,
 lock all access to C++ functions that have heap
 allocation/deallocation.</p>
<p> Note that some of the STL in Visual C++ 6 is not thread safe, so
 although code might be linked to the multithread runtime libraries,
 undefined behaviour might still occur in a single threaded Java
 program. Similarly some older versions of Sun Studio have bugs in the
 multi-threaded implementation of the std::string class and so will lead
 to undefined behaviour in these supposedly single threaded Java
 applications.</p>
<p> The following innocuous Java usage of Test is an example that will
 crash very quickly on a multiprocessor machine if the JNI compiled code
 is linked against the single thread C runtime libraries.</p>
<div class="code">
<pre>
for (int i=0; i&lt;100000; i++) {
  System.out.println(&quot;Iteration &quot; + i);
  for (int k=0; k&lt;10; k++) {
    Test test = new Test();
  }
  System.gc();
}
</pre>
</div>
<h3><a name="Java_type_wrapper_classes">26.4.4 Type wrapper classes</a></h3>
<p> The generated type wrapper class, for say an <tt>int *</tt>, looks
 like this:</p>
<div class="code">
<pre>
public class SWIGTYPE_p_int {
  private transient long swigCPtr;

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

  protected SWIGTYPE_p_int() {
    swigCPtr = 0;
  }

  protected static long getCPtr(SWIGTYPE_p_int obj) {
    return obj.swigCPtr;
  }
}
</pre>
</div>
<p> The methods do not have public access, so by default it is
 impossible to do anything with objects of this class other than pass
 them around. The methods in the class are part of the inner workings of
 SWIG. If you need to mess around with pointers you will have to use
 some typemaps specific to the Java module to achieve this. The section
 on <a href="#Java_typemaps">Java typemaps</a> details how to modify the
 generated code.</p>
<p> Note that if you use a pointer or reference to a proxy class in a
 function then no type wrapper class is generated because the proxy
 class can be used as the function parameter. If however, you need
 anything more complicated like a pointer to a pointer to a proxy class
 then a typewrapper class is generated for your use.</p>
<p> Note that SWIG generates a type wrapper class and not a proxy class
 when it has not parsed the definition of a type that gets used. For
 example, say SWIG has not parsed the definition of <tt>class Snazzy</tt>
 because it is in a header file that you may have forgotten to use the <tt>
%include</tt> directive on. Should SWIG parse <tt>Snazzy *</tt> being
 used in a function parameter, it will then generates a type wrapper
 class around a <tt>Snazzy</tt> pointer. Also recall from earlier that
 SWIG will use a pointer when a class is passed by value or by
 reference:</p>
<div class="code">
<pre>
void spam(Snazzy *x, Snazzy &amp;y, Snazzy z);
</pre>
</div>
<p> Should SWIG not know anything about <tt>Snazzy</tt> then a <tt>
SWIGTYPE_p_Snazzy</tt> must be used for all 3 parameters in the <tt>spam</tt>
 function. The Java function generated is:</p>
<div class="code">
<pre>
public static void spam(SWIGTYPE_p_Snazzy x, SWIGTYPE_p_Snazzy y, SWIGTYPE_p_Snazzy z) {
 ...
}
</pre>
</div>
<p> Note that typedefs are tracked by SWIG and the typedef name is used
 to construct the type wrapper class name. For example, consider the
 case where <tt>Snazzy</tt> is a typedef to an <tt>int</tt> which SWIG
 does parse:</p>
<div class="code">
<pre>
typedef int Snazzy;
void spam(Snazzy *x, Snazzy &amp;y, Snazzy z);
</pre>
</div>
<p> Because the typedefs have been tracked the Java function generated
 is:</p>
<div class="code">
<pre>
public static void spam(SWIGTYPE_p_int x, SWIGTYPE_p_int y, int z) { ... }
</pre>
</div>
<h3><a name="Java_enum_classes">26.4.5 Enum classes</a></h3>
<p> SWIG can generate three types of enum classes. The <a href="#Java_enumerations">
Enumerations</a> section discussed these but omitted all the details.
 The following sub-sections detail the various types of enum classes
 that can be generated.</p>
<h4><a name="Java_typesafe_enums_classes">26.4.5.1 Typesafe enum classes</a>
</h4>
<p> The following example demonstrates the typesafe enum classes which
 SWIG generates:</p>
<div class="code">
<pre>
%include &quot;enumtypesafe.swg&quot;
%javaconst(1);
enum Beverage { ALE, LAGER=10, STOUT, PILSNER, PILZ=PILSNER };
</pre>
</div>
<p> The following is the code that SWIG generates:</p>
<div class="code">
<pre>
public final class Beverage {
  public final static Beverage ALE = new Beverage(&quot;ALE&quot;);
  public final static Beverage LAGER = new Beverage(&quot;LAGER&quot;, 10);
  public final static Beverage STOUT = new Beverage(&quot;STOUT&quot;);
  public final static Beverage PILSNER = new Beverage(&quot;PILSNER&quot;);
  public final static Beverage PILZ = new Beverage(&quot;PILZ&quot;, PILSNER);

  public final int swigValue() {
    return swigValue;
  }

  public String toString() {
    return swigName;
  }

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

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

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

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

  private static Beverage[] swigValues = { ALE, LAGER, STOUT, PILSNER, PILZ };
  private static int swigNext = 0;
  private final int swigValue;
  private final String swigName;
}
</pre>
</div>
<p> As can be seen, there are a fair number of support methods for the
 typesafe enum pattern. The typesafe enum pattern involves creating a
 fixed number of static instances of the enum class. The constructors
 are private to enforce this. Three constructors are available - two for
 C/C++ enums with an initializer and one for those without an
 initializer. Note that the two enums with initializers, <tt>LAGER</tt>
 and <tt>PILZ</tt>, each call one the two different initializer
 constructors. In order to use one of these typesafe enums, the <tt>
swigToEnum</tt> static method must be called to return a reference to
 one of the static instances. The JNI layer returns the enum value from
 the C/C++ world as an integer and this method is used to find the
 appropriate Java enum static instance. The <tt>swigValue</tt> method is
 used for marshalling in the other direction. The <tt>toString</tt>
 method is overridden so that the enum name is available.</p>
<h4><a name="Java_proper_enums_classes">26.4.5.2 Proper Java enum
 classes</a></h4>
<p> The following example demonstrates the Java enums approach:</p>
<div class="code">
<pre>
%include &quot;enums.swg&quot;
%javaconst(1);
enum Beverage { ALE, LAGER=10, STOUT, PILSNER, PILZ=PILSNER };
</pre>
</div>
<p> SWIG will generate the following Java enum:</p>
<div class="code">
<pre>
public enum Beverage {
  ALE,
  LAGER(10),
  STOUT,
  PILSNER,
  PILZ(PILSNER);

  public final int swigValue() {
    return swigValue;
  }

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

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

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

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

  private final int swigValue;

  private static class SwigNext {
    private static int next = 0;
  }
}
</pre>
</div>
<p> The enum items appear first. Like the typesafe enum pattern, the
 constructors are private. The constructors are required to handle C/C++
 enums with initializers. The <tt>next</tt> variable is in the <tt>
SwigNext</tt> inner class rather than in the enum class as static
 primitive variables cannot be modified from within enum constructors.
 Marshalling between Java enums and the C/C++ enum integer value is
 handled via the <tt>swigToEnum</tt> and <tt>swigValue</tt> methods. All
 the constructors and methods in the Java enum are required just to
 handle C/C++ enums with initializers. These needn't be generated if the
 enum being wrapped does not have any initializers and the <a href="#Java_simpler_enum_classes">
Simpler Java enums for enums without initializers</a> section describes
 how typemaps can be used to achieve this.</p>
<h4><a name="Java_typeunsafe_enums_classes">26.4.5.3 Type unsafe enum
 classes</a></h4>
<p> The following example demonstrates type unsafe enums:</p>
<div class="code">
<pre>
%include &quot;enumtypeunsafe.swg&quot;
%javaconst(1);
enum Beverage { ALE, LAGER=10, STOUT, PILSNER, PILZ=PILSNER };
</pre>
</div>
<p> SWIG will generate the following simple class:</p>
<div class="code">
<pre>
public final class Beverage {
  public final static int ALE = 0;
  public final static int LAGER = 10;
  public final static int STOUT = LAGER + 1;
  public final static int PILSNER = STOUT + 1;
  public final static int PILZ = PILSNER;
}
</pre>
</div>
<h3><a name="Java_interfaces">26.4.6 Interfaces</a></h3>
<p> By default SWIG wraps all C++ classes as Java classes. As Java only
 supports derivation from a single base class, SWIG has to ignore all
 bases except the first when a C++ class inherits from more than one
 base class. However, there is a family of SWIG macros that change the
 default wrapping and allows a C++ class to be wrapped as a Java
 interface instead of a Java class. These macros provide a way to
 support some sort of multiple inheritance as there is no limit to the
 number of interfaces that a Java class can inherit from.</p>
<p> When a C++ class is wrapped as a Java interface, a Java proxy class
 is still needed. The <tt>swiginterface.i</tt> library file provides
 three macros for marking a C++ class to be wrapped as a Java interface.
 There is more than one macro in order to provide a choice for choosing
 the Java interface and Java proxy names.</p>
<table BORDER summary="Java interface macros">
<tr VALIGN="TOP"><td><b>Interface Macro Name</b></td><td><b>Description</b>
</td></tr>
<tr><td><tt>%interface(CTYPE)</tt></td><td>For C++ class <tt>CTYPE</tt>,
 proxy class name is unchanged without any suffix added, interface name
 has <tt>SwigInterface</tt> added as a suffix.</td></tr>
<tr><td><tt>%interface_impl(CTYPE)</tt></td><td>For C++ class <tt>CTYPE</tt>
, proxy class name has <tt>SwigImpl</tt> added as a suffix, interface
 name has no added suffix.</td></tr>
<tr><td><tt>%interface_custom(&quot;PROXY&quot;, &quot;INTERFACE&quot;, CTYPE)</tt></td><td>
For C++ class <tt>CTYPE</tt>, proxy class name is given by the string <tt>
PROXY</tt>, interface name is given by the string <tt>INTERFACE</tt>.
 The <tt>PROXY</tt> and <tt>INTERFACE</tt> names can use the <a href="#SWIG_advanced_renaming">
string formatting functions</a> used in <tt>%rename</tt>.</td></tr>
</table>
<p> The table below has a few examples showing the resulting proxy and
 interface names for a C++ class called <tt>Base</tt>.</p>
<table BORDER summary="Java interface macro examples">
<tr VALIGN="TOP"><td><b>Example Usage</b></td><td><b>Proxy Class Name</b>
</td><td><b>Interface Class Name</b></td></tr>
<tr><td><tt>%interface(Base)</tt></td><td><tt>Base</tt></td><td><tt>
BaseSwigInterface</tt></td></tr>
<tr><td><tt>%interface_impl(Base)</tt></td><td><tt>BaseSwigImpl</tt></td><td>
<tt>Base</tt></td></tr>
<tr><td><tt>%interface_custom(&quot;BaseProxy&quot;, &quot;IBase&quot;, Base)</tt></td><td><tt>
BaseProxy</tt></td><td><tt>IBase</tt></td></tr>
<tr><td><tt>%interface_custom(&quot;%sProxy&quot;, &quot;IBase&quot;, Base)</tt></td><td><tt>
BaseProxy</tt></td><td><tt>IBase</tt></td></tr>
<tr><td><tt>%interface_custom(&quot;%sProxy&quot;, &quot;%sInterface&quot;, Base)</tt></td><td>
<tt>BaseProxy</tt></td><td><tt>BaseProxyInterface</tt></td></tr>
<tr><td><tt>%interface_custom(&quot;%sProxy&quot;, &quot;%(rstrip:[Proxy])sInterface&quot;,
 Base)</tt></td><td><tt>BaseProxy</tt></td><td><tt>BaseInterface</tt></td>
</tr>
</table>
<p> The 2nd last example shows the names used in the string formatting
 functions. The input for <tt>PROXY</tt> that <tt>&quot;%s&quot;</tt> expands to
 is the proxy name, that is, Base. The input for <tt>INTERFACE</tt> that
 <tt>&quot;%s&quot;</tt> expands to is the proxy name, that is, <tt>BaseProxy</tt>
.</p>
<p> The last example shows <tt>rstrip</tt> and in this case strips the <tt>
Proxy</tt> suffix and then adds on <tt>Interface</tt>.</p>
<p> Consider the following C++ code:</p>
<div class="code">
<pre>
namespace Space {
  struct Base1 {
    virtual void Method1();
  };
  struct Base2 {
    virtual void Method2();
  };
  struct Derived : Base1, Base2 {
  };
  void UseBases(const Base1 &amp;b1, const Base2 &amp;b2);
}
</pre>
</div>
<p> By default all classes are wrapped and are available in Java, but, <tt>
Derived</tt> has all bases ignored except the first. SWIG generates a
 warning for the above code:</p>
<div class="shell">
<pre>
example.i:10: Warning 813: Warning for Derived, base Base2 ignored. 
Multiple inheritance is not supported in Java.
</pre>
</div>
<p> If we decide to wrap the two base classes as interfaces and add the
 following before SWIG parses the above example code:</p>
<div class="code">
<pre>
%include &lt;swiginterface.i&gt;
%interface_impl(Space::Base1);
%interface_impl(Space::Base2);
</pre>
</div>
<p> then two interface files are generated, Base1.java and Base2.java in
 addition to proxy class files, Base1SwigImpl.java and
 Base2SwigImpl.java. The contents of interface file Base1.java for <tt>
Base1</tt> is shown below:</p>
<div class="code">
<pre>
public interface Base1 {
  long Base1_GetInterfaceCPtr();
  void Method1();
}
</pre>
</div>
<p> The proxy class in Base1SwigImpl.java for Base1 is as it would have
 been if <tt>%interface</tt> was not used, except the name has changed
 to <tt>Base1SwigImpl</tt> and it implements the appropriate base:</p>
<div class="code">
<pre>
public class Base1SwigImpl implements Base1 {
...
  public long Base1_GetInterfaceCPtr() {
    return exampleJNI.Base1SwigImpl_Base1_GetInterfaceCPtr(swigCPtr);
  }

  public void Method1() {
    exampleJNI.Base1SwigImpl_Method1(swigCPtr, this);
  }
...
}
</pre>
</div>
<p> In fact any class deriving from <tt>Base</tt> will now implement the
 interface instead of deriving from it (or ignoring the base in the case
 of multiple base classes). Hence the <tt>Derived</tt> proxy class will
 now implement both bases:</p>
<div class="code">
<pre>
public class Derived implements Base1, Base2 {
...
  public long Base1_GetInterfaceCPtr() {
    return exampleJNI.Derived_Base1_GetInterfaceCPtr(swigCPtr);
  }

  public long Base2_GetInterfaceCPtr() {
    return exampleJNI.Derived_Base2_GetInterfaceCPtr(swigCPtr);
  }

  public void Method1() {
    exampleJNI.Derived_Method1(swigCPtr, this);
  }

  public void Method2() {
    exampleJNI.Derived_Method2(swigCPtr, this);
  }
...
}
</pre>
</div>
<p> Wherever a class marked as an interface is used, such as the <tt>
UseBases</tt> method in the example, the interface name is used as the
 type in the Java layer:</p>
<div class="code">
<pre>
  public static void UseBases(Base1 b1, Base2 b2) {
    exampleJNI.UseBases(b1.Base1_GetInterfaceCPtr(), b1, b2.Base2_GetInterfaceCPtr(), b2);
  }
</pre>
</div>
<p> Note that each Java interface has a method added to obtain the
 correct C++ pointer for passing to the native function - <tt>
Base1_GetInterfaceCPtr</tt> for <tt>Base1</tt>. This method is similar
 to the <tt>getCPtr</tt> method in the proxy classes. In fact, as shown
 above in the <tt>Derived</tt> class, the proxy classes implement this
 generated interface by calling a native method (<tt>
Derived_Base1_GetInterfaceCPtr</tt>) which calls an appropriate C++ cast
 of the pointer up the inheritance chain.</p>
<p> The interface macros are implemented using the <tt>interface</tt>
 feature and typemaps. For example:</p>
<div class="code">
<pre>
%define %interface(CTYPE...)
%feature(&quot;interface&quot;, name=&quot;%sSwigInterface&quot;) CTYPE;
INTERFACE_TYPEMAPS(CTYPE)
%enddef
</pre>
</div>
<p> The feature accepts one attribute called <tt>name</tt>, which is the
 name of the Java interface mentioned earlier. The <tt>
INTERFACE_TYPEMAPS</tt> macro implements the typemaps and can be viewed
 in the <tt>swiginterface.i</tt> file and contain the usual Java
 typemaps for generating code plus the <tt>javainterfacecode</tt>
 typemap which is only used when a class is marked with the <tt>
interface</tt> feature. See <a href="#Java_code_typemaps">Java code
 typemaps</a> for details.</p>
<h2><a name="Java_directors">26.5 Cross language polymorphism using
 directors</a></h2>
<p> Proxy classes provide a natural, object-oriented way to wrap C++
 classes. as described earlier, each proxy instance has an associated
 C++ instance, and method calls from Java to the proxy are passed to the
 C++ instance transparently via C wrapper functions.</p>
<p> This arrangement is asymmetric in the sense that no corresponding
 mechanism exists to pass method calls down the inheritance chain from
 C++ to Java. In particular, if a C++ class has been extended in Java
 (by deriving from the proxy class), these classes will not be visible
 from C++ code. Virtual method calls from C++ are thus not able to
 access the lowest implementation in the inheritance chain.</p>
<p> SWIG can address this problem and make the relationship between C++
 classes and proxy classes more symmetric. To achieve this goal, new
 classes called directors are introduced at the bottom of the C++
 inheritance chain. The job of the directors is to route method calls
 correctly, either to C++ implementations higher in the inheritance
 chain or to Java implementations lower in the inheritance chain. The
 upshot is that C++ classes can be extended in Java and from C++ these
 extensions look exactly like native C++ classes. Neither C++ code nor
 Java code needs to know where a particular method is implemented: the
 combination of proxy classes, director classes, and C wrapper functions
 transparently takes care of all the cross-language method routing.</p>
<h3><a name="Java_enabling_directors">26.5.1 Enabling directors</a></h3>
<p> The director feature is disabled by default. To use directors you
 must make two changes to the interface file. First, add the &quot;directors&quot;
 option to the %module directive, like this:</p>
<div class="code">
<pre>
%module(directors=&quot;1&quot;) modulename
</pre>
</div>
<p> Without this option no director code will be generated. Second, you
 must use the %feature(&quot;director&quot;) directive to tell SWIG which classes
 and methods should get directors. The %feature directive can be applied
 globally, to specific classes, and to specific methods, like this:</p>
<div class="code">
<pre>
// generate directors for all classes that have virtual methods
%feature(&quot;director&quot;);         

// generate directors for the virtual methods in class Foo
%feature(&quot;director&quot;) Foo;      
</pre>
</div>
<p> You can use the %feature(&quot;nodirector&quot;) directive to turn off
 directors for specific classes or methods. So for example,</p>
<div class="code">
<pre>
%feature(&quot;director&quot;) Foo;
%feature(&quot;nodirector&quot;) Foo::bar;
</pre>
</div>
<p> will generate directors for the virtual methods of class Foo except
 bar().</p>
<p> Directors can also be generated implicitly through inheritance. In
 the following, class Bar will get a director class that handles the
 methods one() and two() (but not three()):</p>
<div class="code">
<pre>
%feature(&quot;director&quot;) Foo;
class Foo {
public:
  virtual void one();
  virtual void two();
};

class Bar: public Foo {
public:
  virtual void three();
};
</pre>
</div>
<h3><a name="Java_directors_classes">26.5.2 Director classes</a></h3>
<p> For each class that has directors enabled, SWIG generates a new
 class that derives from both the class in question and a special <tt>
Swig::Director</tt> class. These new classes, referred to as director
 classes, can be loosely thought of as the C++ equivalent of the Java
 proxy classes. The director classes store a pointer to their underlying
 Java proxy classes.</p>
<p> For simplicity let's ignore the <tt>Swig::Director</tt> class and
 refer to the original C++ class as the director's base class. By
 default, a director class extends all virtual methods in the
 inheritance chain of its base class (see the preceding section for how
 to modify this behavior). Virtual methods that have a final specifier
 are unsurprisingly excluded. Thus the 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 &quot;appropriate place&quot; we mean the method that would
 have been called if the C++ base class and its Java derived classes
 were seamlessly integrated. That seamless integration is exactly what
 the director classes provide, transparently skipping over all the messy
 JNI glue code that binds the two languages together.</p>
<p> In reality, the &quot;appropriate place&quot; is one of only two
 possibilities: C++ or Java. Once this decision is made, the rest is
 fairly easy. If the correct implementation is in C++, then the lowest
 implementation of the method in the C++ inheritance chain is called
 explicitly. If the correct implementation is in Java, the Java API is
 used to call the method of the underlying Java object (after which the
 usual virtual method resolution in Java automatically finds the right
 implementation).</p>
<h3><a name="Java_directors_overhead">26.5.3 Overhead and code bloat</a></h3>
<p> Enabling directors for a class will generate a new director method
 for every virtual method in the class' inheritance chain. This alone
 can generate a lot of code bloat for large hierarchies. Method
 arguments that require complex conversions to and from Java types can
 result in large director methods. For this reason it is recommended
 that directors are selectively enabled only for specific classes that
 are likely to be extended in Java and used in C++.</p>
<p> Although directors make it natural to mix native C++ objects with
 Java objects (as director objects), one should be aware of the obvious
 fact that method calls to Java objects from C++ will be much slower
 than calls to C++ objects. Additionally, compared to classes that do
 not use directors, the call routing in the director methods adds a
 small overhead. This situation can be optimized by selectively enabling
 director methods (using the %feature directive) for only those methods
 that are likely to be extended in Java.</p>
<h3><a name="Java_directors_example">26.5.4 Simple directors example</a></h3>
<p> Consider the following SWIG interface file:</p>
<div class="code">
<pre>
%module(directors=&quot;1&quot;) example;

%feature(&quot;director&quot;) DirectorBase;

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

void callup(DirectorBase *director) {
  director-&gt;upcall_method();
}
</pre>
</div>
<p> The following <code>DirectorDerived</code> Java class is derived
 from the Java proxy class <code>DirectorBase</code> and overrides <code>
upcall_method()</code>. When C++ code invokes <code>upcall_method()</code>
, the SWIG-generated C++ code redirects the call via JNI to the Java <code>
DirectorDerived</code> subclass. Naturally, the SWIG generated C++ code
 and the generated Java intermediary class marshal and convert arguments
 between C++ and Java when needed.</p>
<div class="code">
<pre>
class DirectorDerived extends DirectorBase {
  @Override
  public void upcall_method() {
    System.out.println(&quot;DirectorDerived.upcall_method() invoked.&quot;);
  }
}
</pre>
</div>
<p> Running the following Java code</p>
<div class="code">
<pre>
DirectorDerived director = new DirectorDerived();
example.callup(director);
</pre>
</div>
<p> will result in the following being output:</p>
<div class="code">
<pre>
DirectorDerived.upcall_method() invoked.
</pre>
</div>
<h3><a name="Java_directors_threading">26.5.5 Director threading issues</a>
</h3>
<p> Depending on your operating system and version of Java and how you
 are using threads, you might find the JVM hangs on exit. There are a
 couple of solutions to try out. The preferred solution requires jdk-1.4
 and later and uses <tt>AttachCurrentThreadAsDaemon</tt> instead of <tt>
AttachCurrentThread</tt> whenever a call into the JVM is required. This
 can be enabled by defining the
 SWIG_JAVA_ATTACH_CURRENT_THREAD_AS_DAEMON macro when compiling the C++
 wrapper code. For older JVMs define SWIG_JAVA_NO_DETACH_CURRENT_THREAD
 instead, to avoid the <tt>DetachCurrentThread</tt> call but this will
 result in a memory leak instead. For further details inspect the source
 code in the java/director.swg library file.</p>
<p> Macros can be defined on the commandline when compiling your C++
 code, or alternatively added to the C++ wrapper file as shown below:</p>
<div class="code">
<pre>
%insert(&quot;runtime&quot;) %{
#define SWIG_JAVA_NO_DETACH_CURRENT_THREAD
%}
</pre>
</div>
<h3><a name="Java_directors_performance">26.5.6 Director performance
 tuning</a></h3>
<p> When a new instance of a director (or subclass) is created in Java,
 the C++ side of the director performs a runtime check per director
 method to determine if that particular method is overridden in Java or
 if it should invoke the C++ base implementation directly. Although this
 makes initialization slightly more expensive, it is generally a good
 overall tradeoff.</p>
<p> However, if all director methods are expected to usually be
 overridden by Java subclasses, then initialization can be made faster
 by avoiding these checks via the <tt>assumeoverride</tt> attribute. For
 example:</p>
<div class="code">
<pre>
%feature(&quot;director&quot;, assumeoverride=1) Foo;
</pre>
</div>
<p> The disadvantage is that invocation of director methods from C++
 when Java doesn't actually override the method will require an
 additional call up into Java and back to C++. As such, this option is
 only useful when overrides are extremely common and instantiation is
 frequent enough that its performance is critical.</p>
<h3><a name="Java_exceptions_from_directors">26.5.7 Java exceptions from
 directors</a></h3>
<p> With directors routing method calls to Java, and proxies routing
 them to C++, the handling of exceptions is an important concern. The
 default behavior for Java exceptions thrown in a director method
 overridden in Java is to store the thrown Java exception into a SWIG
 defined <code>Swig::DirectorException</code> C++ class exception in the
 C++ layer and then throw this C++ exception.</p>
<p> Of course, should this exception be thrown, your C++ code must catch
 it and handle it before returning back to Java. The default generated
 code<b> does not</b> attempt to handle the C++ exception, but there is
 a simple way to make this all work by catching the C++ exception and
 extracting the original Java exception by using <tt>%catches</tt> for <tt>
Swig::DirectorException</tt>. Consider the example shown earlier with a
 modification to the <tt>upcall_method</tt> Java method to throw a Java
 exception:</p>
<div class="code">
<pre>
class DirectorDerived extends DirectorBase {
  @Override
  public void upcall_method() {
    System.out.println(&quot;DirectorDerived.upcall_method() invoked.&quot;);
    throw new RuntimeException(&quot;There was a problem!&quot;);
  }
}
</pre>
</div>
<p> Now, by default, the JVM will abort when <tt>
example.callup(director)</tt> is called as the C++ <tt>
Swig::DirectorException</tt> (storing the Java exception) is thrown and
 not handled by the <tt>callup</tt> method. Needless to say this is not
 very user friendly and so the recommendation is to add the following
 simple <tt>%catches</tt> directive before SWIG parses the <tt>callup</tt>
 function:</p>
<div class="code">
<pre>
%catches(Swig::DirectorException) callup;
</pre>
</div>
<p> Or target all wrapped methods using:</p>
<div class="code">
<pre>
%catches(Swig::DirectorException);
</pre>
</div>
<p> This tells SWIG to generate a C++ catch handler using some code from
 the <a href="#Typemaps_throws_typemap">throws typemap</a> for <tt>
Swig::DirectorException</tt> that SWIG supplies by default, see <a href="#SWIGPlus_catches">
Exception handling with %catches</a>. This typemap code is written to
 simply catch the C++ <tt>Swig::DirectorException</tt> class and
 immediately return to Java throwing the original Java exception that it
 has stored. The net result is a stack trace containing the original
 Java exception including the location that the exception was thrown
 from.</p>
<div class="shell">
<pre>
DirectorDerived.upcall_method() invoked.
Exception in thread &quot;main&quot; java.lang.RuntimeException: There was a problem!
    at DirectorDerived.upcall_method(runme.java:4)
    at exampleJNI.SwigDirector_DirectorBase_upcall_method(exampleJNI.java:20)
    at exampleJNI.callup(Native Method)
    at example.callup(example.java:12)
    at runme.main(runme.java:21)
</pre>
</div>
<p> More on the <tt>Swig::DirectorException</tt> class can be found in
 the next section which details how to customize the handling of
 director exceptions.</p>
<h4><a name="Java_customizing_director_exceptions">26.5.7.1 Customizing
 director exceptions</a></h4>
<p> This section is for advanced customization of director exceptions.
 The recommendation for most users is to use the simple <tt>%catches</tt>
 directive described above as it should be sufficient for most users
 needs.</p>
<p> The conversion of Java exceptions into C++ exceptions can be
 customized in two different ways using the <code>director:except</code>
 <a href="#Customization_features">feature</a>. In the first approach, a
 code block is attached to each director method to handle the mapping of
 Java exceptions into C++ exceptions. The code block is generated just
 after the call up from the C++ director method into the overloaded
 method in Java. Its primary function is to check if a Java exception
 has been thrown and then handle it in C++. The example below converts a
 <tt>java.lang.IndexOutOfBoundsException</tt> into a C++ <tt>
std::out_of_range</tt> exception and converts a user's Java <tt>
MyJavaException</tt> into a C++ <tt>MyCppException</tt> exception. If
 the Java exception doesn't match either of these, a fallback <tt>
std::runtime_error</tt> C++ exception is thrown.</p>
<div class="code">
<pre>
%feature(&quot;director:except&quot;) MyClass::dirmethod(int x) {
  jthrowable $error = jenv-&gt;ExceptionOccurred();
  if ($error) {
    if (Swig::ExceptionMatches(jenv, $error, &quot;java/lang/IndexOutOfBoundsException&quot;))
      throw std::out_of_range(Swig::JavaExceptionMessage(jenv, $error).message());
    if (Swig::ExceptionMatches(jenv, $error, &quot;$packagepath/MyJavaException&quot;))
      throw MyCppException(Swig::JavaExceptionMessage(jenv, $error).message());
    throw std::runtime_error(&quot;Unexpected exception thrown in MyClass::dirmethod&quot;);
  }
}

class MyClass {
public:
  /** Throws either a std::out_of_range or MyCppException on error */
  virtual void dirmethod(int x);
  virtual ~MyClass();
};
</pre>
</div>
<p> A few special variables are expanded within the <tt>director:except</tt>
 feature.</p>
<ul>
<li> The special variable <tt>$error</tt> is expanded into a unique
 variable name (swigerror) and should be used for the assignment of the
 jthrowable exception that occurred.</li>
<li> The special variable <tt>$packagepath</tt> is replaced by the outer
 package provided for SWIG generation by the -package option.</li>
<li> The special variable <tt>$directorthrowshandlers</tt> is not shown
 above, but is replaced by applicable &quot;directorthrows&quot; typemap contents
 (covered later in this section).</li>
<li> The special variable <tt>$null</tt> is not shown above, but is
 replaced by a suitable default constructed object for returning from
 the director method (or nothing if the director method has a void
 return).</li>
</ul>
<p> Utility functions/classes in director.swg are provided to aid the
 exception conversion as follows:</p>
<div class="code">
<pre>
namespace Swig {

  // Helper method to determine if a Java throwable matches a particular Java class type
  // Note side effect of clearing any pending exceptions
  bool ExceptionMatches(JNIEnv *jenv, jthrowable throwable, const char *classname);

  // Helper class to extract the exception message from a Java throwable
  class JavaExceptionMessage {
  public:
    JavaExceptionMessage(JNIEnv *jenv, jthrowable throwable);

    // Return a C string of the exception message in the jthrowable passed in the constructor
    // If no message is available, null_string is return instead
    const char *message(const char *null_string = 
                        &quot;Could not get exception message in JavaExceptionMessage&quot;) const;
  };

  // C++ Exception class for handling Java exceptions thrown during a director method Java upcall
  class DirectorException : public std::exception {
  public:

    // Construct exception from a Java throwable
    DirectorException(JNIEnv *jenv, jthrowable throwable);

    // More general constructor for handling as a java.lang.RuntimeException
    DirectorException(const char *msg);

    // Return exception message extracted from the Java throwable
    const char *what() const throw();

    // Reconstruct and raise/throw the Java Exception that caused the DirectorException
    // Note that any error in the JNI exception handling results in a Java RuntimeException
    void throwException(JNIEnv *jenv) const;

    // Create and throw the DirectorException
    static void raise(JNIEnv *jenv, jthrowable throwable) {
      throw DirectorException(jenv, throwable);
    }
  };

}
</pre>
</div>
<p> The utility function <code>Swig::ExceptionMatches</code> and class <code>
Swig::JavaExceptionMessage</code> are provided to simplify writing code
 for wrappers that use the <code>director:except</code> feature. The
 function <code>Swig::ExceptionMatches</code> matches the type of the <code>
jthrowable</code> thrown against a<b> fully qualified</b> JNI style
 class name, such as <code>&quot;java/lang/IOError&quot;</code>. If the throwable
 class is the same type, or derives from the given type, <code>
Swig::ExceptionMatches</code> will return true. Care must be taken to
 provide the correct fully qualified name, since for wrapped exceptions
 the generated proxy class will have an additional package
 qualification, depending on the '-package' argument and use of the <a href="#Java_namespaces">
nspace feature</a>. The utility class <code>Swig::JavaExceptionMessage</code>
 is a holder providing access to the message from the thrown Java
 exception. The <code>message()</code> method returns the exception
 message as a <code>const char *</code>, which is only valid during the
 lifetime of the holder. Any code using this message needs to copy it,
 for example into a std::string or a newly constructed C++ exception.</p>
<p> Using the first approach above to write handlers for a large number
 of methods will require repetitive duplication of the <code>
director:except</code> feature code for each director method. To
 mitigate this, a second approach is provided via typemaps in a fashion
 analogous to the <a href="Typemaps.html#throws_typemap">&quot;throws&quot;
 typemap</a>. The &quot;throws&quot; typemap provides a way to map all the C++
 exceptions listed in a method's defined exceptions (either from a C++<em>
 exception specification</em> or a <code>%catches</code> feature) into
 Java exceptions. The &quot;directorthrows&quot; typemap provides the inverse
 mapping and should contain code to convert a suitably matching Java
 exception into a C++ exception. Only use this typemap if you wish to
 write custom conversions of Java exceptions into C++ exceptions and
 apply them to many different methods. The default handling which uses
 the <code>Swig::DirectorException</code> class should otherwise meet
 your needs.</p>
<p> The example below converts a Java <code>
java.lang.IndexOutOfBoundsException</code> exception to the typemap's
 type, that is a <code>std::out_of_range</code> C++ exception:<div class="code">
<pre>
%typemap(directorthrows) std::out_of_range %{
  if (Swig::ExceptionMatches(jenv, $error, &quot;java/lang/IndexOutOfBoundsException&quot;)) {
    throw std::out_of_range(Swig::JavaExceptionMessage(jenv, $error).message());
  }
%}
</pre>
</div></p>
<p> The &quot;directorthrows&quot; typemap is then used in conjunction with the <code>
director:except</code> feature if the <code>$directorthrowshandlers</code>
 special variable is used in the code block. Consider the following,
 which also happens to be the default:</p>
<div class="code">
<pre>
%feature(&quot;director:except&quot;) %{
  jthrowable $error = jenv-&gt;ExceptionOccurred();
  if ($error) {
    $directorthrowshandlers
    Swig::DirectorException::raise(jenv, $error);
  }
%}
</pre>
</div>
<p> where <tt>Swig::DirectorException::raise</tt> is the helper method
 to throw a C++ <tt>Swig::DirectorException</tt>, see above. The code
 generated from the <code>director:except</code> feature has the <code>
$directorthrowshandlers</code> special variable replaced with the code
 in the relevant &quot;directorthrows&quot; typemaps, for each and every exception
 defined for the method. The relevant exceptions can be defined either
 with a C++ exception specification or <code>%catches</code> as
 described for the <a href="Typemaps.html#throws_typemap">&quot;throws&quot;
 typemap</a>.</p>
<p> Let's try and put all this together by considering the following
 director method:</p>
<div class="code">
<pre>
struct X {
  virtual void doSomething(int index) throw (std::out_of_range);
  ...
};

OR

%catches(std::out_of_range) X::doSomething;
struct X {
  virtual void doSomething(int index);
  ...
};
</pre>
</div>
<p> When combined with the default <code>director:except</code> feature
 and the &quot;directorthrows&quot; typemap above, the resulting code generated in
 the director method after calling up to Java will be:</p>
<div class="code">
<pre>
jthrowable swigerror = jenv-&gt;ExceptionOccurred();
if (swigerror) {
  if (Swig::ExceptionMatches(jenv, swigerror, &quot;java/lang/IndexOutOfBoundsException&quot;)) {
    throw std::out_of_range(Swig::JavaExceptionMessage(jenv, swigerror).message());
  }
  Swig::DirectorException::raise(jenv, swigerror);
}
</pre>
</div>
<p><em> Note: Beware of using exception specifications as the SWIG
 director methods will be generated with the same exception
 specifications and if the director method throws an exception that is
 not specified in the exception specifications list it is likely to
 terminate your program. See the C++ standard for more details. Using
 the %catches feature instead to define the handled exceptions does not
 suffer this potential fate.</em></p>
<p>Because the default code generation maps any unhandled Java
 exceptions to <code>Swig::DirectorException</code>, any director
 methods that have exception specifications may cause program
 termination as this exception class won't be in the exception
 specifications list. You can avoid throwing <tt>Swig::DirectorException</tt>
 by changing the default handling for all methods by adding a <tt>
director:except</tt> feature without any method name. For example, you
 can just ignore them:</p>
<div class="code">
<pre>
%feature(&quot;director:except&quot;) %{
  jthrowable $error = jenv-&gt;ExceptionOccurred();
  if ($error) {
    $directorthrowshandlers
    jenv-&gt;ExceptionClear();
    return $null; // exception is ignored
  }
%}
</pre>
</div>
<p>Alternatively an exception compatible with the existing director
 method exception specifications can be thrown. Assuming that all
 methods allow std::runtime_error to be thrown, the <code>return&nbsp;$null</code>
 line above could be changed to:</p>
<div class="code">
<pre>
  throw std::runtime_error(Swig::JavaExceptionMessage(jenv, $error).message());
</pre>
</div>
<p>In more complex situations, a separate <code>director:except</code>
 feature may need to be attached to specific methods by providing a
 method name to the <tt>director:except</tt> feature.</p>
<p>This is all no doubt quite hard to follow without seeing a full
 example and some code. Below is a complete example demonstrating the
 use of most of the exception customizations one can use, that is,
 &quot;directorthrows&quot; and &quot;throws&quot; typemaps, %exception and %catches. See
 the <a href="#Java_exception_handling">Exception handling with
 %exception and %javaexception</a> section for more on converting C++
 exceptions to Java exceptions. The example also has a user defined C++
 exception class called <tt>MyNS::MyException</tt> and this is wrapped
 as a Java exception. The director class being wrapped is <tt>MyClass</tt>
 and the director method is called <tt>MyClass::dirmethod</tt>. A number
 of <tt>std::cout</tt> calls have been added to help understand code
 flow. You can copy the code below into an interface file and run SWIG
 on it and examine the generated code.<div class="code">
<pre>
%module(directors=&quot;1&quot;) example

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

// Generic catch handler for all wrapped methods
%exception %{
  try {
    $action
  } catch (const std::exception &amp;e) {
    std::cout &lt;&lt; &quot;Generic std::exception catch handler&quot; &lt;&lt; std::endl;
    jclass clazz = jenv-&gt;FindClass(&quot;java/lang/RuntimeException&quot;);
    jenv-&gt;ThrowNew(clazz, e.what()); 
    return $null;
  }
%}

// Expose C++ exception as a Java Exception by changing the Java base class and providing a getMessage()
%typemap(javabase) MyNS::MyException &quot;java.lang.RuntimeException&quot;;
%rename(getMessage) MyNS::MyException::whatsup;

%inline %{
namespace MyNS {
  class MyException {
    std::string msg;
  public:
    MyException(const char *msg) : msg(msg) {}
    const char * whatsup() const { return msg.c_str(); }
  };
}
%}

%typemap(directorthrows) MyNS::MyException %{
  if (Swig::ExceptionMatches(jenv, $error, &quot;$packagepath/MyException&quot;)) {
    std::cout &lt;&lt; &quot;$1_type exception matched (directorthrows typemap)&quot; &lt;&lt; std::endl;
    throw $1_type(Swig::JavaExceptionMessage(jenv, $error).message());
  }
%}

%typemap(throws) MyNS::MyException %{
  std::cout &lt;&lt; &quot;$1_type caught (throws typemap)&quot; &lt;&lt; std::endl;
  jclass excep = jenv-&gt;FindClass(&quot;MyException&quot;);
  if (excep) {
    std::cout &lt;&lt; &quot;$1_type class found (throws typemap)&quot; &lt;&lt; std::endl;
    jenv-&gt;ThrowNew(excep, $1.whatsup());
  }
  return $null;
%}

// These are the exceptions that the director method MyClass::dirmethod will have catch handlers for.
// Note that this is also a virtual method / director method and the C++ exceptions listed can be
// thrown after converting them from Java exceptions.
%catches(MyNS::MyException, Swig::DirectorException) MyClass::dirmethod;

// These are the exceptions that call_dirmethod C++ wrapper will have catch handlers for.
// Note that this is not a virtual method, hence not a director method.
%catches(MyNS::MyException, Swig::DirectorException) call_dirmethod;

%feature(&quot;director&quot;) MyClass;

%feature(&quot;director:except&quot;) MyClass::dirmethod(int x) {
  jthrowable $error = jenv-&gt;ExceptionOccurred();
  if ($error) {
    std::cout &lt;&lt; &quot;Upcall finished, an exception was thrown in Java&quot; &lt;&lt; std::endl;
    $directorthrowshandlers
    std::cout &lt;&lt; &quot;Upcall finished, no exception conversion, throwing DirectorException&quot; &lt;&lt; std::endl;
    Swig::DirectorException::raise(jenv, $error);
  }
}

%inline %{
class MyClass {
public:
  /** Throws either a std::out_of_range or MyException on error */
  virtual void dirmethod(int x) {
    if (x &lt;= 0)
      throw std::out_of_range(&quot;MyClass::dirmethod index is out of range&quot;);
    else if (x == 1)
      throw MyNS::MyException(&quot;MyClass::dirmethod some problem!&quot;);
  }
  virtual ~MyClass() {}
  static void call_dirmethod(MyClass&amp; c, int x) {
    return c.dirmethod(x);
  }
};
%}
</pre>
</div></p>
<p> The generated code for the <tt>call_dirmethod</tt> wrapper contains
 the various exception handlers. The outer exception handler is from the
 <tt>%exception</tt> directive and the others are from the &quot;throws&quot;
 typemaps.</p>
<div class="code">
<pre>
SWIGEXPORT void JNICALL Java_exampleJNI_MyClass_1call_1dirmethod(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jint jarg2) {
  ...
  try {
    try {
      MyClass::call_dirmethod(*arg1,arg2);
    } catch(MyNS::MyException &amp;_e) {
      std::cout &lt;&lt; &quot;MyNS::MyException caught (throws typemap)&quot; &lt;&lt; std::endl;
      jclass excep = jenv-&gt;FindClass(&quot;MyException&quot;);
      if (excep) {
        std::cout &lt;&lt; &quot;MyNS::MyException class found (throws typemap)&quot; &lt;&lt; std::endl;
        jenv-&gt;ThrowNew(excep, (&amp;_e)-&gt;whatsup());
      }
      return ;
      
    } catch(Swig::DirectorException &amp;_e) {
      (&amp;_e)-&gt;throwException(jenv);
      return ; 
    }
  } catch (const std::exception &amp;e) {
    std::cout &lt;&lt; &quot;Generic std::exception catch handler&quot; &lt;&lt; std::endl;
    jclass clazz = jenv-&gt;FindClass(&quot;java/lang/RuntimeException&quot;);
    jenv-&gt;ThrowNew(clazz, e.what()); 
    return ;
  }
</pre>
</div>
<p> The director method calling up to Java contains the exception
 handling code from the &quot;directorthrows&quot; typemaps and <tt>
director:except</tt> feature.</p>
<div class="code">
<pre>
void SwigDirector_MyClass::dirmethod(int x) {
      ... [call up to Java using CallStaticVoidMethod]
      jthrowable swigerror = jenv-&gt;ExceptionOccurred();
      if (swigerror) {
        std::cout &lt;&lt; &quot;Upcall finished, an exception was thrown in Java&quot; &lt;&lt; std::endl;
        
        if (Swig::ExceptionMatches(jenv, swigerror, &quot;MyException&quot;)) {
          std::cout &lt;&lt; &quot;MyNS::MyException exception matched (directorthrows typemap)&quot; &lt;&lt; std::endl;
          throw MyNS::MyException(Swig::JavaExceptionMessage(jenv, swigerror).message());
        }
        
        std::cout &lt;&lt; &quot;Upcall finished, no exception conversion, throwing DirectorException&quot; &lt;&lt; std::endl;
        Swig::DirectorException::raise(jenv, swigerror);
      }
</pre>
</div>
<p> Let's use the following Java class to override the director method.</p>
<div class="code">
<pre>
class DerivedClass extends MyClass {
  @Override
  public void dirmethod(int x) {
    if (x &lt; 0)
      throw new IndexOutOfBoundsException(&quot;Index is negative&quot;);
    else if (x == 0)
      throw new MyException(&quot;MyException: bad dirmethod&quot;);
  }
}
public class runme {
  public static void main(String argv[]) {
    System.loadLibrary(&quot;example&quot;);
    ... code snippets shown below ...
  }
}
</pre>
</div>
<p> Consider the output using the Java code in the four slightly
 different scenarios below.</p>
<p> 1. Non-director C++ class is used, thus, no upcall to a Java
 director method is made. A <tt>std::out_of_range</tt> exception is
 thrown, which is derived from <tt>std::exception</tt>, and hence caught
 by the generic exception handler in the <tt>call_dirmethod</tt>
 wrapper. The Java code snippet and resulting output is:</p>
<div class="code">
<pre>
MyClass.call_dirmethod(new MyClass(), 0);
</pre>
</div><div class="shell">
<pre>
Generic std::exception catch handler
Exception in thread &quot;main&quot; java.lang.RuntimeException: MyClass::dirmethod index is out of range
        at exampleJNI.MyClass_call_dirmethod(Native Method)
        at MyClass.call_dirmethod(MyClass.java:57)
        at runme.main(runme.java:14)
</pre>
</div>
<p> 2. Non-director C++ class again but this time the <tt>
MyNS::MyException</tt> class is thrown and caught:</p>
<div class="code">
<pre>
MyClass.call_dirmethod(new MyClass(), 1);
</pre>
</div><div class="shell">
<pre>
MyNS::MyException caught (throws typemap)
MyNS::MyException class found (throws typemap)
Exception in thread &quot;main&quot; MyException: MyClass::dirmethod some problem!
        at exampleJNI.MyClass_call_dirmethod(Native Method)
        at MyClass.call_dirmethod(MyClass.java:57)
        at runme.main(runme.java:15)
</pre>
</div>
<p> 3. The <tt>DerivedClass</tt> director class is used so the upcall to
 Java occurs, but it throws a Java <tt>MyException</tt>, which gets
 converted into a C++ <tt>MyNS::MyException</tt>, then caught and
 converted back into a Java <tt>MyException</tt>:</p>
<div class="code">
<pre>
MyClass.call_dirmethod(new DerivedClass(), 0);
</pre>
</div><div class="shell">
<pre>
Upcall finished, an exception was thrown in Java
MyNS::MyException exception matched (directorthrows typemap)
MyNS::MyException caught (throws typemap)
MyNS::MyException class found (throws typemap)
Exception in thread &quot;main&quot; MyException: MyException: bad dirmethod
        at exampleJNI.MyClass_call_dirmethod(Native Method)
        at MyClass.call_dirmethod(MyClass.java:57)
        at runme.main(runme.java:16)
</pre>
</div>
<p> 4. The director class is used again, but this time the director
 method throws a Java <tt>IndexOutOfBoundsException</tt> exception which
 is converted into a C++ <tt>Swig::DirectorException</tt>, thrown and
 caught again. This time the original Java exception is extracted from
 the <tt>Swig::DirectorException</tt> and rethrown. Note that this
 approach keeps the stack trace information of the original exception,
 so it has the exact location of where the <tt>IndexOutOfBoundsException</tt>
 exception was thrown. This is arguably an improvement over the approach
 above that converts from a Java excepton to C++ exception and then back
 to a new Java exception, losing the location of the original exception.</p>
<div class="code">
<pre>
MyClass.call_dirmethod(new DerivedClass(), -1);
</pre>
</div><div class="shell">
<pre>
Upcall finished, an exception was thrown in Java
Upcall finished, no exception conversion, throwing DirectorException
Exception in thread &quot;main&quot; java.lang.IndexOutOfBoundsException: Index is negative
        at DerivedClass.dirmethod(runme.java:5)
        at exampleJNI.SwigDirector_MyClass_dirmethod(exampleJNI.java:23)
        at exampleJNI.MyClass_call_dirmethod(Native Method)
        at MyClass.call_dirmethod(MyClass.java:57)
        at runme.main(runme.java:17)
</pre>
</div>
<h2><a name="Java_allprotected">26.6 Accessing protected members</a></h2>
<p> When using directors, the protected virtual methods are also
 wrapped. These methods are wrapped with a protected Java proxy method,
 so the only way that Java code can access these is from within a Java
 class derived from the director class.</p>
<p> Members which are protected and non-virtual can also be accessed
 when using the 'allprotected' mode. The allprotected mode requires
 directors and is turned on by setting the <tt>allprotected</tt> option
 in addition to the <tt>directors</tt> option in the %module directive,
 like this:</p>
<div class="code">
<pre>
%module(directors=&quot;1&quot;, allprotected=&quot;1&quot;) modulename
</pre>
</div>
<p> Protected member variables and methods (both static and non-static)
 will then be wrapped with protected access in the Java proxy class.</p>
<p><b> Note:</b> Neither the directors option nor the allprotected mode
 support types defined with protected scope. This includes any enums or
 typedefs declared in the protected section of the C++ class.</p>
<p> The following simple example is a class with numerous protected
 members, including the constructor and destructor:</p>
<div class="code">
<pre>
%module(directors=&quot;1&quot;, allprotected=&quot;1&quot;) example

%feature(&quot;director&quot;) ProtectedBase;

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

%inline %{

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

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

%}

</pre>
</div>
<p> Note that the <tt>IntegerType</tt> has protected scope and the
 members which use this type must be ignored as they cannot be wrapped.</p>
<p> The proxy methods are protected, so the only way the protected
 members can be accessed is within a class that derives from the
 director class, such as the following:</p>
<div class="code">
<pre>
class MyProtectedBase extends ProtectedBase
{
  public MyProtectedBase() {
  }

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

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

    setStaticMemberVariable(10);
    i = getStaticMemberVariable();
  }
}
</pre>
</div>
<h2><a name="Java_common_customization">26.7 Common customization
 features</a></h2>
<p> An earlier section presented the absolute basics of C/C++ wrapping.
 If you do nothing but feed SWIG a header file, you will get an
 interface that mimics the behavior described. However, sometimes this
 isn't enough to produce a nice module. Certain types of functionality
 might be missing or the interface to certain functions might be
 awkward. This section describes some common SWIG features that are used
 to improve the interface to existing C/C++ code.</p>
<h3><a name="Java_helper_functions">26.7.1 C/C++ helper functions</a></h3>
<p> Sometimes when you create a module, it is missing certain bits of
 functionality. For example, if you had a function like this</p>
<div class="code">
<pre>
typedef struct Image {...};
void set_transform(Image *im, double m[4][4]);
</pre>
</div>
<p> it would be accessible from Java, but there may be no easy way to
 call it. The problem here is that a type wrapper class is generated for
 the two dimensional array parameter so there is no easy way to
 construct and manipulate a suitable <tt>double [4][4]</tt> value. To
 fix this, you can write some extra C helper functions. Just use the <tt>
%inline</tt> directive. For example:</p>
<div class="code">
<pre>
%inline %{
/* Note: double[4][4] is equivalent to a pointer to an array double (*)[4] */
double (*new_mat44())[4] {
  return (double (*)[4]) malloc(16*sizeof(double));
}
void free_mat44(double (*x)[4]) {
  free(x);
}
void mat44_set(double x[4][4], int i, int j, double v) {
  x[i][j] = v;
}
double mat44_get(double x[4][4], int i, int j) {
  return x[i][j];
}
%}
</pre>
</div>
<p> From Java, you could then write code like this:</p>
<div class="code">
<pre>
Image im = new Image();
SWIGTYPE_p_a_4__double a = example.new_mat44();
example.mat44_set(a, 0, 0, 1.0);
example.mat44_set(a, 1, 1, 1.0);
example.mat44_set(a, 2, 2, 1.0);
...
example.set_transform(im, a);
example.free_mat44(a);
</pre>
</div>
<p> Admittedly, this is not the most elegant looking approach. However,
 it works and it wasn't too hard to implement. It is possible to improve
 on this using Java code, typemaps, and other customization features as
 covered in later sections, but sometimes helper functions are a quick
 and easy solution to difficult cases.</p>
<h3><a name="Java_class_extension">26.7.2 Class extension with %extend</a>
</h3>
<p> One of the more interesting features of SWIG is that it can extend
 structures and classes with new methods or constructors. Here is a
 simple example:</p>
<div class="code">
<pre>
%module example
%{
#include &quot;someheader.h&quot;
%}

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

%extend Vector {
  char *toString() {
    static char tmp[1024];
    sprintf(tmp, &quot;Vector(%g, %g, %g)&quot;, $self-&gt;x, $self-&gt;y, $self-&gt;z);
    return tmp;
  }
  Vector(double x, double y, double z) {
    Vector *v = (Vector *) malloc(sizeof(Vector));
    v-&gt;x = x;
    v-&gt;y = y;
    v-&gt;z = z;
    return v;
  }
};
</pre>
</div>
<p> Now, in Java</p>
<div class="code">
<pre>
Vector v = new Vector(2, 3, 4);
System.out.println(v);
</pre>
</div>
<p> will display</p>
<div class="code">
<pre>
Vector(2, 3, 4)
</pre>
</div>
<p> <tt>%extend</tt> works with both C and C++ code. It does not modify
 the underlying object in any way---the extensions only show up in the
 Java interface.</p>
<h3><a name="Java_proxycode">26.7.3 Class extension with %proxycode</a></h3>
<p> The previous section described how to extend a wrapped class with C
 or C++ code. This section describes how to extend a wrapped class with
 Java code instead of C/C++ code. The <tt>%proxycode</tt> directive is
 used and is just a macro for <tt>%insert(&quot;proxycode&quot;)</tt>. The <a href="#SWIG_nn42">
Code insertion block</a> section describes the <tt>%insert</tt>
 directive. The section of code for insertion is &quot;proxycode&quot;, that is,
 the Java proxy class. This directive must hence only be used within the
 scope of a class, otherwise it is silently ignored. There are two
 common ways to get the scope correct.</p>
<p> The first is to use <tt>%proxycode</tt> inside a class that SWIG
 parses, for example a <tt>toString()</tt> method can be added to a C++
 class using pure Java code. A C++ header file can mix C++ and Java code
 inside the C++ class as follows:</p>
<div class="code">
<pre>
// flag.h header file
class Flag {
  bool flag;
public:
  Flag(bool flag) : flag(flag) {}
  bool FetchFlag() { return flag; }
#if defined(SWIG)
%proxycode %{
  public String toString() {
    boolean flag = FetchFlag();
    return Boolean.toString(flag);
  }
%}
#endif
};
</pre>
</div>
<p> and wrapped using:</p>
<div class="code">
<pre>
%{
#include &quot;flag.h&quot;
%}
%include &quot;flag.h&quot;
</pre>
</div>
<p> The second is to use <tt>%proxycode</tt> within <tt>%extend</tt> as
 everything within a <tt>%extend</tt> block is effectively within the
 scope of the class, for example:</p>
<div class="code">
<pre>
// flag.h header file
class Flag {
  bool flag;
public:
  Flag(bool flag) : flag(flag) {}
  bool FetchFlag() { return flag; }
};
</pre>
</div>
<p> and wrapped using:</p>
<div class="code">
<pre>
%{
#include &quot;flag.h&quot;
%}
%include &quot;flag.h&quot;

%extend Flag {
#if defined(SWIG)
%proxycode %{
  public String toString() {
    boolean flag = FetchFlag();
    return Boolean.toString(flag);
  }
%}
#endif
}
</pre>
</div>
<p> There is some very limited support of typemaps within a <tt>
%proxycode</tt> block. A useful trick is to obtain the Java type for a
 given C/C++ type using the <a href="#Typemaps_special_macro_typemap">
$typemap</a> special macro. The following C++ template demonstrates
 this:</p>
<div class="code">
<pre>
%inline %{
template&lt;typename T&gt; struct Value {
  T value;
  Value(const T&amp; val) : value(val) {}
};
%}

%extend Value {
%proxycode %{
  public String toString() {
    // Note template type expansion is supported, so T is expanded to 'unsigned int' in this example
    // and $typemap(jstype, unsigned int) in turn is expanded to 'long'
    $typemap(jstype, T) val = getValue();
    return &quot;$javaclassname value: &quot; + val + &quot; Java type: $typemap(jstype, T) JNI type: $typemap(jni, T)&quot;;
  }
%}
}
%template(ValueUnsignedInt) Value&lt;unsigned int&gt;;
</pre>
</div>
<p> The generated Java contains the expanded special variable and macro
 resulting in Java proxy code:</p>
<div class="code">
<pre>
public class ValueUnsignedInt {
  ...
  public String toString() {
    long val = getValue();
    return &quot;ValueUnsignedInt value: &quot; + val + &quot; Java type: long JNI type: jlong&quot;;
  }

}
</pre>
</div>
<h3><a name="Java_exception_handling">26.7.4 Exception handling with
 %exception and %javaexception</a></h3>
<p> If a C or C++ function throws an error, you may want to convert that
 error into a Java exception. To do this, you can use the <tt>%exception</tt>
 directive. The <tt>%exception</tt> directive simply lets you rewrite
 part of the generated wrapper code to include an error check. It is
 detailed in full in the <a href="#Customization_exception">Exception
 handling with %exception</a> section.</p>
<p> In C, a function often indicates an error by returning a status code
 (a negative number or a NULL pointer perhaps). Here is a simple example
 of how you might handle that:</p>
<div class="code">
<pre>
%exception malloc {
  $action
  if (!result) {
    jclass clazz = (*jenv)-&gt;FindClass(jenv, &quot;java/lang/OutOfMemoryError&quot;);
    (*jenv)-&gt;ThrowNew(jenv, clazz, &quot;Not enough memory&quot;);
    return $null;
  }
}
void *malloc(size_t nbytes);
</pre>
</div>
<p> In Java,</p>
<div class="code">
<pre>
SWIGTYPE_p_void a = example.malloc(2000000000);
</pre>
</div>
<p> will produce a familiar looking Java exception:</p>
<div class="code">
<pre>
Exception in thread &quot;main&quot; java.lang.OutOfMemoryError: Not enough memory
        at exampleJNI.malloc(Native Method)
        at example.malloc(example.java:16)
        at runme.main(runme.java:112)
</pre>
</div>
<p> If a library provides some kind of general error handling framework,
 you can also use that. For example:</p>
<div class="code">
<pre>
%exception malloc {
  $action
  if (err_occurred()) {
    jclass clazz = (*jenv)-&gt;FindClass(jenv, &quot;java/lang/OutOfMemoryError&quot;);
    (*jenv)-&gt;ThrowNew(jenv, clazz, &quot;Not enough memory&quot;);
    return $null;
  }
}
void *malloc(size_t nbytes);
</pre>
</div>
<p> If no declaration name is given to <tt>%exception</tt>, it is
 applied to all wrapper functions. The <tt>$action</tt> is a SWIG
 special variable and is replaced by the C/C++ function call being
 wrapped. The <tt>return $null;</tt> handles all native method return
 types, namely those that have a void return and those that do not. This
 is useful for typemaps that will be used in native method returning all
 return types. See the section on <a href="#Java_special_variables">Java
 special variables</a> for further explanation.</p>
<p> C++ exceptions are also easy to handle. We can catch the C++
 exception and rethrow it as a Java exception like this:</p>
<div class="code">
<pre>
%exception getitem {
  try {
    $action
  } catch (std::out_of_range &amp;e) {
    jclass clazz = jenv-&gt;FindClass(&quot;java/lang/Exception&quot;);
    jenv-&gt;ThrowNew(clazz, &quot;Range error&quot;);
    return $null;
  }
}

class FooClass {
  public:
    FooClass *getitem(int index);      // Might throw std::out_of_range exception
    ...
};
</pre>
</div>
<p> In the example above, <tt>java.lang.Exception</tt> is a checked
 exception class and so ought to be declared in the throws clause of <tt>
getitem</tt>. Classes can be specified for adding to the throws clause
 using <tt>%javaexception(classes)</tt> instead of <tt>%exception</tt>,
 where <tt>classes</tt> is a string containing one or more comma
 separated Java classes. The <tt>%clearjavaexception</tt> feature is the
 equivalent to <tt>%clearexception</tt> and clears previously declared
 exception handlers. The <tt>%nojavaexception</tt> feature is the
 equivalent to <tt>%noexception</tt> and disables the exception handler.
 See <a href="#Customization_clearing_features">Clearing features</a>
 for the difference on disabling and clearing features.</p>
<div class="code">
<pre>
%javaexception(&quot;java.lang.Exception&quot;) getitem {
  try {
    $action
  } catch (std::out_of_range &amp;e) {
    jclass clazz = jenv-&gt;FindClass(&quot;java/lang/Exception&quot;);
    jenv-&gt;ThrowNew(clazz, &quot;Range error&quot;);
    return $null;
  }
}

class FooClass {
public:
  FooClass *getitem(int index);      // Might throw std::out_of_range exception
  ...
};
</pre>
</div>
<p> The generated proxy method now generates a throws clause containing <tt>
java.lang.Exception</tt>:</p>
<div class="code">
<pre>
public class FooClass {
  ...
  public FooClass getitem(int index) throws java.lang.Exception { ... }
  ...
}
</pre>
</div>
<p> The examples above first use the C JNI calling syntax then the C++
 JNI calling syntax. The C++ calling syntax will not compile as C and
 also vice versa. It is however possible to write JNI calls which will
 compile under both C and C++ and is covered in the <a href="#Java_typemaps_for_c_and_cpp">
Typemaps for both C and C++ compilation</a> section.</p>
<p> The language-independent <tt>exception.i</tt> library file can also
 be used to raise exceptions. See the <a href="#Library">SWIG Library</a>
 chapter. The typemap example <a href="#Java_exception_typemap">Handling
 C++ exception specifications as Java exceptions</a> provides further
 exception handling capabilities.</p>
<h3><a name="Java_method_access">26.7.5 Method access with
 %javamethodmodifiers</a></h3>
<p> A Java feature called <tt>%javamethodmodifiers</tt> can be used to
 change the method modifiers from the default <tt>public</tt>. It
 applies to both module class methods and proxy class methods. For
 example:</p>
<div class="code">
<pre>
%javamethodmodifiers protect_me() &quot;protected&quot;;
void protect_me();
</pre>
</div>
<p> Will produce the method in the module class with protected access.</p>
<div class="code">
<pre>
protected static void protect_me() {
  exampleJNI.protect_me();
}
</pre>
</div>
<h2><a name="Java_tips_techniques">26.8 Tips and techniques</a></h2>
<p> Although SWIG is largely automatic, there are certain types of
 wrapping problems that require additional user input. Examples include
 dealing with output parameters, strings and arrays. This chapter
 discusses the common techniques for solving these problems.</p>
<h3><a name="Java_input_output_parameters">26.8.1 Input and output
 parameters using primitive pointers and references</a></h3>
<p> A common problem in some C programs is handling parameters passed as
 simple pointers or references. For example:</p>
<div class="code">
<pre>
void add(int x, int y, int *result) {
  *result = x + y;
}
</pre>
</div>
<p> or perhaps</p>
<div class="code">
<pre>
int sub(int *x, int *y) {
  return *x-*y;
}
</pre>
</div>
<p> The <tt>typemaps.i</tt> library file will help in these situations.
 For example:</p>
<div class="code">
<pre>
%module example
%include &quot;typemaps.i&quot;

void add(int, int, int *OUTPUT);
int  sub(int *INPUT, int *INPUT);
</pre>
</div>
<p> In Java, this allows you to pass simple values. For example:</p>
<div class="code">
<pre>
int result = example.sub(7, 4);
System.out.println(&quot;7 - 4 = &quot; + result);
int[] sum = {0};
example.add(3, 4, sum);
System.out.println(&quot;3 + 4 = &quot; + sum[0]);
</pre>
</div>
<p> Which will display:</p>
<div class="code">
<pre>
7 - 4 = 3
3 + 4 = 7
</pre>
</div>
<p> Notice how the <tt>INPUT</tt> parameters allow integer values to be
 passed instead of pointers and how the <tt>OUTPUT</tt> parameter will
 return the result in the first element of the integer array.</p>
<p> If you don't want to use the names <tt>INPUT</tt> or <tt>OUTPUT</tt>
, use the <tt>%apply</tt> directive. For example:</p>
<div class="code">
<pre>
%module example
%include &quot;typemaps.i&quot;

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

void add(int x, int y, int *result);
int  sub(int *x, int *y);
</pre>
</div>
<p> If a function mutates one of its parameters like this,</p>
<div class="code">
<pre>
void negate(int *x) {
  *x = -(*x);
}
</pre>
</div>
<p> you can use <tt>INOUT</tt> like this:</p>
<div class="code">
<pre>
%include &quot;typemaps.i&quot;
...
void negate(int *INOUT);
</pre>
</div>
<p> In Java, the input parameter is the first element in a 1 element
 array and is replaced by the output of the function. For example:</p>
<div class="code">
<pre>
int[] neg = {3};
example.negate(neg);
System.out.println(&quot;Negative of 3 = &quot; + neg[0]);
</pre>
</div>
<p> And no prizes for guessing the output:</p>
<div class="code">
<pre>
Negative of 3 = -3
</pre>
</div>
<p> These typemaps can also be applied to C++ references. The above
 examples would work the same if they had been defined using references
 instead of pointers. For example, the Java code to use the <tt>negate</tt>
 function would be the same if it were defined either as it is above:</p>
<div class="code">
<pre>
void negate(int *INOUT);
</pre>
</div>
<p> or using a reference:</p>
<div class="code">
<pre>
void negate(int &amp;INOUT);
</pre>
</div>
<p> Note: Since most Java primitive types are immutable and are passed
 by value, it is not possible to perform in-place modification of a type
 passed as a parameter.</p>
<p> Be aware that the primary purpose of the <tt>typemaps.i</tt> file is
 to support primitive datatypes. Writing a function like this</p>
<div class="code">
<pre>
void foo(Bar *OUTPUT);
</pre>
</div>
<p> will not have the intended effect since <tt>typemaps.i</tt> does not
 define an OUTPUT rule for <tt>Bar</tt>.</p>
<h3><a name="Java_simple_pointers">26.8.2 Simple pointers</a></h3>
<p> If you must work with simple pointers such as <tt>int *</tt> or <tt>
double *</tt> another approach to using <tt>typemaps.i</tt> is to use
 the <tt>cpointer.i</tt> pointer library file. For example:</p>
<div class="code">
<pre>
%module example
%include &quot;cpointer.i&quot;

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

%pointer_functions(int, intp);
</pre>
</div>
<p> The <tt>%pointer_functions(type, name)</tt> macro generates five
 helper functions that can be used to create, destroy, copy, assign, and
 dereference a pointer. In this case, the functions are as follows:</p>
<div class="code">
<pre>
int  *new_intp();
int  *copy_intp(int *x);
void  delete_intp(int *x);
void  intp_assign(int *x, int value);
int   intp_value(int *x);
</pre>
</div>
<p> In Java, you would use the functions like this:</p>
<div class="code">
<pre>
SWIGTYPE_p_int intPtr = example.new_intp();
example.add(3, 4, intPtr);
int result = example.intp_value(intPtr);
System.out.println(&quot;3 + 4 = &quot; + result);
</pre>
</div>
<p> If you replace <tt>%pointer_functions(int, intp)</tt> by <tt>
%pointer_class(int, intp)</tt>, the interface is more class-like.</p>
<div class="code">
<pre>
intp intPtr = new intp();
example.add(3, 4, intPtr.cast());
int result = intPtr.value();
System.out.println(&quot;3 + 4 = &quot; + result);
</pre>
</div>
<p> See the <a href="#Library">SWIG Library</a> chapter for further
 details.</p>
<h3><a name="Java_c_arrays">26.8.3 Wrapping C arrays with Java arrays</a>
</h3>
<p> SWIG can wrap arrays in a more natural Java manner than the default
 by using the <tt>arrays_java.i</tt> library file. Let's consider an
 example:</p>
<div class="code">
<pre>
%include &quot;arrays_java.i&quot;;
int array[4];
void populate(int x[]) {
  int i;
  for (i=0; i&lt;4; i++)
    x[i] = 100 + i;
}
</pre>
</div>
<p> These one dimensional arrays can then be used as if they were Java
 arrays:</p>
<div class="code">
<pre>
int[] array = new int[4];
example.populate(array);

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

example.setArray(array);

int[] global_array = example.getArray();

System.out.print(&quot;\nglobal_array: &quot;);
for (int i=0; i&lt;array.length; i++)
  System.out.print(global_array[i] + &quot; &quot;);
</pre>
</div>
<p> Java arrays are always passed by reference, so any changes a
 function makes to the array will be seen by the calling function. Here
 is the output after running this code:</p>
<div class="code">
<pre>
array: 100 101 102 103
global_array: 100 101 102 103
</pre>
</div>
<p> Note that for assigning array variables the length of the C variable
 is used, so it is possible to use a Java array that is bigger than the
 C code will cope with. Only the number of elements in the C array will
 be used. However, if the Java array is not large enough then you are
 likely to get a segmentation fault or access violation, just like you
 would in C. When arrays are used in functions like <tt>populate</tt>,
 the size of the C array passed to the function is determined by the
 size of the Java array.</p>
<p> Please be aware that the typemaps in this library are not efficient
 as all the elements are copied from the Java array to a C array
 whenever the array is passed to and from JNI code. There is an
 alternative approach using the SWIG array library and this is covered
 in the next section.</p>
<h3><a name="Java_unbounded_c_arrays">26.8.4 Unbounded C Arrays</a></h3>
<p> Sometimes a C function expects an array to be passed as a pointer.
 For example,</p>
<div class="code">
<pre>
int sumitems(int *first, int nitems) {
  int i, sum = 0;
  for (i = 0; i &lt; nitems; i++) {
    sum += first[i];
  }
  return sum;
}
</pre>
</div>
<p> One of the ways to wrap this is to apply the Java array typemaps
 that come in the <tt>arrays_java.i</tt> library file:</p>
<div class="code">
<pre>
%include &quot;arrays_java.i&quot;
%apply int[] {int *};
</pre>
</div>
<p> The <tt>ANY</tt> size will ensure the typemap is applied to arrays
 of all sizes. You could narrow the typemap matching rules by specifying
 a particular array size. Now you can use a pure Java array and pass it
 to the C code:</p>
<div class="code">
<pre>
int[] array = new int[10000000];          // Array of 10-million integers
for (int i=0; i&lt;array.length; i++) {      // Set some values
  array[i] = i;
}
int sum = example.sumitems(array, 10000);
System.out.println(&quot;Sum = &quot; + sum);
</pre>
</div>
<p> and the sum would be displayed:</p>
<div class="code">
<pre>
Sum = 49995000
</pre>
</div>
<p> This approach is probably the most natural way to use arrays.
 However, it suffers from performance problems when using large arrays
 as a lot of copying of the elements occurs in transferring the array
 from the Java world to the C++ world. An alternative approach to using
 Java arrays for C arrays is to use an alternative SWIG library file <tt>
carrays.i</tt>. This approach can be more efficient for large arrays as
 the array is accessed one element at a time. For example:</p>
<div class="code">
<pre>
%include &quot;carrays.i&quot;
%array_functions(int, intArray);
</pre>
</div>
<p> The <tt>%array_functions(type, name)</tt> macro generates four
 helper functions that can be used to create and destroy arrays and
 operate on elements. In this case, the functions are as follows:</p>
<div class="code">
<pre>
int *new_intArray(int nelements);
void delete_intArray(int *x);
int intArray_getitem(int *x, int index);
void intArray_setitem(int *x, int index, int value);
</pre>
</div>
<p> In Java, you would use the functions like this:</p>
<div class="code">
<pre>
SWIGTYPE_p_int array = example.new_intArray(10000000);  // Array of 10-million integers
for (int i=0; i&lt;10000; i++) {                           // Set some values
  example.intArray_setitem(array, i, i);
}
int sum = example.sumitems(array, 10000);
System.out.println(&quot;Sum = &quot; + sum);
</pre>
</div>
<p> If you replace <tt>%array_functions(int, intp)</tt> by <tt>
%array_class(int, intp)</tt>, the interface is more class-like and a
 couple more helper functions are available for casting between the
 array and the type wrapper class.</p>
<div class="code">
<pre>
%include &quot;carrays.i&quot;
%array_class(int, intArray);
</pre>
</div>
<p> The <tt>%array_class(type, name)</tt> macro creates wrappers for an
 unbounded array object that can be passed around as a simple pointer
 like <tt>int *</tt> or <tt>double *</tt>. For instance, you will be
 able to do this in Java:</p>
<div class="code">
<pre>
intArray array = new intArray(10000000);  // Array of 10-million integers
for (int i=0; i&lt;10000; i++) {             // Set some values
  array.setitem(i, i);
}
int sum = example.sumitems(array.cast(), 10000);
System.out.println(&quot;Sum = &quot; + sum);
</pre>
</div>
<p> The array &quot;object&quot; created by <tt>%array_class()</tt> does not
 encapsulate pointers inside a special array object. In fact, there is
 no bounds checking or safety of any kind (just like in C). Because of
 this, the arrays created by this library are extremely low-level
 indeed. You can't iterate over them nor can you even query their
 length. In fact, any valid memory address can be accessed if you want
 (negative indices, indices beyond the end of the array, etc.). Needless
 to say, this approach is not going to suit all applications. On the
 other hand, this low-level approach is extremely efficient and well
 suited for applications in which you need to create buffers, package
 binary data, etc.</p>
<h3><a name="Java_binary_char">26.8.5 Binary data vs Strings</a></h3>
<p> By default SWIG handles <tt>char *</tt> as a string but there is a
 handy multi-argument typemap available as mentioned in <a href="#Library_nn10">
Passing binary data</a>. The following simple example demonstrates using
 a byte array instead of passing the default string type and length to
 the wrapped function.</p>
<div class="code">
<pre>
%apply (char *STRING, size_t LENGTH) { (const char data[], size_t len) }
%inline %{
void binaryChar1(const char data[], size_t len) {
  printf(&quot;len: %d data: &quot;, len);
  for (size_t i=0; i&lt;len; ++i)
    printf(&quot;%x &quot;, data[i]);
  printf(&quot;\n&quot;);
}
%}
</pre>
</div>
<p> Calling from Java requires just the byte array to be passed in as
 the multi-argument typemap being applied reduces the number of
 arguments in the target language to one, from the original two:</p>
<div class="code">
<pre>
byte[] data = &quot;hi\0jk&quot;.getBytes();
example.binaryChar1(data);     
</pre>
</div>
<p> resulting in the output</p>
<div class="code">
<pre>
$ java runme
len: 5 data: 68 69 0 6a 6b
</pre>
</div>
<h3><a name="Java_heap_allocations">26.8.6 Overriding new and delete to
 allocate from Java heap</a></h3>
<p> Unlike some languages supported by SWIG, Java has a true garbage
 collection subsystem. Other languages will free SWIG wrapped objects
 when their reference count reaches zero. Java only schedules these
 objects for finalization, which may not occur for some time. Because
 SWIG objects are allocated on the C heap, Java users may find the JVM
 memory use quickly exceeds the assigned limits, as memory fills with
 unfinalized proxy objects. Forcing garbage collection is clearly an
 undesirable solution.</p>
<p> An elegant fix for C++ users is to override new and delete using the
 following code (here shown included in a SWIG interface file)</p>
<div class="code">
<pre>
/* File: java_heap.i */
%module test
%{
#include &lt;stdexcept&gt;
#include &quot;jni.h&quot;

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

static JavaVM *cached_jvm = 0;

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

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

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

void operator delete(void *v) {
  if (v != 0) {
    void *buffer = static_cast&lt;void *&gt;( static_cast&lt;char *&gt;(v) - sizeof(Jalloc));
    Jalloc *pJalloc = static_cast&lt;Jalloc *&gt;(buffer);
    if (pJalloc-&gt;ref) {
      JNIEnv *env = JNU_GetEnv();
      env-&gt;DeleteGlobalRef(pJalloc-&gt;ref);
      env-&gt;ReleaseByteArrayElements(pJalloc-&gt;jba, static_cast&lt;jbyte *&gt;(buffer), 0);
    }
    else {
      free(buffer);
    }
  }
}
%}
...
</pre>
</div>
<p> This code caches the Java environment during initialization, and
 when new is called, a Java ByteArray is allocated to provide the SWIG
 objects with space in the Java heap. This has the combined effect of
 re-asserting the Java virtual machine's limit on memory allocation, and
 puts additional pressure on the garbage collection system to run more
 frequently. This code is made slightly more complicated because
 allowances must be made if new is called before the JNI_OnLoad is
 executed. This can happen during static class initialization, for
 example.</p>
<p> Unfortunately, because most Java implementations call malloc and
 free, this solution will not work for C wrapped structures. However,
 you are free to make functions that allocate and free memory from the
 Java heap using this model and use these functions in place of malloc
 and free in your own code.</p>
<h2><a name="Java_typemaps">26.9 Java typemaps</a></h2>
<p> This section describes how you can modify SWIG's default wrapping
 behavior for various C/C++ datatypes using the <tt>%typemap</tt>
 directive. You are advised to be familiar with the material in the &quot;<a href="#Typemaps">
Typemaps</a>&quot; 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="https://www.oracle.com/technetwork/java/index.html">
the Java web site</a> or from a good JNI book. The following two books
 are recommended:</p>
<ul>
<li> Title: 'Essential JNI: Java Native Interface.' Author: Rob Gordon.
 Publisher: Prentice Hall. ISBN: 0-13-679895-0.</li>
<li> Title: 'The Java Native Interface: Programmer's Guide and
 Specification.' Author: Sheng Liang. Publisher: Addison-Wesley. ISBN:
 0-201-32577-2. Also available <a href="http://java.sun.com/docs/books/jni">
online</a> at the Sun Developer Network.</li>
</ul>
<p> Before proceeding, it should be stressed that typemaps are not a
 required part of using SWIG---the default wrapping behavior is enough
 in most cases. Typemaps are only used if you want to change some aspect
 of the generated code.</p>
<h3><a name="Java_default_primitive_type_mappings">26.9.1 Default
 primitive type mappings</a></h3>
<p> The following table lists the default type mapping from Java to
 C/C++.</p>
<table BORDER summary="Default primitive type mappings">
<tr><td><b>C/C++ type</b></td><td><b>Java type</b></td><td><b>JNI type</b>
</td></tr>
<tr><td>bool
<br> const bool &amp;</td><td>boolean</td><td>jboolean</td></tr>
<tr><td>char
<br>const char &amp;</td><td>char</td><td>jchar</td></tr>
<tr><td>signed char
<br>const signed char &amp;</td><td>byte</td><td>jbyte</td></tr>
<tr><td>unsigned char
<br>const unsigned char &amp;</td><td>short</td><td>jshort</td></tr>
<tr><td>short
<br>const short &amp;</td><td>short</td><td>jshort</td></tr>
<tr><td>unsigned short
<br> const unsigned short &amp;</td><td>int</td><td>jint</td></tr>
<tr><td>int
<br> const int &amp;</td><td>int</td><td>jint</td></tr>
<tr><td>unsigned int
<br> const unsigned int &amp;</td><td>long</td><td>jlong</td></tr>
<tr><td>long
<br>const long &amp;</td><td>int</td><td>jint</td></tr>
<tr><td>unsigned long
<br>const unsigned long &amp;</td><td>long</td><td>jlong</td></tr>
<tr><td>long long
<br> const long long &amp;</td><td>long</td><td>jlong</td></tr>
<tr><td>unsigned long long
<br>const unsigned long long &amp;</td><td>java.math.BigInteger</td><td>
jobject</td></tr>
<tr><td>float
<br>const float &amp;</td><td>float</td><td>jfloat</td></tr>
<tr><td>double
<br> const double &amp;</td><td>double</td><td>jdouble</td></tr>
<tr><td>char *
<br>char []</td><td>String</td><td>jstring</td></tr>
</table>
<p> Note that SWIG wraps the C <tt>char</tt> type as a character.
 Pointers and arrays of this type are wrapped as strings. The <tt>signed
 char</tt> type can be used if you want to treat <tt>char</tt> as a
 signed number rather than a character. Also note that all const
 references to primitive types are treated as if they are passed by
 value.</p>
<p> Given the following C function:</p>
<div class="code">
<pre>
void func(unsigned short a, char *b, const long &amp;c, unsigned long long d);
</pre>
</div>
<p> The module class method would be:</p>
<div class="code">
<pre>
public static void func(int a, String b, int c, java.math.BigInteger d) {...}
</pre>
</div>
<p> The intermediary JNI class would use the same types:</p>
<div class="code">
<pre>
public final static native void func(int jarg1, String jarg2, int jarg3,
                                     java.math.BigInteger jarg4);
</pre>
</div>
<p> and the JNI function would look like this:</p>
<div class="code">
<pre>
SWIGEXPORT void JNICALL Java_exampleJNI_func(JNIEnv *jenv, jclass jcls,
                jint jarg1, jstring jarg2, jint jarg3, jobject jarg4) {...}
</pre>
</div>
<p> The mappings for C <tt>int</tt> and C <tt>long</tt> are appropriate
 for 32 bit applications which are used in the 32 bit JVMs. There is no
 perfect mapping between Java and C as Java doesn't support all the
 unsigned C data types. However, the mappings allow the full range of
 values for each C type from Java.</p>
<h3><a name="Java_default_non_primitive_typemaps">26.9.2 Default
 typemaps for non-primitive types</a></h3>
<p> The previous section covered the primitive type mappings.
 Non-primitive types such as classes and structs are mapped using
 pointers on the C/C++ side and storing the pointer into a Java <tt>long</tt>
 variable which is held by the proxy class or type wrapper class. This
 applies whether the type is marshalled as a pointer, by reference or by
 value. It also applies for any unknown/incomplete types which use type
 wrapper classes.</p>
<p> So in summary, the C/C++ pointer to non-primitive types is cast into
 the 64 bit Java <tt>long</tt> type and therefore the JNI type is a <tt>
jlong</tt>. The Java type is either the proxy class or type wrapper
 class.</p>
<h3><a name="Java_jvm64">26.9.3 Sixty four bit JVMs</a></h3>
<p> If you are using a 64 bit JVM you may have to override the C long,
 but probably not C int default mappings. Mappings will be system
 dependent, for example long will need remapping on Unix LP64 systems
 (long, pointer 64 bits, int 32 bits), but not on Microsoft 64 bit
 Windows which will be using a P64 IL32 (pointer 64 bits and int, long
 32 bits) model. This may be automated in a future version of SWIG. Note
 that the Java write once run anywhere philosophy holds true for all
 pure Java code when moving to a 64 bit JVM. Unfortunately it won't of
 course hold true for JNI code.</p>
<h3><a name="Java_what_is_typemap">26.9.4 What is a typemap?</a></h3>
<p> A typemap is nothing more than a code generation rule that is
 attached to a specific C datatype. For example, to convert integers
 from Java to C, you might define a typemap like this:</p>
<div class="code">
<pre>
%module example

%typemap(in) int {
  $1 = $input;
  printf(&quot;Received an integer : %d\n&quot;,  $1);
}
%inline %{
extern int fact(int nonnegative);
%}
</pre>
</div>
<p> Typemaps are always associated with some specific aspect of code
 generation. In this case, the &quot;in&quot; method refers to the conversion of
 input arguments to C/C++. The datatype <tt>int</tt> is the datatype to
 which the typemap will be applied. The supplied C code is used to
 convert values. In this code a number of special variables prefaced by
 a <tt>$</tt> are used. The <tt>$1</tt> variable is a placeholder for a
 local variable of type <tt>int</tt>. The <tt>$input</tt> variable
 contains the Java data, the JNI <tt>jint</tt> in this case.</p>
<p> When this example is compiled into a Java module, it can be used as
 follows:</p>
<div class="code">
<pre>
System.out.println(example.fact(6));
</pre>
</div>
<p> and the output will be:</p>
<div class="code">
<pre>
Received an integer : 6
720
</pre>
</div>
<p> In this example, the typemap is applied to all occurrences of the <tt>
int</tt> datatype. You can refine this by supplying an optional
 parameter name. For example:</p>
<div class="code">
<pre>
%module example

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

%inline %{
extern int fact(int nonnegative);
%}
</pre>
</div>
<p> In this case, the typemap code is only attached to arguments that
 exactly match <tt>int nonnegative</tt>.</p>
<p> The application of a typemap to specific datatypes and argument
 names involves more than simple text-matching--typemaps are fully
 integrated into the SWIG C++ type-system. When you define a typemap for
 <tt>int</tt>, that typemap applies to <tt>int</tt> and qualified
 variations such as <tt>const int</tt>. In addition, the typemap system
 follows <tt>typedef</tt> declarations. For example:</p>
<div class="code">
<pre>
%typemap(in) int nonnegative {
  $1 = $input;
  printf(&quot;Received an integer : %d\n&quot;,  $1);
}
%inline %{
typedef int Integer;
extern int fact(Integer nonnegative);    // Above typemap is applied
%}
</pre>
</div>
<p> However, the matching of <tt>typedef</tt> only occurs in one
 direction. If you defined a typemap for <tt>Integer</tt>, it is not
 applied to arguments of type <tt>int</tt>.</p>
<p> Typemaps can also be defined for groups of consecutive arguments.
 For example:</p>
<div class="code">
<pre>
%typemap(in) (char *str, int len) {
...
};

int count(char c, char *str, int len);
</pre>
</div>
<p> When a multi-argument typemap is defined, the arguments are always
 handled as a single Java parameter. This allows the function to be used
 like this (notice how the length parameter is omitted):</p>
<div class="code">
<pre>
int c = example.count('e', &quot;Hello World&quot;);
</pre>
</div>
<h3><a name="Java_typemaps_c_to_java_types">26.9.5 Typemaps for mapping
 C/C++ types to Java types</a></h3>
<p> The typemaps available to the Java module include the common
 typemaps listed in the main typemaps section. There are a number of
 additional typemaps which are necessary for using SWIG with Java. The
 most important of these implement the mapping of C/C++ types to Java
 types:</p>
<br> &nbsp;
<table BORDER summary="Typemap mappings for C/C++ types to Java types">
<tr><td><b>Typemap</b></td><td><b>Description</b></td></tr>
<tr><td>jni</td><td>JNI C types. These provide the default mapping of
 types from C/C++ to JNI for use in the JNI (C/C++) code.</td></tr>
<tr><td>jtype</td><td>Java intermediary types. These provide the default
 mapping of types from C/C++ to Java for use in the native functions in
 the intermediary JNI class. The type must be the equivalent Java type
 for the JNI C type specified in the &quot;jni&quot; 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 &quot;jstype&quot;
 typemap) to the type used in the Java intermediary JNI class (as
 specified in the &quot;jtype&quot; 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 &quot;jtype&quot; typemap) to the Java type used
 in the Java module class, proxy classes and type wrapper classes (as
 specified in the &quot;jstype&quot; typemap). In other words the typemap provides
 the conversion from the native method call return type.</td></tr>
<tr><td>jboxtype</td><td>Java boxed type. These are Java code typemaps
 to provide the Java boxed type, such as, <tt>Integer</tt> for C type <tt>
int</tt>. As autoboxing is only relevant to the Java primitive types,
 these are only provided for the C types that map to Java primitive
 types. This typemap is usually only used by C++ STL container wrappers
 that are wrapped by Java generic types as the boxed type must be used
 instead of the unboxed/primitive type when declaring a Java generic
 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 &quot;jtype&quot;
 typemap) to the Java type used in the Java module class, proxy classes
 and type wrapper classes (as specified in the &quot;jstype&quot; 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 &quot;jstype&quot; typemap) to the type used in the Java
 intermediary JNI class (as specified in the &quot;jtype&quot; typemap). This
 typemap provides the conversion for the return type in the director
 methods when returning from the C++ to Java upcall. See <a href="#Java_directors_typemaps">
Director typemaps</a>.</td></tr>
<tr><td>directorin</td><td>Conversion from C++ type to jni type for
 director methods. These are C++ typemaps which convert the parameters
 used in the C++ director method to the appropriate JNI intermediary
 type. The conversion is done in JNI code prior to calling the Java
 function from the JNI code. See <a href="#Java_directors_typemaps">
Director typemaps</a>.</td></tr>
<tr><td>directorout</td><td>Conversion from jni type to C++ type for
 director methods. These are C++ typemaps which convert the JNI return
 type used in the C++ director method to the appropriate C++ return
 type. The conversion is done in JNI code after calling the Java
 function from the JNI code. See <a href="#Java_directors_typemaps">
Director typemaps</a>.</td></tr>
</table>
<p> If you are writing your own typemaps to handle a particular type,
 you will normally have to write a collection of them. The default
 typemaps are in &quot;<tt>java.swg</tt>&quot; and so might be a good place for
 finding typemaps to base any new ones on.</p>
<p> The &quot;jni&quot;, &quot;jtype&quot; and &quot;jstype&quot; typemaps are usually defined
 together to handle the Java to C/C++ type mapping. An &quot;in&quot; typemap
 should be accompanied by a &quot;javain&quot; typemap and likewise an &quot;out&quot;
 typemap by a &quot;javaout&quot; typemap. If an &quot;in&quot; typemap is written, a
 &quot;freearg&quot; and &quot;argout&quot; typemap may also need to be written as some
 types have a default &quot;freearg&quot; and/or &quot;argout&quot; typemap which may need
 overriding. The &quot;freearg&quot; typemap sometimes releases memory allocated
 by the &quot;in&quot; typemap. The &quot;argout&quot; typemap sometimes sets values in
 function parameters which are passed by reference in Java.</p>
<p> Note that the &quot;in&quot; typemap marshals the JNI type held in the &quot;jni&quot;
 typemap to the real C/C++ type and for the opposite direction, the
 &quot;out&quot; typemap marshals the real C/C++ type to the JNI type held in the
 &quot;jni&quot; typemap. For <a href="#Java_default_non_primitive_typemaps">
non-primitive types</a> the &quot;in&quot; and &quot;out&quot; typemaps are responsible for
 casting between the C/C++ pointer and the 64 bit <tt>jlong</tt> type.
 There is no portable way to cast a pointer into a 64 bit integer type
 and the approach taken by SWIG is mostly portable, but breaks C/C++
 aliasing rules. In summary, these rules state that a pointer to any
 type must never be dereferenced by a pointer to any other incompatible
 type. The following code snippet might aid in understand aliasing rules
 better:</p>
<div class="code">
<pre>
short a;
short* pa = 0;
int i = 0x1234;

a = (short)i;    /* okay */
a = *(short*)&amp;i; /* breaks aliasing rules */
</pre>
</div>
<p> An email posting, <a href="http://mail-index.netbsd.org/tech-kern/2003/08/11/0001.html">
Aliasing, pointer casts and gcc 3.3</a> elaborates further on the
 subject. In SWIG, the &quot;in&quot; and &quot;out&quot; typemaps for pointers are
 typically</p>
<div class="code">
<pre>
%typemap(in) struct Foo * %{
  $1 = *(struct Foo **)&amp;$input; /* cast jlong into C ptr */
%}
%typemap(out) struct Bar * %{
  *(struct Bar **)&amp;$result = $1; /* cast C ptr into jlong */
%}
struct Bar {...};
struct Foo {...};
struct Bar * FooBar(struct Foo *f);
</pre>
</div>
<p> resulting in the following code which breaks the aliasing rules:</p>
<div class="code">
<pre>
SWIGEXPORT jlong JNICALL Java_exampleJNI_FooBar(JNIEnv *jenv, jclass jcls,
                                                jlong jarg1, jobject jarg1_) {
  jlong jresult = 0 ;
  struct Foo *arg1 = (struct Foo *) 0 ;
  struct Bar *result = 0 ;
  
  (void)jenv;
  (void)jcls;
  (void)jarg1_;
  arg1 = *(struct Foo **)&amp;jarg1; 
  result = (struct Bar *)FooBar(arg1);
  *(struct Bar **)&amp;jresult = result; 
  return jresult;
}
</pre>
</div>
<p> If you are using gcc as your C compiler, you might get a
 &quot;dereferencing type-punned pointer will break strict-aliasing rules&quot;
 warning about this. Please see <a href="#Java_compiling_dynamic">
Compiling a dynamic module</a> to avoid runtime problems with these
 strict aliasing rules.</p>
<p> The default code generated by SWIG for the Java module comes from
 the typemaps in the &quot;<tt>java.swg</tt>&quot; library file which implements
 the <a href="#Java_default_primitive_type_mappings">Default primitive
 type mappings</a> and <a href="#Java_default_non_primitive_typemaps">
Default typemaps for non-primitive types</a> covered earlier. There are
 other type mapping typemaps in the Java library. These are listed
 below:</p>
<br> &nbsp;
<table BORDER summary="Java library typemap mappings">
<tr VALIGN="TOP"><td><b>C Type</b></td><td><b>Typemap</b></td><td><b>
File</b></td><td><b>Kind</b></td><td><b>Java Type</b></td><td><b>
Function</b></td></tr>
<tr><td>primitive pointers and references</td><td>INPUT</td><td>
typemaps.i</td><td>input</td><td>Java basic types</td><td>Allows values
 to be used for C functions taking pointers for data input.
<tr><td>primitive pointers and references</td><td>OUTPUT</td><td>
typemaps.i</td><td>output</td><td>Java basic type arrays</td><td>Allows
 values held within an array to be used for C functions taking pointers
 for data output.
<tr><td>primitive pointers and references</td><td>INOUT</td><td>
typemaps.i</td><td>input
<br>output</td><td>Java basic type arrays</td><td>Allows values held
 within an array to be used for C functions taking pointers for data
 input and output.
<tr><td>string
<br> wstring</td><td>[unnamed]</td><td>std_string.i</td><td>input
<br> output</td><td>String</td><td>Use for std::string mapping to Java
 String.</td></tr>
<tr><td>arrays of primitive types</td><td>[unnamed]</td><td>
arrays_java.i</td><td>input
<br> output</td><td>arrays of primitive Java types</td><td>Use for
 mapping C arrays to Java arrays.</td></tr>
<tr><td>arrays of classes/structs/unions</td><td>JAVA_ARRAYSOFCLASSES
 macro</td><td>arrays_java.i</td><td>input
<br> output</td><td>arrays of proxy classes</td><td>Use for mapping C
 arrays to Java arrays.</td></tr>
<tr><td>arrays of enums</td><td>ARRAYSOFENUMS</td><td>arrays_java.i</td><td>
input
<br> output</td><td>int[]</td><td>Use for mapping C arrays to Java
 arrays (typeunsafe and simple enum wrapping approaches only).</td></tr>
<tr VALIGN="TOP"><td>char *</td><td>BYTE</td><td>various.i</td><td>input</td><td>
byte[]</td><td VALIGN="TOP">Java byte array is converted to char array</td>
</tr>
<tr><td>char **</td><td>STRING_ARRAY</td><td>various.i</td><td>input
<br> output</td><td>String[]</td><td>Use for mapping NULL terminated
 arrays of C strings to Java String arrays</td></tr>
<tr><td>unsigned char *</td><td>NIOBUFFER</td><td>various.i</td><td>
input
<br> output</td><td>java.nio.Buffer</td><td>Use for mapping directly
 allocated buffers to c/c++. useful with directors and long lived memory
 objects</td></tr>
</td></tr>
</td></tr>
</td></tr>
</table>
<h3><a name="Java_typemap_attributes">26.9.6 Java typemap attributes</a></h3>
<p> There are a few additional typemap attributes that the Java module
 supports.</p>
<p> The first of these is the 'throws' attribute. The throws attribute
 is optional and specified after the typemap name and contains one or
 more comma separated classes for adding to the throws clause for any
 methods that use that typemap. It is analogous to the <a href="#Java_exception_handling">
%javaexception</a> feature's throws attribute.</p>
<div class="code">
<pre>
%typemap(typemapname, throws=&quot;ExceptionClass1, ExceptionClass2&quot;) type { ... }
</pre>
</div>
<p> The attribute is necessary for supporting Java checked exceptions
 and can be added to just about any typemap. The list of typemaps
 include all the C/C++ (JNI) typemaps in the &quot;<a href="#Typemaps">
Typemaps</a>&quot; chapter and the Java specific typemaps listed in <a href="#Java_typemaps_c_to_java_types">
the previous section</a>, barring the &quot;jni&quot;, &quot;jtype&quot; and &quot;jstype&quot;
 typemaps as they could never contain code to throw an exception.</p>
<p> The throws clause is generated for the proxy method as well as the
 JNI method in the JNI intermediary class. If a method uses more than
 one typemap and each of those typemaps have classes specified in the
 throws clause, the union of the exception classes is added to the
 throws clause ensuring there are no duplicate classes. See the <a href="#Java_nan_exception_typemap">
NaN exception example</a> for further usage.</p>
<p> The &quot;jtype&quot; typemap has the optional 'nopgcpp' attribute which can
 be used to suppress the generation of the <a href="#Java_pgcpp">
premature garbage collection prevention parameter</a>.</p>
<p> The &quot;javain&quot; typemap has the optional 'pre', 'post' and 'pgcppname'
 attributes. These are used for generating code before and after the JNI
 call in the proxy class or module class. The 'pre' attribute contains
 code that is generated before the JNI call and the 'post' attribute
 contains code generated after the JNI call. The 'pgcppname' attribute
 is used to change the <a href="#Java_pgcpp">premature garbage
 collection prevention parameter</a> name passed to the JNI function.
 This is sometimes needed when the 'pre' typemap creates a temporary
 variable which is then passed to the JNI function.</p>
<p> <a name="Java_constructor_helper_function"></a> Note that when the
 'pre' or 'post' attributes are specified and the associated type is
 used in a constructor, a constructor helper function is generated. This
 is necessary as the Java proxy constructor wrapper makes a call to a
 support constructor using a<i> this</i> call. In Java the<i> this</i>
 call must be the first statement in the constructor body. The
 constructor body thus calls the helper function and the helper function
 instead makes the JNI call, ensuring the 'pre' code is called before
 the JNI call is made. There is a <a href="#Java_date_marshalling">Date
 marshalling</a> example showing 'pre', 'post' and 'pgcppname'
 attributes in action.</p>
<h3><a name="Java_special_variables">26.9.7 Java special variables</a></h3>
<p> The standard SWIG special variables are available for use within
 typemaps as described in the <a href="#Typemaps">Typemaps documentation</a>
, for example <tt>$1</tt>, <tt>$input</tt>, <tt>$result</tt> etc.</p>
<p> The Java module uses a few additional special variables:</p>
<p><b> <tt>$javaclassname</tt></b>
<br> This special variable works like the other <a href="#Typemaps_special_variables">
special variables</a> and <tt>$javaclassname</tt> is similar to <tt>
$1_type</tt>. It expands to the class name for use in Java given a
 pointer. SWIG wraps unions, structs and classes using pointers and in
 this case it expands to the Java proxy class name. For example, <tt>
$javaclassname</tt> is replaced by the proxy classname <tt>Foo</tt> when
 wrapping a <tt>Foo *</tt> and <tt>$&amp;javaclassname</tt> expands to the
 proxy classname when wrapping the C/C++ type <tt>Foo</tt> and <tt>
$*javaclassname</tt> expands to the proxy classname when wrapping <tt>
Foo *&amp;</tt>. If the type does not have an associated proxy class, it
 expands to the type wrapper class name, for example, <tt>
SWIGTYPE_p_unsigned_short</tt> is generated when wrapping <tt>unsigned
 short *</tt>. The class name is fully qualified with the package name
 when using the <a href="#SWIGPlus_nspace">nspace feature</a>.</p>
<p><b> <tt>$javaclazzname</tt></b>
<br> This special variable works like <tt>$javaclassname</tt>, but
 expands the fully qualified C++ class into the package name, if used by
 the <a href="#SWIGPlus_nspace">nspace feature</a>, and the proxy class
 name, mangled for use as a function name. For example, <tt>
Namespace1::Namespace2::Klass</tt> is expanded into <tt>
Namespace1_Namespace2_Klass_</tt>. This special variable is usually used
 for making calls to a function in the intermediary JNI class, as they
 are mangled with this prefix.</p>
<p><b> <tt>$null</tt></b>
<br> Used in input typemaps to return early from JNI functions that have
 either void or a non-void return type. Example:</p>
<div class="code">
<pre>
%typemap(check) int * %{ 
  if (error) {
    SWIG_JavaThrowException(jenv, SWIG_JavaIndexOutOfBoundsException, &quot;Array element error&quot;);
    return $null;
  }
%}
</pre>
</div>
<p> If the typemap gets put into a function with void as return, $null
 will expand to nothing:</p>
<div class="code">
<pre>
SWIGEXPORT void JNICALL Java_jnifn(...) {
  if (error) {
    SWIG_JavaThrowException(jenv, SWIG_JavaIndexOutOfBoundsException, &quot;Array element error&quot;);
    return ;
  }
  ...
}
</pre>
</div>
<p> otherwise $null expands to<i> NULL</i></p>
<div class="code">
<pre>
SWIGEXPORT jobject JNICALL Java_jnifn(...) {
  if (error) {
    SWIG_JavaThrowException(jenv, SWIG_JavaIndexOutOfBoundsException, &quot;Array element error&quot;);
    return NULL;
  }
  ...
}
</pre>
</div>
<p><b> <tt>$javainput, $jnicall and $owner</tt></b>
<br> The $javainput special variable is used in &quot;javain&quot; typemaps and
 $jnicall and $owner are used in &quot;javaout&quot; typemaps. $jnicall is
 analogous to $action in %exception. It is replaced by the call to the
 native method in the intermediary JNI class. $owner is replaced by
 either <tt>true</tt> if %newobject has been used, otherwise <tt>false</tt>
. $javainput is analogous to the $input special variable. It is replaced
 by the parameter name.</p>
<p> Here is an example:</p>
<div class="code">
<pre>
%typemap(javain) Class &quot;Class.getCPtr($javainput)&quot;
%typemap(javain) unsigned short &quot;$javainput&quot;
%typemap(javaout) Class * {
    return new Class($jnicall, $owner);
  }

%inline %{
  class Class {...};
  Class * bar(Class cls, unsigned short ush) { return new Class(); };
%}
</pre>
</div>
<p> The generated proxy code is then:</p>
<div class="code">
<pre>
public static Class bar(Class cls, int ush) {
  return new Class(exampleJNI.bar(Class.getCPtr(cls), cls, ush), false);
}
</pre>
</div>
<p> Here $javainput has been replaced by <tt>cls</tt> and <tt>ush</tt>.
 $jnicall has been replaced by the native method call, <tt>
exampleJNI.bar(...)</tt> and $owner has been replaced by <tt>false</tt>.
 If %newobject is used by adding the following at the beginning of our
 example:</p>
<div class="code">
<pre>
%newobject bar(Class cls, unsigned short ush);
</pre>
</div>
<p> The generated code constructs the return type using <tt>true</tt>
 indicating the proxy class <tt>Class</tt> is responsible for destroying
 the C++ memory allocated for it in <tt>bar</tt>:</p>
<div class="code">
<pre>
public static Class bar(Class cls, int ush) {
  return new Class(exampleJNI.bar(Class.getCPtr(cls), cls, ush), true);
}
</pre>
</div>
<p><b> <tt>$static</tt></b>
<br> This special variable expands to either<i> static</i> or nothing
 depending on whether the class is an inner Java class or not. It is
 used in the &quot;javaclassmodifiers&quot; typemap so that global classes can be
 wrapped as Java proxy classes and nested C++ classes/enums can be
 wrapped with the Java equivalent, that is, static inner proxy classes.</p>
<p><b> <tt>$error, $jniinput, $javacall and $packagepath</tt></b>
<br> These special variables are used in the directors typemaps. See <a href="#Java_directors_typemaps">
Director specific typemaps</a> for details.</p>
<p><b> <tt>$module</tt></b>
<br> This special variable expands to the module name, as specified by <tt>
%module</tt> or the <tt>-module</tt> commandline option.</p>
<p><b> <tt>$imclassname</tt></b>
<br> This special variable expands to the intermediary class name.
 Usually this is the same as '$moduleJNI', unless the jniclassname
 attribute is specified in the <a href="#Java_module_directive">%module
 directive</a>.</p>
<p><b> <tt>$javainterfacename</tt></b>
<br> This special variable is only expanded when the <tt>interface</tt>
 feature is applied to a class. It works much like <tt>$javaclassname</tt>
, but instead of expanding to the proxy classname, it expands to the
 value in the <tt>name</tt> attribute in the <tt>interface</tt> feature.
 For example:</p>
<div class="code">
<pre>
%feature(&quot;interface&quot;, name=&quot;MyInterface&quot;) MyClass;
%typemap(jstype) MyClass  &quot;$&amp;javainterfacename&quot;
%typemap(jstype) MyClass * &quot;$javainterfacename&quot;
</pre>
</div>
<p> will result in the <tt>jstype</tt> typemap expanding to <tt>
MyInterface</tt> for both <tt>MyClass</tt> and <tt>MyClass *</tt>. The
 interface name is fully qualified with the package name when using the <a
href="#SWIGPlus_nspace">nspace feature</a>.</p>
<p><b> <tt>$interfacename</tt></b>
<br> This special variable is only expanded when the <tt>interface</tt>
 feature is applied to a class. It expands to just the interface name
 and is thus different to <tt>$javainterfacename</tt> in that it is not
 fully qualified with the package name when using the <a href="#SWIGPlus_nspace">
nspace feature</a>.</p>
<h3><a name="Java_typemaps_for_c_and_cpp">26.9.8 Typemaps for both C and
 C++ compilation</a></h3>
<p> JNI calls must be written differently depending on whether the code
 is being compiled as C or C++. For example C compilation requires the
 pointer to a function pointer struct member syntax like</p>
<div class="code">
<pre>
const jclass clazz = (*jenv)-&gt;FindClass(jenv, &quot;java/lang/String&quot;);
</pre>
</div>
<p> whereas C++ code compilation of the same function call is a member
 function call using a class pointer like</p>
<div class="code">
<pre>
const jclass clazz = jenv-&gt;FindClass(&quot;java/lang/String&quot;);
</pre>
</div>
<p> To enable typemaps to be used for either C or C++ compilation, a set
 of JCALLx macros have been defined in Lib/java/javahead.swg, where x is
 the number of arguments in the C++ version of the JNI call. The above
 JNI calls would be written in a typemap like this</p>
<div class="code">
<pre>
const jclass clazz = JCALL1(FindClass, jenv, &quot;java/lang/String&quot;);
</pre>
</div>
<p> Note that the SWIG preprocessor expands these into the appropriate C
 or C++ JNI calling convention. The C calling convention is emitted by
 default and the C++ calling convention is emitted when using the -c++
 SWIG commandline option. If you do not intend your code to be targeting
 both C and C++ then your typemaps can use the appropriate JNI calling
 convention and need not use the JCALLx macros.</p>
<h3><a name="Java_code_typemaps">26.9.9 Java code typemaps</a></h3>
<p> Most of SWIG's typemaps are used for the generation of C/C++ code.
 The typemaps in this section are used solely for the generation of Java
 code. Elements of proxy classes and type wrapper classes come from the
 following typemaps (the defaults).</p>
<p><tt>%typemap(javabase)</tt></p>
<div class="indent"> base (extends) for Java class: empty default
<br> Note that this typemap accepts a <tt>replace</tt> attribute as an
 optional flag. When set to &quot;1&quot;, it will replace/override any C++ base
 classes that might have been parsed. If this flag is not specified and
 there are C++ base classes, then a multiple inheritance warning is
 issued and the code in the typemap is ignored. The typemap also accepts
 a <tt>notderived</tt> attribute as an optional flag. When set to &quot;1&quot;,
 it will not apply to classes that are derived from a C++ base. When
 used with the SWIGTYPE type, it is useful for giving a common base for
 all proxy classes, that is, providing a base class that sits in between
 all proxy classes and the Java base class <tt>Object</tt> for example: <tt>
%typemap(javabase, notderived=&quot;1&quot;) SWIGTYPE &quot;CommonBase&quot;</tt>.</div>
<p><tt>%typemap(javabody)</tt></p>
<div class="indent"> the essential support body for proxy classes (proxy
 base classes only), typewrapper classes and enum classes. Default
 contains extra constructors, memory ownership control member variables
 (<tt>swigCMemOwn</tt>, <tt>swigCPtr</tt>), the <tt>getCPtr</tt> method
 etc.</div>
<p><tt>%typemap(javabody_derived)</tt></p>
<div class="indent"> the essential support body for proxy classes
 (derived classes only). Same as &quot;javabody&quot; typemap, but only used for
 proxy derived classes.</div>
<p><tt>%typemap(javaclassmodifiers)</tt></p>
<div class="indent"> class modifiers for the Java class: default is
 &quot;public class&quot;</div>
<p><tt>%typemap(javacode)</tt></p>
<div class="indent"> Java code is copied verbatim to the Java class:
 empty default As there can only be one &quot;javacode&quot; typemap per class,
 also consider using the <a href="#Java_proxycode">%proxycode</a>
 directive which can be used multiple times per class and offers nearly
 identical functionality.</div>
<p><tt>%typemap(javadestruct, methodname=&quot;delete&quot;,
 methodmodifiers=&quot;public synchronized&quot;, parameters=&quot;&quot;)</tt>
<br></p>
<div class="indent"> destructor wrapper - the <tt>delete()</tt> method
 (proxy classes only), used for all proxy classes except those which
 have a base class : default calls C++ destructor (or frees C memory)
 and resets <tt>swigCPtr</tt> and <tt>swigCMemOwn</tt> flags
<br>
<br> Note that the <tt>delete()</tt> method name is configurable and is
 specified by the <tt>methodname</tt> attribute. The method modifiers
 are also configurable via the <tt>methodmodifiers</tt> attribute. If a <tt>
%javamethodmodifiers</tt> is attached to the class' destructor, it will
 be used in preference to the <tt>methodmodifiers</tt> typemap attribute
 for the class. The <tt>delete</tt> method's parameters declaration can
 be provided in the optional <tt>parameters</tt> typemap attribute.</div>
<p><tt>%typemap(javadestruct_derived, methodname=&quot;delete&quot;,
 methodmodifiers=&quot;public synchronized&quot;, parameters=&quot;&quot;)</tt></p>
<div class="indent"> destructor wrapper - the <tt>delete()</tt> method
 (proxy classes only), same as &quot;javadestruct&quot; but only used for derived
 proxy classes : default calls C++ destructor (or frees C memory) and
 resets <tt>swigCPtr</tt> and <tt>swigCMemOwn</tt> flags
<br>
<br> Note that the <tt>delete()</tt> method name is configurable and is
 specified by the <tt>methodname</tt> attribute. The method modifiers
 are also configurable via the <tt>methodmodifiers</tt> attribute. If a <tt>
%javamethodmodifiers</tt> is attached to the class' destructor, it will
 be used in preference to the <tt>methodmodifiers</tt> typemap attribute
 for the class. The <tt>delete</tt> method's parameters declaration can
 be provided in the optional <tt>parameters</tt> typemap attribute.</div>
<p><tt>%typemap(javaimports)</tt></p>
<div class="indent"> import statements for Java class: empty default</div>
<p><tt>%typemap(javainterfaces)</tt></p>
<div class="indent"> interfaces (implements) for Java class: empty
 default</div>
<p><tt>%typemap(javafinalize)</tt></p>
<div class="indent"> the <tt>finalize()</tt> method (proxy classes
 only): default calls the <tt>delete()</tt> method
<p> Note that the default javafinalize typemap must contain the full
 implementation of the finalize method. Any customization to this
 typemap must still declare a java finalize method with the correct
 signature. Note also that the name of the generated &quot;delete&quot; method may
 be affected by <tt>javadestruct</tt> and <tt>javadestruct_derived</tt>
 typemaps. Below shows an example modifying the finalizer, assuming the <tt>
delete</tt> method has been renamed to <tt>swig_delete</tt>.</p>
<div class="code">
<pre>
%typemap(javafinalize) SWIGTYPE %{
  protected void finalize() {
    swig_delete();  // renamed to prevent conflict with existing delete method
  }
]%
</pre>
</div></div>
<p><tt>%typemap(javainterfacecode, declaration=&quot;...&quot;, cptrmethod=&quot;...&quot;)</tt>
</p>
<div class="indent">
<p> The code in this typemap is added to the body of a Java proxy class
 but only when a class is marked with the <tt>interface</tt> feature.
 The typemap is used in the proxy class marked with the interface
 feature as well as all proxy classes derived from the marked C++ class,
 as they are all generated as implementing the Java interface. The
 default typemap used in the <tt>%interface</tt> family of macros
 mentioned in the <a href="#Java_interfaces">Java interfaces</a>
 section, where <tt>CTYPE</tt> is the C++ class macro argument, is as
 follows:</p>
<div class="code">
<pre>
%typemap(javainterfacecode,
         declaration=&quot;  long $interfacename_GetInterfaceCPtr();\n&quot;,
         cptrmethod=&quot;$interfacename_GetInterfaceCPtr&quot;) CTYPE %{
  public long $interfacename_GetInterfaceCPtr() {
    return $imclassname.$javaclazzname$interfacename_GetInterfaceCPtr(swigCPtr);
  }
%}
</pre>
</div></div>
<p> The special variable <tt>$interfacename</tt> is expanded into the
 name specified in the <tt>interface</tt> feature.</p>
<p><b> Compatibility Note:</b> In SWIG-1.3.21 and earlier releases,
 typemaps called &quot;javagetcptr&quot; and &quot;javaptrconstructormodifiers&quot; were
 available. These are deprecated and the &quot;javabody&quot; typemap can be used
 instead. The <tt>javainterfacecode</tt> typemap and interface feature
 was introduced in SWIG-3.0.9.</p>
<p> In summary the contents of the typemaps make up a proxy class like
 this:</p>
<div class="code">
<pre>
[ javaimports typemap ]
[ javaclassmodifiers typemap ] javaclassname extends [ javabase typemap ]
                                             implements [ javainterfaces typemap ] {
[ javabody or javabody_derived typemap ]
[ javafinalize typemap ]
public synchronized void <i>delete</i>() [ javadestruct OR javadestruct_derived typemap ]
[ javacode typemap ]
[ javainterfacecode typemap]
... proxy functions ...
}
</pre>
</div>
<p> Note the <tt><i>delete</i>()</tt> methodname and method modifiers
 are configurable, see &quot;javadestruct&quot; and &quot;javadestruct_derived&quot;
 typemaps above.</p>
<p> The <tt>javainterfacecode</tt> typemap is only used when bases are
 marked by the <tt>interface</tt> feature and the <tt>implements</tt>
 list will also then be expanded to include these Java interfaces.</p>
<p> The type wrapper class is similar in construction:</p>
<div class="code">
<pre>
[ javaimports typemap ]
[ javaclassmodifiers typemap ] javaclassname extends [ javabase typemap ]
                                             implements [ javainterfaces typemap ] {
[ javabody typemap ]
[ javacode typemap ]
}
</pre>
</div>
<p>The enum class is also similar in construction:</p>
<div class="code">
<pre>
[ javaimports typemap ]
[ javaclassmodifiers typemap ] javaclassname extends [ javabase typemap ]
                                             implements [ javainterfaces typemap ] {
... Enum values ...
[ javabody typemap ]
[ javacode typemap ]
}
</pre>
</div>
<p> The &quot;javaimports&quot; typemap is ignored if the enum class is wrapped by
 an inner Java class, that is when wrapping an enum declared within a
 C++ class.</p>
<p>The Java interface turned on by the <tt>interface</tt> feature is
 fairly simple:</p>
<div class="code">
<pre>
[ javaimports typemap ]
public interface [ javainterfacename ] {
[ javainterfacecode:cptrmethod typemap attribute ]
... interface declarations ...
}
</pre>
</div>
<p> where <tt>javainterfacename</tt> is the <tt>name</tt> attribute in
 the <a href="#Java_interfaces">interface feature</a>.</p>
<p> The defaults can be overridden to tailor the generated classes. Here
 is an example which will change the <tt>getCPtr</tt> method and
 constructor from the default public access to protected access. If the
 classes in one package are not using the classes in another package,
 then these methods need not be public and removing access to these low
 level implementation details, is a good thing. If you are invoking SWIG
 more than once and generating the wrapped classes into different
 packages in each invocation, then you cannot do this as you will then
 have different packages.</p>
<div class="code">
<pre>
%typemap(javabody) SWIGTYPE %{
  private transient long swigCPtr;
  protected transient boolean swigCMemOwn;

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

  protected static long getCPtr($javaclassname obj) {
    return (obj == null) ? 0 : obj.swigCPtr;
  }
%}
</pre>
</div>
<p> The typemap code is the same that is in &quot;<tt>java.swg</tt>&quot;, barring
 the last two method modifiers. Note that <tt>SWIGTYPE</tt> will target
 all proxy classes, but not the type wrapper classes. Also the above
 typemap is only used for proxy classes that are potential base classes.
 To target proxy classes that are derived from a wrapped class as well,
 the &quot;javabody_derived&quot; typemap should also be overridden.</p>
<p> For the typemap to be used in all type wrapper classes, all the
 different types that type wrapper classes could be used for should be
 targeted:</p>
<div class="code">
<pre>
%typemap(javabody) SWIGTYPE *, SWIGTYPE &amp;, SWIGTYPE [], SWIGTYPE (CLASS::*) %{
  private transient long swigCPtr;

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

  protected $javaclassname() {
    swigCPtr = 0;
  }

  protected static long getCPtr($javaclassname obj) {
    return (obj == null) ? 0 : obj.swigCPtr;
  }
%}
</pre>
</div>
<p> Again this is the same that is in &quot;<tt>java.swg</tt>&quot;, barring the
 method modifier for <tt>getCPtr</tt>.</p>
<p> When using <a href="#Modules">multiple modules</a> or the <a href="#Java_namespaces">
nspace feature</a> it is common to invoke SWIG with a different <tt>
-package</tt> command line option for each module. However, by default
 the generated code may not compile if generated classes in one package
 use generated classes in another package. The visibility of the <tt>
getCPtr()</tt> and pointer constructor generated from the <tt>javabody</tt>
 typemaps needs changing. The default visibility is <tt>protected</tt>
 but it needs to be <tt>public</tt> for access from a different package.
 Just changing 'protected' to 'public' in the typemap achieves this. Two
 macros are available in <tt>java.swg</tt> to make this easier and using
 them is the preferred approach over simply copying the typemaps and
 modifying as this is forward compatible with any changes in the <tt>
javabody</tt> typemap in future versions of SWIG. The macros are for the
 proxy and typewrapper classes and can respectively be used to to make
 the method and constructor public:</p>
<div class="code">
<pre>
  SWIG_JAVABODY_PROXY(public, public, SWIGTYPE)
  SWIG_JAVABODY_TYPEWRAPPER(public, public, public, SWIGTYPE)
</pre>
</div>
<h3><a name="Java_directors_typemaps">26.9.10 Director specific typemaps</a>
</h3>
<p> The Java directors feature requires the &quot;javadirectorin&quot;,
 &quot;javadirectorout&quot;, &quot;directorin&quot; and the &quot;directorout&quot; typemaps in order
 to work properly. The &quot;javapackage&quot; typemap is an optional typemap used
 to identify the Java package path for individual SWIG generated proxy
 classes used in director methods.</p>
<p><tt>%typemap(directorin)</tt></p>
<div class="indent">
<p> The &quot;directorin&quot; 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 &quot;descriptor&quot; attribute. For example, integers are converted as
 follows:</p>
<div class="code">
<pre>
%typemap(directorin, descriptor=&quot;I&quot;) int &quot;$input = (jint) $1;&quot;
</pre>
</div>
<p> <code>$input</code> is the SWIG name of the JNI temporary variable
 passed to Java in the upcall. The <code>descriptor=&quot;I&quot;</code> will put
 an <code>I</code> into the JNI field descriptor that identifies the
 Java method that will be called from C++. For more about JNI field
 descriptors and their importance, refer to the <a href="#Java_typemaps">
JNI documentation mentioned earlier</a>. A typemap for C character
 strings is:</p>
<div class="code">
<pre>
%typemap(directorin, descriptor=&quot;Ljava/lang/String;&quot;, noblock=1) char * {
  $input = 0;
  if ($1) {
    $input = JCALL1(NewStringUTF, jenv, (const char *)$1);
    if (!$input) return $null;
  }
  Swig::LocalRefGuard $1_refguard(jenv, $input);
}
</pre>
</div>
<p> The <tt>Swig::LocalRefGuard</tt> class should be used in directorin
 typemaps for newly allocated objects. It is used to control local
 reference counts ensuring the count is decremented after the call up
 into Java has completed. Its destructor simply calls <tt>
jenv-&gt;DeleteLocalRef(obj)</tt> on the <tt>obj</tt> passed in during
 construction.</p>
<p> User-defined types have the default &quot;descriptor&quot; attribute &quot;<code>
L$packagepath/$javaclassname;</code>&quot; 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 &quot;method not found&quot; runtime error. Note that the <code>
$packagepath</code> substitution always uses the path separator '/' when
 expanded. The <code>$javaclassname</code> expansion can be confusing as
 it is normally expanded using the '.' separator. However, <code>
$javaclassname</code> is expanded using the path separator '/' in
 typemap's &quot;descriptor&quot; attribute as well as in the &quot;directorthrows&quot;
 typemap.</p>
</div>
<p><tt>%typemap(directorout)</tt></p>
<div class="indent">
<p> The &quot;directorout&quot; typemap is used for converting the JNI return type
 in the C++ director class to the appropriate C++ type after the upcall
 to Java. For example, integers are converted as follows:</p>
<div class="code">
<pre>
%typemap(directorout) int %{ $result = (int)$input; %}
</pre>
</div>
<p> <code>$input</code> is the SWIG name of the JNI temporary variable
 returned from Java after the upcall. <code>$result</code> is the
 resulting output. A typemap for C character strings is:</p>
<div class="code">
<pre>
%typemap(directorout) char * {
  $1 = 0;
  if ($input) {
    $result = (char *)jenv-&gt;GetStringUTFChars($input, 0);
    if (!$1) return $null;
  }
}
</pre>
</div></div>
<p><tt>%typemap(javadirectorin)</tt></p>
<div class="indent">
<p> Conversion from jtype to jstype for director methods. These are Java
 code typemaps which transform the type used in the Java intermediary
 JNI class (as specified in the &quot;jtype&quot; typemap) to the Java type used
 in the Java module class, proxy classes and type wrapper classes (as
 specified in the &quot;jstype&quot; typemap). This typemap provides the
 conversion for the parameters in the director methods when calling up
 from C++ to Java.</p>
<p> For primitive types, this typemap is usually specified as:</p>
<div class="code">
<pre>
%typemap(javadirectorin) int &quot;$jniinput&quot;
</pre>
</div>
<p> The <code>$jniinput</code> special variable is analogous to <code>
$javainput</code> special variable. It is replaced by the input
 parameter name.</p>
</div>
<p><tt>%typemap(javadirectorout)</tt></p>
<div class="indent">
<p> Conversion from jstype to jtype for director methods. These are Java
 code typemaps which transform the type used in the Java module class,
 proxy classes and type wrapper classes (as specified in the &quot;jstype&quot;
 typemap) to the type used in the Java intermediary JNI class (as
 specified in the &quot;jtype&quot; typemap). This typemap provides the conversion
 for the return type in the director methods when returning from the C++
 to Java upcall.</p>
<p> For primitive types, this typemap is usually specified as:</p>
<div class="code">
<pre>
%typemap(javadirectorout) int &quot;$javacall&quot;
</pre>
</div>
<p> The <code>$javacall</code> special variable is analogous to the <code>
$jnicall</code> special variable. It is replaced by the call to the
 target Java method. The target method is the method in the Java proxy
 class which overrides the virtual C++ method in the C++ base class.</p>
</div>
<p><tt>%typemap(directorthrows)</tt></p>
<div class="indent">
<p> Conversion of Java exceptions to C++ exceptions in director method's
 exception handling. This typemap is expected to test the <tt>$error</tt>
 special variable for a matching Java exception and if successful
 convert and throw it into a C++ exception given by the typemap's type.
 The <code>$error</code> special variable is of type <code>jthrowable</code>
 and is substituted with a unique variable name in the generated code.</p>
<p> The example below converts a Java <code>
java.lang.IndexOutOfBoundsException</code> exception to the typemap's
 type, that is <code>std::out_of_range</code>:</p>
<div class="code">
<pre>
%typemap(directorthrows) std::out_of_range %{
  if (Swig::ExceptionMatches(jenv, $error, &quot;java/lang/IndexOutOfBoundsException&quot;)) {
    throw std::out_of_range(Swig::JavaExceptionMessage(jenv, $error).message());
  }
%}
</pre>
</div>
<p> The utility function <code>Swig::ExceptionMatches</code> and class <code>
Swig::JavaExceptionMessage</code> are helpers available when using
 directors and are described in the <a href="#Java_exceptions_from_directors">
Java Exceptions from Directors</a> section.</p>
</div>
<p><tt>%typemap(javapackage)</tt></p>
<div class="indent">
<p> The &quot;javapackage&quot; typemap is optional; it serves to identify a
 class's Java package. This typemap should be used in conjunction with
 classes that are defined outside of the current SWIG interface file.
 The typemap is only used if the type is used in a director method, that
 is, in a virtual method in a director class. For example:</p>
<div class="code">
<pre>
// class Foo is handled in a different interface file:
%import &quot;Foo.i&quot;

%feature(&quot;director&quot;) Example;

%inline {
  class Bar { };

  class Example {
  public:
    virtual ~Example();
    virtual void ping(Foo *arg1, Bar *arg2);
  };
}
</pre>
</div>
<p> Assume that the Foo class is part of the Java package<i>
 com.wombat.foo</i> but the above interface file is part of the Java
 package<i> com.wombat.example</i>. Without the &quot;javapackage&quot; typemap,
 SWIG will assume that the Foo class belongs to<i> com.wombat.example</i>
 class. The corrected interface file looks like:</p>
<div class="code">
<pre>
// class Foo is handled in a different interface file:
%import &quot;Foo.i&quot;
%typemap(&quot;javapackage&quot;) Foo, Foo *, Foo &amp; &quot;com.wombat.foo&quot;;
%feature(&quot;director&quot;) Example;

%inline {
  class Bar { };

  class Example {
  public:
    virtual ~Example();
    virtual void ping(Foo *arg1, Bar *arg2);
  };
}
</pre>
</div>
<p> SWIG looks up the package based on the<b> actual</b> type (plain
 Foo, Foo pointer and Foo reference), so it is important to associate
 all three types with the desired package. Practically speaking, you
 should create a separate SWIG interface file, which is %import-ed into
 each SWIG interface file, when you have multiple Java packages. Note
 the helper macros below, <code>OTHER_PACKAGE_SPEC</code> and <code>
ANOTHER_PACKAGE_SPEC</code>, which reduce the amount of extra typing. &quot;<code>
TYPE...</code>&quot; is useful when passing templated types to the macro,
 since multiargument template types appear to the SWIG preprocessor as
 multiple macro arguments.</p>
<div class="code">
<pre>
%typemap(&quot;javapackage&quot;) SWIGTYPE, SWIGTYPE *, SWIGTYPE &amp;
                                            &quot;package.for.most.classes&quot;;

%define OTHER_PACKAGE_SPEC(TYPE...)
%typemap(&quot;javapackage&quot;) TYPE, TYPE *, TYPE &amp; &quot;package.for.other.classes&quot;;
%enddef

%define ANOTHER_PACKAGE_SPEC(TYPE...)
%typemap(&quot;javapackage&quot;) TYPE, TYPE *, TYPE &amp; &quot;package.for.another.set&quot;;
%enddef

OTHER_PACKAGE_SPEC(Package_2_class_one)
ANOTHER_PACKAGE_SPEC(Package_3_class_two)
/* etc */
</pre>
</div>
<p> The basic strategy here is to provide a default package typemap for
 the majority of the classes, only providing &quot;javapackage&quot; typemaps for
 the exceptions.</p>
</div>
<h2><a name="Java_typemap_examples">26.10 Typemap Examples</a></h2>
<p> This section includes a few examples of typemaps. For more examples,
 you might look at the files &quot;<tt>java.swg</tt>&quot; and &quot;<tt>typemaps.i</tt>
&quot; in the SWIG library.</p>
<h3><a name="Java_simpler_enum_classes">26.10.1 Simpler Java enums for
 enums without initializers</a></h3>
<p> The default <a href="#Java_proper_enums_classes">Proper Java enums</a>
 approach to wrapping enums is somewhat verbose. This is to handle all
 possible C/C++ enums, in particular enums with initializers. The
 generated code can be simplified if the enum being wrapped does not
 have any initializers.</p>
<p> The following shows how to remove the support methods that are
 generated by default and instead use the methods in the Java enum base
 class <tt>java.lang.Enum</tt> and <tt>java.lang.Class</tt> for
 marshalling enums between C/C++ and Java. The type used for the
 typemaps below is <tt>enum SWIGTYPE</tt> which is the default type used
 for all enums. The &quot;enums.swg&quot; file should be examined in order to see
 the original overridden versions of the typemaps.</p>
<div class="code">
<pre>
%include &quot;enums.swg&quot;

%typemap(javain) enum SWIGTYPE &quot;$javainput.ordinal()&quot;
%typemap(javaout) enum SWIGTYPE {
    return $javaclassname.class.getEnumConstants()[$jnicall];
  }
%typemap(javabody) enum SWIGTYPE &quot;&quot;

%inline %{
  enum HairType { blonde, ginger, brunette };
  void setHair(HairType h);
  HairType getHair();
%}
</pre>
</div>
<p> SWIG will generate the following Java enum, which is somewhat
 simpler than the default:</p>
<div class="code">
<pre>
public enum HairType {
  blonde,
  ginger,
  brunette;
}
</pre>
</div>
<p> and the two Java proxy methods will be:</p>
<div class="code">
<pre>
public static void setHair(HairType h) {
  exampleJNI.setHair(h.ordinal());
}

public static HairType getHair() {
  return HairType.class.getEnumConstants()[exampleJNI.getHair()];
}
</pre>
</div>
<p> For marshalling Java enums to C/C++ enums, the <tt>ordinal</tt>
 method is used to convert the Java enum into an integer value for
 passing to the JNI layer, see the &quot;javain&quot; typemap. For marshalling
 C/C++ enums to Java enums, the C/C++ enum value is cast to an integer
 in the C/C++ typemaps (not shown). This integer value is then used to
 index into the array of enum constants that the Java language provides.
 See the <tt>getEnumConstants</tt> method in the &quot;javaout&quot; typemap.</p>
<p> These typemaps can often be used as the default for wrapping enums
 as in many cases there won't be any enum initializers. In fact a good
 strategy is to always use these typemaps and to specifically handle
 enums with initializers using %apply. This would be done by using the
 original versions of these typemaps in &quot;enums.swg&quot; under another
 typemap name for applying using %apply.</p>
<h3><a name="Java_exception_typemap">26.10.2 Handling C++ exception
 specifications as Java exceptions</a></h3>
<p> This example demonstrates various ways in which C++ exceptions can
 be tailored and converted into Java exceptions. Let's consider a simple
 file class <tt>SimpleFile</tt> and an exception class <tt>FileException</tt>
 which it may throw on error:</p>
<div class="code">
<pre>
%include &quot;std_string.i&quot; // for std::string typemaps
#include &lt;string&gt;

class FileException {
  std::string message;
public:
  FileException(const std::string&amp; msg) : message(msg) {}
  std::string what() {
    return message;
  }
};

class SimpleFile {
  std::string filename;
public:
  SimpleFile(const std::string&amp; filename) : filename(filename) {}
  void open() throw(FileException) {
  ...
  }
};
</pre>
</div>
<p> As the <tt>open</tt> method has a C++ exception specification, SWIG
 will parse this and know that the method can throw an exception. The <a href="Typemaps.html#throws_typemap">
&quot;throws&quot; typemap</a> is then used when SWIG encounters an exception
 specification. The default generic &quot;throws&quot; typemap looks like this:</p>
<div class="code">
<pre>
%typemap(throws) SWIGTYPE, SWIGTYPE &amp;, SWIGTYPE *, SWIGTYPE [ANY] %{
  SWIG_JavaThrowException(jenv, SWIG_JavaRuntimeException,
                          &quot;C++ $1_type exception thrown&quot;);
  return $null;
%}
</pre>
</div>
<p> Basically SWIG will generate a C++ try catch block and the body of
 the &quot;throws&quot; typemap constitutes the catch block. The above typemap
 calls a SWIG supplied method which throws a <tt>
java.lang.RuntimeException</tt>. This exception class is a runtime
 exception and therefore not a checked exception. If, however, we wanted
 to throw a checked exception, say <tt>java.io.IOException</tt>, then we
 could use the following typemap:</p>
<div class="code">
<pre>
%typemap(throws, throws=&quot;java.io.IOException&quot;) FileException {
  jclass excep = jenv-&gt;FindClass(&quot;java/io/IOException&quot;);
  if (excep)
    jenv-&gt;ThrowNew(excep, $1.what().c_str());
  return $null;
}
</pre>
</div>
<p> Note that this typemap uses the 'throws' <a href="#Java_typemap_attributes">
typemap attribute</a> to ensure a throws clause is generated. The
 generated proxy method then specifies the checked exception by
 containing <tt>java.io.IOException</tt> in the throws clause:</p>
<div class="code">
<pre>
public class SimpleFile {
  ...
  public void open() throws java.io.IOException { ... }
}
</pre>
</div>
<p> Lastly, if you don't want to map your C++ exception into one of the
 standard Java exceptions, the C++ class can be wrapped and turned into
 a custom Java exception class. If we go back to our example, the first
 thing we must do is get SWIG to wrap <tt>FileException</tt> and ensure
 that it derives from <tt>java.lang.Exception</tt>. Additionally, we
 might want to override the <tt>java.lang.Exception.getMessage()</tt>
 method. The typemaps to use then are as follows:</p>
<div class="code">
<pre>
%typemap(javabase) FileException &quot;java.lang.Exception&quot;;
%typemap(javacode) FileException %{
  public String getMessage() {
    return what();
  }
%}
</pre>
</div>
<p> This generates:</p>
<div class="code">
<pre>
public class FileException extends java.lang.Exception {
  ...
  public String getMessage() {
    return what();
  }

  public FileException(String msg) { ... }

  public String what() {
    return exampleJNI.FileException_what(swigCPtr, this);
  }
}
</pre>
</div>
<p> We could alternatively have used <tt>%rename</tt> to rename <tt>
what()</tt> into <tt>getMessage()</tt>.</p>
<h3><a name="Java_nan_exception_typemap">26.10.3 NaN Exception -
 exception handling for a particular type</a></h3>
<p> A Java exception can be thrown from any Java or JNI code. Therefore,
 as most typemaps contain either Java or JNI code, just about any
 typemap could throw an exception. The following example demonstrates
 exception handling on a type by type basis by checking for 'Not a
 number' (NaN) whenever a parameter of type <tt>float</tt> is wrapped.</p>
<p> Consider the following C++ code:</p>
<div class="code">
<pre>
bool calculate(float first, float second);
</pre>
</div>
<p> To validate every <tt>float</tt> being passed to C++, we could
 precede the code being wrapped by the following typemap which throws a
 runtime exception whenever the <tt>float</tt> is 'Not a Number':</p>
<div class="code">
<pre>
%module example
%typemap(javain) float &quot;$module.CheckForNaN($javainput)&quot;
%pragma(java) modulecode=%{
  /** Simply returns the input value unless it is not a number,
      whereupon an exception is thrown. */
  static protected float CheckForNaN(float num) {
    if (Float.isNaN(num))
      throw new RuntimeException(&quot;Not a number&quot;);
    return num;
  }
%}
</pre>
</div>
<p> Note that the <tt>CheckForNaN</tt> support method has been added to
 the module class using the <tt>modulecode</tt> pragma. The following
 shows the generated code of interest:</p>
<div class="code">
<pre>
public class example {
  ...

  /** Simply returns the input value unless it is not a number,
      whereupon an exception is thrown. */
  static protected float CheckForNaN(float num) {
    if (Float.isNaN(num))
      throw new RuntimeException(&quot;Not a number&quot;);
    return num;
  }

  public static boolean calculate(float first, float second) {
    return exampleJNI.calculate(example.CheckForNaN(first), example.CheckForNaN(second));
  }
}
</pre>
</div>
<p> Note that the &quot;javain&quot; typemap is used for every occurrence of a <tt>
float</tt> being used as an input. Of course, we could have targeted the
 typemap at a particular parameter by using <tt>float first</tt>, say,
 instead of just <tt>float</tt>.</p>
<p> The exception checking could alternatively have been placed into the
 'pre' attribute that the &quot;javain&quot; typemap supports. The &quot;javain&quot;
 typemap above could be replaced with the following:</p>
<div class="code">
<pre>
%typemap(javain, pre=&quot;    $module.CheckForNaN($javainput);&quot;) float &quot;$javainput&quot;
</pre>
</div>
<p> which would modify the <tt>calculate</tt> function to instead be
 generated as:</p>
<div class="code">
<pre>
public class example {
  ...
  public static boolean calculate(float first, float second) {
    example.CheckForNaN(first);
    example.CheckForNaN(second);
    {
      return exampleJNI.calculate(first, second);
    }
  }
}
</pre>
</div>
<p> See the <a href="#Java_date_marshalling">Date marshalling example</a>
 for an example using further &quot;javain&quot; typemap attributes.</p>
<p> If we decide that what we actually want is a checked exception
 instead of a runtime exception, we can change this easily enough. The
 proxy method that uses <tt>float</tt> as an input, must then add the
 exception class to the throws clause. SWIG can handle this as it
 supports the 'throws' <a href="#Java_typemap_attributes">typemap
 attribute</a> for specifying classes for the throws clause. Thus we can
 modify the pragma and the typemap for the throws clause:</p>
<div class="code">
<pre>
%typemap(javain, throws=&quot;java.lang.Exception&quot;) float &quot;$module.CheckForNaN($javainput)&quot;
%pragma(java) modulecode=%{
  /** Simply returns the input value unless it is not a number,
      whereupon an exception is thrown. */
  static protected float CheckForNaN(float num) throws java.lang.Exception {
    if (Float.isNaN(num))
      throw new RuntimeException(&quot;Not a number&quot;);
    return num;
  }
%}
</pre>
</div>
<p> The <tt>calculate</tt> method now has a throws clause and even
 though the typemap is used twice for both <tt>float first</tt> and <tt>
float second</tt>, the throws clause contains a single instance of <tt>
java.lang.Exception</tt>:</p>
<div class="code">
<pre>
public class example {
  ...

  /** Simply returns the input value unless it is not a number,
      whereupon an exception is thrown. */
  static protected float CheckForNaN(float num) throws java.lang.Exception {
    if (Float.isNaN(num))
      throw new RuntimeException(&quot;Not a number&quot;);
    return num;
  }

  public static boolean calculate(float first, float second) throws java.lang.Exception {
    return exampleJNI.calculate(example.CheckForNaN(first), example.CheckForNaN(second));
  }
}
</pre>
</div>
<p> If we were a martyr to the JNI cause, we could replace the succinct
 code within the &quot;javain&quot; typemap with a few pages of JNI code. If we
 had, we would have put it in the &quot;in&quot; typemap which, like all JNI and
 Java typemaps, also supports the 'throws' attribute.</p>
<h3><a name="Java_converting_java_string_arrays">26.10.4 Converting Java
 String arrays to char **</a></h3>
<p> A common problem in many C programs is the processing of command
 line arguments, which are usually passed in an array of NULL terminated
 strings. The following SWIG interface file allows a Java String array
 to be used as a <tt>char **</tt> object.</p>
<div class="code">
<pre>
%module example

/* This tells SWIG to treat char ** as a special case when used as a parameter
   in a function call */
%typemap(in) char ** (jint size) {
  int i = 0;
  size = (*jenv)-&gt;GetArrayLength(jenv, $input);
  $1 = (char **) malloc((size+1)*sizeof(char *));
  /* make a copy of each string */
  for (i = 0; i&lt;size; i++) {
    jstring j_string = (jstring)(*jenv)-&gt;GetObjectArrayElement(jenv, $input, i);
    const char * c_string = (*jenv)-&gt;GetStringUTFChars(jenv, j_string, 0);
    $1[i] = malloc((strlen(c_string)+1)*sizeof(char));
    strcpy($1[i], c_string);
    (*jenv)-&gt;ReleaseStringUTFChars(jenv, j_string, c_string);
    (*jenv)-&gt;DeleteLocalRef(jenv, j_string);
  }
  $1[i] = 0;
}

/* This cleans up the memory we malloc'd before the function call */
%typemap(freearg) char ** {
  int i;
  for (i=0; i&lt;size$argnum-1; i++)
    free($1[i]);
  free($1);
}

/* This allows a C function to return a char ** as a Java String array */
%typemap(out) char ** {
  int i;
  int len=0;
  jstring temp_string;
  const jclass clazz = (*jenv)-&gt;FindClass(jenv, &quot;java/lang/String&quot;);

  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 ** &quot;jobjectArray&quot;
%typemap(jtype) char ** &quot;String[]&quot;
%typemap(jstype) char ** &quot;String[]&quot;

/* These 2 typemaps handle the conversion of the jtype to jstype typemap type
   and vice versa */
%typemap(javain) char ** &quot;$javainput&quot;
%typemap(javaout) char ** {
    return $jnicall;
  }

/* Now a few test functions */
%inline %{

int print_args(char **argv) {
  int i = 0;
  while (argv[i]) {
    printf(&quot;argv[%d] = %s\n&quot;, i, argv[i]);
    i++;
  }
  return i;
}

char **get_args() {
  static char *values[] = { &quot;Dave&quot;, &quot;Mike&quot;, &quot;Susan&quot;, &quot;John&quot;, &quot;Michelle&quot;, 0};
  return &amp;values[0];
}

%}
</pre>
</div>
<p> Note that the 'C' JNI calling convention is used. Checking for any
 thrown exceptions after JNI function calls has been omitted. When this
 module is compiled, our wrapped C functions can be used by the
 following Java program:</p>
<div class="code">
<pre>
// File runme.java

public class runme {

  static {
    try {
      System.loadLibrary(&quot;example&quot;);
    } catch (UnsatisfiedLinkError e) {
      System.err.println(&quot;Native code library failed to load. &quot; + e);
      System.exit(1);
    }
  }

  public static void main(String argv[]) {
    String animals[] = {&quot;Cat&quot;, &quot;Dog&quot;, &quot;Cow&quot;, &quot;Goat&quot;};
    example.print_args(animals);
    String args[] = example.get_args();
    for (int i=0; i&lt;args.length; i++)
      System.out.println(i + &quot;:&quot; + args[i]);
  }
}
</pre>
</div>
<p> When compiled and run we get:</p>
<div class="code">
<pre>
$ java runme
argv[0] = Cat
argv[1] = Dog
argv[2] = Cow
argv[3] = Goat
0:Dave
1:Mike
2:Susan
3:John
4:Michelle
</pre>
</div>
<p> In the example, a few different typemaps are used. The &quot;in&quot; 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
 &quot;freearg&quot; typemap is used to later release this memory after the
 execution of the C function. The &quot;out&quot; typemap is used for function
 return values. Lastly the &quot;jni&quot;, &quot;jtype&quot; and &quot;jstype&quot; typemaps are also
 required to specify what Java types to use.</p>
<h3><a name="Java_expanding_java_object">26.10.5 Expanding a Java object
 to multiple arguments</a></h3>
<p> Suppose that you had a collection of C functions with arguments such
 as the following:</p>
<div class="code">
<pre>
int foo(int argc, char **argv);
</pre>
</div>
<p> In the previous example, a typemap was written to pass a Java String
 array as the <tt>char **argv</tt>. This allows the function to be used
 from Java as follows:</p>
<div class="code">
<pre>
example.foo(4, new String[]{&quot;red&quot;, &quot;green&quot;, &quot;blue&quot;, &quot;white&quot;});
</pre>
</div>
<p> Although this works, it's a little awkward to specify the argument
 count. To fix this, a multi-argument typemap can be defined. This is
 not very difficult--you only have to make slight modifications to the
 previous example's typemaps:</p>
<div class="code">
<pre>
%typemap(in) (int argc, char **argv) {
  int i = 0;
  $1 = (*jenv)-&gt;GetArrayLength(jenv, $input);
  $2 = (char **) malloc(($1+1)*sizeof(char *));
  /* make a copy of each string */
  for (i = 0; i&lt;$1; i++) {
    jstring j_string = (jstring)(*jenv)-&gt;GetObjectArrayElement(jenv, $input, i);
    const char * c_string = (*jenv)-&gt;GetStringUTFChars(jenv, j_string, 0);
    $2[i] = malloc((strlen(c_string)+1)*sizeof(char));
    strcpy($2[i], c_string);
    (*jenv)-&gt;ReleaseStringUTFChars(jenv, j_string, c_string);
    (*jenv)-&gt;DeleteLocalRef(jenv, j_string);
  }
  $2[i] = 0;
}

%typemap(freearg) (int argc, char **argv) {
  int i;
  for (i=0; i&lt;$1-1; i++)
    free($2[i]);
  free($2);
}

%typemap(jni) (int argc, char **argv) &quot;jobjectArray&quot;
%typemap(jtype) (int argc, char **argv) &quot;String[]&quot;
%typemap(jstype) (int argc, char **argv) &quot;String[]&quot;

%typemap(javain) (int argc, char **argv) &quot;$javainput&quot;
</pre>
</div>
<p> When writing a multiple-argument typemap, each of the types is
 referenced by a variable such as <tt>$1</tt> or <tt>$2</tt>. The
 typemap code simply fills in the appropriate values from the supplied
 Java parameter.</p>
<p> With the above typemap in place, you will find it no longer
 necessary to supply the argument count. This is automatically set by
 the typemap code. For example:</p>
<div class="code">
<pre>
example.foo(new String[]{&quot;red&quot;, &quot;green&quot;, &quot;blue&quot;, &quot;white&quot;});
</pre>
</div>
<h3><a name="Java_using_typemaps_return_arguments">26.10.6 Using
 typemaps to return arguments</a></h3>
<p> A common problem in some C programs is that values may be returned
 in function parameters rather than in the return value of a function.
 The <tt>typemaps.i</tt> file defines INPUT, OUTPUT and INOUT typemaps
 which can be used to solve some instances of this problem. This library
 file uses an array as a means of moving data to and from Java when
 wrapping a C function that takes non const pointers or non const
 references as parameters.</p>
<p> Now we are going to outline an alternative approach to using arrays
 for C pointers. The INOUT typemap uses a <tt>double[]</tt> array for
 receiving and returning the <tt>double*</tt> parameters. In this
 approach we are able to use a Java class <tt>myDouble</tt> instead of <tt>
double[]</tt> arrays where the C pointer <tt>double*</tt> is required.</p>
<p> Here is our example function:</p>
<div class="code">
<pre>
/* Returns a status value and two values in out1 and out2 */
int spam(double a, double b, double *out1, double *out2);
</pre>
</div>
<p> If we define a structure <tt>MyDouble</tt> containing a <tt>double</tt>
 member variable and use some typemaps we can solve this problem. For
 example we could put the following through SWIG:</p>
<div class="code">
<pre>
%module example

/* Define a new structure to use instead of double * */
%inline %{
typedef struct {
  double value;
} MyDouble;
%}


%{
/* Returns a status value and two values in out1 and out2 */
int spam(double a, double b, double *out1, double *out2) {
  int status = 1;
  *out1 = a*10.0;
  *out2 = b*100.0;
  return status;
}
%}

/* 
This typemap will make any double * function parameters with name <tt>OUTVALUE</tt> take an
argument of MyDouble instead of double *. This will 
allow the calling function to read the double * value after returning from the function.
*/
%typemap(in) double *OUTVALUE {
  jclass clazz = jenv-&gt;FindClass(&quot;MyDouble&quot;);
  jfieldID fid = jenv-&gt;GetFieldID(clazz, &quot;swigCPtr&quot;, &quot;J&quot;);
  jlong cPtr = jenv-&gt;GetLongField($input, fid);
  MyDouble *pMyDouble = NULL;
  *(MyDouble **)&amp;pMyDouble = *(MyDouble **)&amp;cPtr;
  $1 = &amp;pMyDouble-&gt;value;
}

%typemap(jtype) double *OUTVALUE &quot;MyDouble&quot;
%typemap(jstype) double *OUTVALUE &quot;MyDouble&quot;
%typemap(jni) double *OUTVALUE &quot;jobject&quot;

%typemap(javain) double *OUTVALUE &quot;$javainput&quot;

/* Now we apply the typemap to the named variables */
%apply double *OUTVALUE { double *out1, double *out2 };
int spam(double a, double b, double *out1, double *out2);
</pre>
</div>
<p> Note that the C++ JNI calling convention has been used this time and
 so must be compiled as C++ and the -c++ commandline must be passed to
 SWIG. JNI error checking has been omitted for clarity.</p>
<p> What the typemaps do are make the named <tt>double*</tt> function
 parameters use our new <tt>MyDouble</tt> wrapper structure. The &quot;in&quot;
 typemap takes this structure, gets the C++ pointer to it, takes the <tt>
double value</tt> member variable and passes it to the C++ <tt>spam</tt>
 function. In Java, when the function returns, we use the SWIG created <tt>
getValue()</tt> function to get the output value. The following Java
 program demonstrates this:</p>
<div class="code">
<pre>
// File: runme.java

public class runme {

  static {
    try {
      System.loadLibrary(&quot;example&quot;);
    } catch (UnsatisfiedLinkError e) {
      System.err.println(&quot;Native code library failed to load. &quot; + 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 + &quot;  &quot; + out1.getValue() + &quot;  &quot; + out2.getValue());
  }
}
</pre>
</div>
<p> When compiled and run we get:</p>
<div class="code">
<pre>
$ java runme
1 12.0  340.0
</pre>
</div>
<h3><a name="Java_adding_downcasts">26.10.7 Adding Java downcasts to
 polymorphic return types</a></h3>
<p> SWIG support for polymorphism works in that the appropriate virtual
 function is called. However, the default generated code does not allow
 for downcasting. Let's examine this with the following code:</p>
<div class="code">
<pre>
%include &quot;std_string.i&quot;

#include &lt;iostream&gt;
using namespace std;
class Vehicle {
public:
  virtual void start() = 0;
...
};

class Ambulance : public Vehicle {
  string vol;
public:
  Ambulance(string volume) : vol(volume) {}
  virtual void start() {
    cout &lt;&lt; &quot;Ambulance started&quot; &lt;&lt; endl;
  }
  void sound_siren() {
    cout &lt;&lt; vol &lt;&lt; &quot; siren sounded!&quot; &lt;&lt; endl;
  }
...
};

Vehicle *vehicle_factory() {
  return new Ambulance(&quot;Very loud&quot;);
}
</pre>
</div>
<p> If we execute the following Java code:</p>
<div class="code">
<pre>
Vehicle vehicle = example.vehicle_factory();
vehicle.start();

Ambulance ambulance = (Ambulance)vehicle;
ambulance.sound_siren();
</pre>
</div>
<p> We get:</p>
<div class="code">
<pre>
Ambulance started
java.lang.ClassCastException
        at runme.main(runme.java:16)
</pre>
</div>
<p> Even though we know from examination of the C++ code that <tt>
vehicle_factory</tt> returns an object of type <tt>Ambulance</tt>, we
 are not able to use this knowledge to perform the downcast in Java.
 This occurs because the runtime type information is not completely
 passed from C++ to Java when returning the type from <tt>
vehicle_factory()</tt>. Usually this is not a problem as virtual
 functions do work by default, such as in the case of <tt>start()</tt>.
 There are a few solutions to getting downcasts to work.</p>
<p> The first is not to use a Java cast but a call to C++ to make the
 cast. Add this to your code:</p>
<div class="code">
<pre>
%exception Ambulance::dynamic_cast(Vehicle *vehicle) {
  $action
    if (!result) {
      jclass excep = jenv-&gt;FindClass(&quot;java/lang/ClassCastException&quot;);
      if (excep) {
        jenv-&gt;ThrowNew(excep, &quot;dynamic_cast exception&quot;);
      }
    }
}
%extend Ambulance {
  static Ambulance *dynamic_cast(Vehicle *vehicle) {
    return dynamic_cast&lt;Ambulance *&gt;(vehicle);
  }
};
</pre>
</div>
<p> It would then be used from Java like this</p>
<div class="code">
<pre>
Ambulance ambulance = Ambulance.dynamic_cast(vehicle);
ambulance.sound_siren();
</pre>
</div>
<p> Should <tt>vehicle</tt> not be of type <tt>ambulance</tt> then a
 Java <tt>ClassCastException</tt> is thrown. The next solution is a
 purer solution in that Java downcasts can be performed on the types.
 Add the following before the definition of <tt>vehicle_factory</tt>:</p>
<div class="code">
<pre>
%typemap(out) Vehicle * {
  Ambulance *downcast = dynamic_cast&lt;Ambulance *&gt;($1);
  *(Ambulance **)&amp;$result = downcast;
}

%typemap(javaout) Vehicle * {
    return new Ambulance($jnicall, $owner);
  }
</pre>
</div>
<p> Here we are using our knowledge that <tt>vehicle_factory</tt> always
 returns type <tt>Ambulance</tt> so that the Java proxy is created as a
 type <tt>Ambulance</tt>. If <tt>vehicle_factory</tt> can manufacture
 any type of <tt>Vehicle</tt> and we want to be able to downcast using
 Java casts for any of these types, then a different approach is needed.
 Consider expanding our example with a new Vehicle type and a more
 flexible factory function:</p>
<div class="code">
<pre>
class FireEngine : public Vehicle {
public:
  FireEngine() {}
  virtual void start() {
    cout &lt;&lt; &quot;FireEngine started&quot; &lt;&lt; endl;
  }
  void roll_out_hose() {
    cout &lt;&lt; &quot;Hose rolled out&quot; &lt;&lt; endl;
  }
  ...
};
Vehicle *vehicle_factory(int vehicle_number) {
  if (vehicle_number == 0)
    return new Ambulance(&quot;Very loud&quot;);
  else
    return new FireEngine();
}
</pre>
</div>
<p> To be able to downcast with this sort of Java code:</p>
<div class="code">
<pre>
FireEngine fireengine = (FireEngine)example.vehicle_factory(1);
fireengine.roll_out_hose();
Ambulance ambulance = (Ambulance)example.vehicle_factory(0);
ambulance.sound_siren();
</pre>
</div>
<p> the following typemaps targeted at the <tt>vehicle_factory</tt>
 function will achieve this. Note that in this case, the Java class is
 constructed using JNI code rather than passing a pointer across the JNI
 boundary in a Java long for construction in Java code.</p>
<div class="code">
<pre>
%typemap(jni) Vehicle *vehicle_factory &quot;jobject&quot;
%typemap(jtype) Vehicle *vehicle_factory &quot;Vehicle&quot;
%typemap(jstype) Vehicle *vehicle_factory &quot;Vehicle&quot;
%typemap(javaout) Vehicle *vehicle_factory {
    return $jnicall;
  }

%typemap(out) Vehicle *vehicle_factory {
  Ambulance *ambulance = dynamic_cast&lt;Ambulance *&gt;($1);
  FireEngine *fireengine = dynamic_cast&lt;FireEngine *&gt;($1);
  if (ambulance) {
    // call the Ambulance(long cPtr, boolean cMemoryOwn) constructor
    jclass clazz = jenv-&gt;FindClass(&quot;Ambulance&quot;);
    if (clazz) {
      jmethodID mid = jenv-&gt;GetMethodID(clazz, &quot;&lt;init&gt;&quot;, &quot;(JZ)V&quot;);
      if (mid) {
        jlong cptr = 0;
        *(Ambulance **)&amp;cptr = ambulance;
        $result = jenv-&gt;NewObject(clazz, mid, cptr, false);
      }
    }
  } else if (fireengine) {
    // call the FireEngine(long cPtr, boolean cMemoryOwn) constructor
    jclass clazz = jenv-&gt;FindClass(&quot;FireEngine&quot;);
    if (clazz) {
      jmethodID mid = jenv-&gt;GetMethodID(clazz, &quot;&lt;init&gt;&quot;, &quot;(JZ)V&quot;);
      if (mid) {
        jlong cptr = 0;
        *(FireEngine **)&amp;cptr = fireengine;
        $result = jenv-&gt;NewObject(clazz, mid, cptr, false);
      }
    }
  }
  else {
    cout &lt;&lt; &quot;Unexpected type &quot; &lt;&lt; endl;
  }

  if (!$result)
    cout &lt;&lt; &quot;Failed to create new java object&quot; &lt;&lt; endl;
}
</pre>
</div>
<p> Better error handling would need to be added into this code. There
 are other solutions to this problem, but this last example demonstrates
 some more involved JNI code. SWIG usually generates code which
 constructs the proxy classes using Java code as it is easier to handle
 error conditions and is faster. Note that the JNI code above uses a
 number of string lookups to call a constructor, whereas this would not
 occur using byte compiled Java code.</p>
<h3><a name="Java_adding_equals_method">26.10.8 Adding an equals method
 to the Java classes</a></h3>
<p> When a pointer is returned from a JNI function, it is wrapped using
 a new Java proxy class or type wrapper class. Even when the pointers
 are the same, it will not be possible to know that the two Java classes
 containing those pointers are actually the same object. It is common in
 Java to use the <tt>equals()</tt> method to check whether two objects
 are equivalent. The <tt>equals()</tt> method is usually accompanied by
 a <tt>hashCode()</tt> method in order to fulfill the requirement that
 the hash code is equal for equal objects. Pure Java code methods like
 these can be easily added:</p>
<div class="code">
<pre>
%typemap(javacode) SWIGTYPE %{
  public boolean equals(Object obj) {
    boolean equal = false;
    if (obj instanceof $javaclassname)
      equal = ((($javaclassname)obj).swigCPtr == this.swigCPtr);
    return equal;
  }
  public int hashCode() {
    return (int)getPointer();
  }
%}

class Foo { };
Foo* returnFoo(Foo *foo) { return foo; }
</pre>
</div>
<p> The following would display <tt>false</tt> without the <tt>javacode</tt>
 typemap above. With the typemap defining the <tt>equals</tt> method the
 result is <tt>true</tt>.</p>
<div class="code">
<pre>
Foo foo1 = new Foo();
Foo foo2 = example.returnFoo(foo1);
System.out.println(&quot;foo1? &quot; + foo1.equals(foo2));
</pre>
</div>
<h3><a name="Java_void_pointers">26.10.9 Void pointers and a common Java
 base class</a></h3>
<p> One might wonder why the common code that SWIG emits for the proxy
 and type wrapper classes is not pushed into a base class. The reason is
 that although <tt>swigCPtr</tt> could be put into a common base class
 for all classes wrapping C structures, it would not work for C++
 classes involved in an inheritance chain. Each class derived from a
 base needs a separate <tt>swigCPtr</tt> because C++ compilers sometimes
 use a different pointer value when casting a derived class to a base.
 Additionally as Java only supports single inheritance, it would not be
 possible to derive wrapped classes from your own pure Java classes if
 the base class has been 'used up' by SWIG. However, you may want to
 move some of the common code into a base class. Here is an example
 which uses a common base class for all proxy classes and type wrapper
 classes:</p>
<div class="code">
<pre>
%typemap(javabase) SWIGTYPE, SWIGTYPE *, SWIGTYPE &amp;, SWIGTYPE [], 
                                                         SWIGTYPE (CLASS::*) &quot;SWIG&quot;

%typemap(javacode) SWIGTYPE, SWIGTYPE *, SWIGTYPE &amp;, SWIGTYPE [], 
                                                         SWIGTYPE (CLASS::*) %{
  protected long getPointer() {
    return swigCPtr;
  }
%}
</pre>
</div>
<p> Define new base class called SWIG:</p>
<div class="code">
<pre>
public abstract class SWIG {
  protected abstract long getPointer();

  public boolean equals(Object obj) {
    boolean equal = false;
    if (obj instanceof SWIG)
      equal = (((SWIG)obj).getPointer() == this.getPointer());
    return equal;
  }
  
  SWIGTYPE_p_void getVoidPointer() {
    return new SWIGTYPE_p_void(getPointer(), false);
  }
}
</pre>
</div>
<p> This example contains some useful functionality which you may want
 in your code.</p>
<ul>
<li> It has an <tt>equals()</tt> method. Unlike the previous example,
 the method code isn't replicated in all classes.</li>
<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.</li>
</ul>
<h3><a name="Java_struct_pointer_pointer">26.10.10 Struct pointer to
 pointer</a></h3>
<p> Pointers to pointers are often used as output parameters in C
 factory type functions. These are a bit more tricky to handle. Consider
 the following situation where a <tt>Butler</tt> can be hired and fired:</p>
<div class="code">
<pre>
typedef struct {
  int hoursAvailable;
  char *greeting;
} Butler;

// Note: HireButler will allocate the memory 
// The caller must free the memory by calling FireButler()!!
extern int HireButler(Butler **ppButler);
extern void FireButler(Butler *pButler);
</pre>
</div>
<p> C code implementation:</p>
<div class="code">
<pre>
int HireButler(Butler **ppButler) {
  Butler *pButler = (Butler *)malloc(sizeof(Butler));
  pButler-&gt;hoursAvailable = 24;
  pButler-&gt;greeting = (char *)malloc(32);
  strcpy(pButler-&gt;greeting, &quot;At your service Sir&quot;);
  *ppButler = pButler;
  return 1;
}
void FireButler(Butler *pButler) {
  free(pButler-&gt;greeting);
  free(pButler);
}
</pre>
</div>
<p> Let's take two approaches to wrapping this code. The first is to
 provide a functional interface, much like the original C interface. The
 following Java code shows how we intend the code to be used:</p>
<div class="code">
<pre>
Butler jeeves = new Butler();
example.HireButler(jeeves);
System.out.println(&quot;Greeting:     &quot; + jeeves.getGreeting());
System.out.println(&quot;Availability: &quot; + jeeves.getHoursAvailable() + &quot; hours per day&quot;);
example.FireButler(jeeves);
</pre>
</div>
<p> Resulting in the following output when run:</p>
<div class="shell">
<pre>
Greeting:     At your service Sir
Availability: 24 hours per day
</pre>
</div>
<p> Note the usage is very much like it would be used if we were writing
 C code, that is, explicit memory management is needed. No C memory is
 allocated in the construction of the <tt>Butler</tt> proxy class and
 the proxy class will not destroy the underlying C memory when it is
 collected. A number of typemaps and features are needed to implement
 this approach. The following interface file code should be placed
 before SWIG parses the above C code.</p>
<div class="code">
<pre>
%module example

// Do not generate the default proxy constructor or destructor
%nodefaultctor Butler;
%nodefaultdtor Butler;

// Add in pure Java code proxy constructor
%typemap(javacode) Butler %{
  /** This constructor creates the proxy which initially does not create nor own any C memory */
  public Butler() {
    this(0, false);
  }
%}

// Type typemaps for marshalling Butler **
%typemap(jni) Butler ** &quot;jobject&quot;
%typemap(jtype) Butler ** &quot;Butler&quot;
%typemap(jstype) Butler ** &quot;Butler&quot;

// Typemaps for Butler ** as a parameter output type
%typemap(in) Butler ** (Butler *ppButler = 0) %{
  $1 = &amp;ppButler;
%}
%typemap(argout) Butler ** {
  // Give Java proxy the C pointer (of newly created object)
  jclass clazz = (*jenv)-&gt;FindClass(jenv, &quot;Butler&quot;);
  jfieldID fid = (*jenv)-&gt;GetFieldID(jenv, clazz, &quot;swigCPtr&quot;, &quot;J&quot;);
  jlong cPtr = 0;
  *(Butler **)&amp;cPtr = *$1;
  (*jenv)-&gt;SetLongField(jenv, $input, fid, cPtr);
}
%typemap(javain) Butler ** &quot;$javainput&quot;
</pre>
</div>
<p> Note that the JNI code sets the proxy's <tt>swigCPtr</tt> member
 variable to point to the newly created object. The <tt>swigCMemOwn</tt>
 remains unchanged (at false), so that the proxy does not own the
 memory.</p>
<p> Note: The old %nodefault directive disabled the default constructor
 and destructor at the same time. This is unsafe in most of the cases,
 and you can use the explicit %nodefaultctor and %nodefaultdtor
 directives to achieve the same result if needed.</p>
<p> The second approach offers a more object oriented interface to the
 Java user. We do this by making the Java proxy class's constructor call
 the <tt>HireButler()</tt> method to create the underlying C object.
 Additionally we get the proxy to take ownership of the memory so that
 the finalizer will call the <tt>FireButler()</tt> function. The proxy
 class will thus take ownership of the memory and clean it up when no
 longer needed. We will also prevent the user from being able to
 explicitly call the <tt>HireButler()</tt> and <tt>FireButler()</tt>
 functions. Usage from Java will simply be:</p>
<div class="code">
<pre>
Butler jeeves = new Butler();
System.out.println(&quot;Greeting:     &quot; + jeeves.getGreeting());
System.out.println(&quot;Availability: &quot; + jeeves.getHoursAvailable() + &quot; hours per day&quot;);
</pre>
</div>
<p> Note that the Butler class is used just like any other Java class
 and no extra coding by the user needs to be written to clear up the
 underlying C memory as the finalizer will be called by the garbage
 collector which in turn will call the <tt>FireButler()</tt> function.
 To implement this, we use the above interface file code but remove the <tt>
javacode</tt> typemap and add the following:</p>
<div class="code">
<pre>
// Don't expose the memory allocation/de-allocation functions
%ignore FireButler(Butler *pButler);
%ignore HireButler(Butler **ppButler);

// Add in a custom proxy constructor and destructor
%extend Butler {
  Butler() {
    Butler *pButler = 0;
    HireButler(&amp;pButler);
    return pButler;
  }
  ~Butler() {
    FireButler($self);
  }
}
</pre>
</div>
<p> Note that the code in <tt>%extend</tt> is using a C++ type
 constructor and destructor, yet the generated code will still compile
 as C code, see <a href="#SWIG_adding_member_functions">Adding member
 functions to C structures</a>. The C functional interface has been
 completely morphed into an object-oriented interface and the Butler
 class would behave much like any pure Java class and feel more natural
 to Java users.</p>
<h3><a name="Java_memory_management_member_variables">26.10.11 Memory
 management when returning references to member variables</a></h3>
<p> This example shows how to prevent premature garbage collection of
 objects when the underlying C++ class returns a pointer or reference to
 a member variable.</p>
<p> Consider the following C++ code:</p>
<div class="code">
<pre>
struct Wheel {
  int size;
  Wheel(int sz = 0) : size(sz) {}
};

class Bike {
  Wheel wheel;
public:
  Bike(int val) : wheel(val) {}
  Wheel&amp; getWheel() { return wheel; }
};
</pre>
</div>
<p> and the following usage from Java after running the code through
 SWIG:</p>
<div class="code">
<pre>
Wheel wheel = new Bike(10).getWheel();
System.out.println(&quot;wheel size: &quot; + wheel.getSize());
// Simulate a garbage collection
System.gc();
System.runFinalization();
System.out.println(&quot;wheel size: &quot; + wheel.getSize());
</pre>
</div>
<p> Don't be surprised that if the resulting output gives strange
 results such as...</p>
<div class="shell">
<pre>
wheel size: 10
wheel size: 135019664
</pre>
</div>
<p> What has happened here is the garbage collector has collected the <tt>
Bike</tt> instance as it doesn't think it is needed any more. The proxy
 instance, <tt>wheel</tt>, contains a reference to memory that was
 deleted when the <tt>Bike</tt> instance was collected. In order to
 prevent the garbage collector from collecting the <tt>Bike</tt>
 instance a reference to the <tt>Bike</tt> must be added to the <tt>
wheel</tt> instance. You can do this by adding the reference when the <tt>
getWheel()</tt> method is called using the following typemaps.</p>
<div class="code">
<pre>
%typemap(javacode) Wheel %{
  // Ensure that the GC doesn't collect any Bike instance set from Java
  private Bike bikeReference;
  protected void addReference(Bike bike) {
    bikeReference = bike;
  }
%}

// Add a Java reference to prevent premature garbage collection and resulting use
// of dangling C++ pointer. Intended for methods that return pointers or
// references to a member variable.
%typemap(javaout) Wheel&amp; getWheel {
  long cPtr = $jnicall;
  $javaclassname ret = null;
  if (cPtr != 0) {
    ret = new $javaclassname(cPtr, $owner);
    ret.addReference(this);
  }
  return ret;
  }
</pre>
</div>
<p> The code in the first typemap gets added to the <tt>Wheel</tt> proxy
 class. The code in the second typemap constitutes the bulk of the code
 in the generated <tt>getWheel()</tt> function:</p>
<div class="code">
<pre>
public class Wheel {
  ...
  // Ensure that the GC doesn't collect any bike set from Java 
  private Bike bikeReference;
  protected void addReference(Bike bike) {
    bikeReference = bike;
  }
}

public class Bike {
  ...
  public Wheel getWheel() {
    long cPtr = exampleJNI.Bike_getWheel(swigCPtr, this);
    Wheel ret = null;
    if (cPtr != 0) {
      ret = new Wheel(cPtr, false);
      ret.addReference(this);
    }
    return ret;
  }
}
</pre>
</div>
<p> Note the <tt>addReference</tt> call.</p>
<h3><a name="Java_memory_management_objects">26.10.12 Memory management
 for objects passed to the C++ layer</a></h3>
<p> Managing memory can be tricky when using C++ and Java proxy classes.
 The previous example shows one such case and this example looks at
 memory management for a class passed to a C++ method which expects the
 object to remain in scope after the function has returned. Consider the
 following two C++ classes:</p>
<div class="code">
<pre>
struct Element {
  int value;
  Element(int val) : value(val) {}
};
class Container {
  Element* element;
public:
  Container() : element(0) {}
  void setElement(Element* e) { element = e; }
  Element* getElement() { return element; }
};
</pre>
</div>
<p> and usage from C++</p>
<div class="code">
<pre>
Container container;
Element element(20);
container.setElement(&amp;element);
cout &lt;&lt; &quot;element.value: &quot; &lt;&lt; container.getElement()-&gt;value &lt;&lt; endl;
</pre>
</div>
<p> and more or less equivalent usage from Java</p>
<div class="code">
<pre>
Container container = new Container();
container.setElement(new Element(20));
System.out.println(&quot;element value: &quot; + container.getElement().getValue());
</pre>
</div>
<p> The C++ code will always print out 20, but the value printed out may
 not be this in the Java equivalent code. In order to understand why,
 consider a garbage collection occurring...</p>
<div class="code">
<pre>
Container container = new Container();
container.setElement(new Element(20));
// Simulate a garbage collection
System.gc();
System.runFinalization();
System.out.println(&quot;element value: &quot; + container.getElement().getValue());
</pre>
</div>
<p> The temporary element created with <tt>new Element(20)</tt> could
 get garbage collected which ultimately means the <tt>container</tt>
 variable is holding a dangling pointer, thereby printing out any old
 random value instead of the expected value of 20. One solution is to
 add in the appropriate references in the Java layer...</p>
<div class="code">
<pre>
public class Container {

  ...

  // Ensure that the GC doesn't collect any Element set from Java
  // as the underlying C++ class stores a shallow copy
  private Element elementReference;

  public void setElement(Element e) {
    exampleJNI.Container_setElement(swigCPtr, this, Element.getCPtr(e), e);
    elementReference = e;
  }
}
</pre>
</div>
<p> The following typemaps can be used to generate this code:</p>
<div class="code">
<pre>
%typemap(javacode) Container %{
  // Ensure that the GC doesn't collect any element set from Java
  // as the underlying C++ class stores a shallow copy
  private Element elementReference;
%}

%typemap(javain, 
         post=&quot;      elementReference = $javainput;&quot;
         ) Element *e &quot;Element.getCPtr($javainput)&quot;
</pre>
</div>
<p> The 'javacode' typemap simply adds in the specified code into the
 Java proxy class. The 'javain' typemap matches the input parameter type
 and name for the <tt>setElement</tt> method and the 'post' typemap
 attribute allows adding code after the JNI call. The 'post' code is
 generated into a finally block after the JNI call so the resulting code
 isn't quite as mentioned earlier, <tt>setElement</tt> is actually:</p>
<div class="code">
<pre>
  public void setElement(Element e) {
    try {
      exampleJNI.Container_setElement(swigCPtr, this, Element.getCPtr(e), e);
    } finally {
      elementReference = e;
    }
  }
</pre>
</div>
<h3><a name="Java_date_marshalling">26.10.13 Date marshalling using the
 javain typemap and associated attributes</a></h3>
<p> The <a href="#Java_nan_exception_typemap">NaN Exception example</a>
 is a simple example of the &quot;javain&quot; typemap and its 'pre' attribute.
 This example demonstrates how a C++ date class, say <tt>CDate</tt>, can
 be mapped onto the standard Java date class, <tt>
java.util.GregorianCalendar</tt> by using the 'pre', 'post' and
 'pgcppname' attributes of the &quot;javain&quot; typemap. The idea is that the <tt>
GregorianCalendar</tt> is used wherever the C++ API uses a <tt>CDate</tt>
. Let's assume the code being wrapped is as follows:</p>
<div class="code">
<pre>
class CDate {
public:
  CDate(int year, int month, int day);
  int getYear();
  int getMonth();
  int getDay();
  ...
};
struct Action {
  static int doSomething(const CDate &amp;dateIn, CDate &amp;dateOut);
  Action(const CDate &amp;date, CDate &amp;dateOut);
};
</pre>
</div>
<p> Note that <tt>dateIn</tt> is const and therefore read only and <tt>
dateOut</tt> is a non-const output type.</p>
<p> First let's look at the code that is generated by default, where the
 Java proxy class <tt>CDate</tt> is used in the proxy interface:</p>
<div class="code">
<pre>
public class Action {
  ...
  public static int doSomething(CDate dateIn, CDate dateOut) {
    return exampleJNI.Action_doSomething(CDate.getCPtr(dateIn), dateIn, 
                                         CDate.getCPtr(dateOut), dateOut);
  }

  public Action(CDate date, CDate dateOut) {
    this(exampleJNI.new_Action(CDate.getCPtr(date), date, 
                               CDate.getCPtr(dateOut), dateOut), true);
  }
}
</pre>
</div>
<p> The <tt>CDate &amp;</tt> and <tt>const CDate &amp;</tt> Java code is
 generated from the following two default typemaps:</p>
<div class="code">
<pre>
%typemap(jstype) SWIGTYPE &amp; &quot;$javaclassname&quot;
%typemap(javain) SWIGTYPE &amp; &quot;$javaclassname.getCPtr($javainput)&quot;
</pre>
</div>
<p> where '$javaclassname' is translated into the proxy class name, <tt>
CDate</tt> and '$javainput' is translated into the name of the
 parameter, eg <tt>dateIn</tt>. From Java, the intention is then to call
 into a modified API with something like:</p>
<div class="code">
<pre>
java.util.GregorianCalendar calendarIn = 
  new java.util.GregorianCalendar(2011, java.util.Calendar.APRIL, 13, 0, 0, 0);
java.util.GregorianCalendar calendarOut = new java.util.GregorianCalendar();

// Note in calls below, calendarIn remains unchanged and calendarOut 
// is set to a new value by the C++ call
Action.doSomething(calendarIn, calendarOut);
Action action = new Action(calendarIn, calendarOut);
</pre>
</div>
<p> To achieve this mapping, we need to alter the default code
 generation slightly so that at the Java layer, a <tt>GregorianCalendar</tt>
 is converted into a <tt>CDate</tt>. The JNI intermediary layer will
 still take a pointer to the underlying <tt>CDate</tt> class. The
 typemaps to achieve this are shown below.</p>
<div class="code">
<pre>
%typemap(jstype) const CDate&amp; &quot;java.util.GregorianCalendar&quot;
%typemap(javain, 
         pre=&quot;    CDate temp$javainput = new CDate($javainput.get(java.util.Calendar.YEAR), &quot;
             &quot;$javainput.get(java.util.Calendar.MONTH), $javainput.get(java.util.Calendar.DATE));&quot;, 
         pgcppname=&quot;temp$javainput&quot;) const CDate &amp;
         &quot;$javaclassname.getCPtr(temp$javainput)&quot;

%typemap(jstype) CDate&amp; &quot;java.util.Calendar&quot;
%typemap(javain, 
         pre=&quot;    CDate temp$javainput = new CDate($javainput.get(java.util.Calendar.YEAR), &quot;
             &quot;$javainput.get(java.util.Calendar.MONTH), $javainput.get(java.util.Calendar.DATE));&quot;, 
         post=&quot;      $javainput.set(temp$javainput.getYear(), temp$javainput.getMonth(), &quot;
              &quot;temp$javainput.getDay(), 0, 0, 0);&quot;, 
         pgcppname=&quot;temp$javainput&quot;) CDate &amp;
         &quot;$javaclassname.getCPtr(temp$javainput)&quot;
</pre>
</div>
<p> The resulting generated proxy code in the <tt>Action</tt> class
 follows:</p>
<div class="code">
<pre>
public class Action {
  ...
  public static int doSomething(java.util.GregorianCalendar dateIn, 
                                java.util.Calendar dateOut) {
    CDate tempdateIn = new CDate(dateIn.get(java.util.Calendar.YEAR), 
                                 dateIn.get(java.util.Calendar.MONTH), 
                                 dateIn.get(java.util.Calendar.DATE));
    CDate tempdateOut = new CDate(dateOut.get(java.util.Calendar.YEAR), 
                                  dateOut.get(java.util.Calendar.MONTH), 
                                  dateOut.get(java.util.Calendar.DATE));
    try {
      return exampleJNI.Action_doSomething(CDate.getCPtr(tempdateIn), tempdateIn, 
                                           CDate.getCPtr(tempdateOut), tempdateOut);
    } finally {
      dateOut.set(tempdateOut.getYear(), tempdateOut.getMonth(), tempdateOut.getDay(), 0, 0, 0);
    }
  }

  static private long SwigConstructAction(java.util.GregorianCalendar date, 
                                          java.util.Calendar dateOut) {
    CDate tempdate = new CDate(date.get(java.util.Calendar.YEAR), 
                               date.get(java.util.Calendar.MONTH), 
                               date.get(java.util.Calendar.DATE));
    CDate tempdateOut = new CDate(dateOut.get(java.util.Calendar.YEAR), 
                                  dateOut.get(java.util.Calendar.MONTH), 
                                  dateOut.get(java.util.Calendar.DATE));
    try {
      return exampleJNI.new_Action(CDate.getCPtr(tempdate), tempdate, 
                                   CDate.getCPtr(tempdateOut), tempdateOut);
    } finally {
      dateOut.set(tempdateOut.getYear(), tempdateOut.getMonth(), tempdateOut.getDay(), 0, 0, 0);
    }
  }

  public Action(java.util.GregorianCalendar date, java.util.Calendar dateOut) {
    this(Action.SwigConstructAction(date, dateOut), true);
  }
}
</pre>
</div>
<p> A few things to note:</p>
<ul>
<li> The &quot;javatype&quot; typemap has changed the parameter type to <tt>
java.util.GregorianCalendar</tt> or <tt>java.util.Calendar</tt> instead
 of the default generated <tt>CDate</tt> proxy.</li>
<li> The code in the 'pre' attribute appears before the JNI call (<tt>
exampleJNI.new_Action</tt> / <tt>exampleJNI.Action_doSomething</tt>).</li>
<li> The code in the 'post' attribute appears after the JNI call.</li>
<li> A try .. finally block is generated with the JNI call in the try
 block and 'post' code in the finally block. The alternative of just
 using a temporary variable for the return value from the JNI call and
 the 'post' code being generated before the return statement is not
 possible given that the JNI call is in one line and comes from the
 &quot;javaout&quot; typemap.</li>
<li> The temporary variables in the &quot;javain&quot; typemaps are called <tt>
temp$javain</tt>, where &quot;$javain&quot; is replaced with the parameter name.
 &quot;$javain&quot; is used to mangle the variable name so that more than one <tt>
CDate &amp;</tt> type can be used as a parameter in a method, otherwise two
 or more local variables with the same name would be generated.</li>
<li> The use of the &quot;javain&quot; typemap causes a constructor helper
 function (<tt>SwigConstructAction</tt>) to be generated. This allows
 Java code to be called before the JNI call and is required as the Java
 compiler won't compile code inserted before the 'this' call.</li>
<li> The 'pgcppname' attribute is used to modify the object being passed
 as the <a href="#Java_pgcpp">premature garbage collection prevention
 parameter</a> (the 2nd and 4th parameters in the JNI calls).</li>
</ul>
<h2><a name="Java_directors_faq">26.11 Living with Java Directors</a></h2>
<p> This section is intended to address frequently asked questions and
 frequently encountered problems when using Java directors.</p>
<ol>
<li><i>When my program starts up, it complains that</i> method_foo<i>
 cannot be found in a Java method called</i> swig_module_init<i>. How do
 I fix this?</i>
<p> Open up the C++ wrapper source code file and look for <code>
&quot;method_foo&quot;</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 &quot;javapackage&quot; typemap in your
 SWIG interface file.</p>
</li>
<li><i>I'm compiling my code and I'm using templates. I provided a
 javapackage typemap, but SWIG doesn't generate the right JNI field
 descriptor.</i>
<p> Use the template's renamed name as the argument to the &quot;javapackage&quot;
 typemap:</p>
<div class="code">
<pre>
%typemap(javapackage)  std::vector&lt;int&gt;  &quot;your.package.here&quot;
%template(VectorOfInt) std::vector&lt;int&gt;;
</pre>
</div></li>
<li>
<p><i>When I pass class pointers or references through a C++ upcall and
 I try to type cast them, Java complains with a ClassCastException. What
 am I doing wrong?</i></p>
<p> Normally, a non-director generated Java proxy class creates
 temporary Java objects as follows:</p>
<div class="code">
<pre>
public static void MyClass_method_upcall(MyClass self, long jarg1)
{
  Foo darg1 = new Foo(jarg1, false);

  self.method_upcall(darg1);
}
</pre>
</div>
<p>Unfortunately, this loses the Java type information that is part of
 the underlying Foo director proxy class's Java object pointer causing
 the type cast to fail. The SWIG Java module's director code attempts to
 correct the problem,<b> but only for director-enabled classes</b>,
 since the director class retains a global reference to its Java object.
 Thus, for director-enabled classes<b> and only for director-enabled
 classes</b>, the generated proxy Java code looks something like:</p>
<div class="code">
<pre>
public static void MyClass_method_upcall(MyClass self, long jarg1,
                                         Foo jarg1_object)
{
  Foo darg1 = (jarg1_object != null ? jarg1_object : new Foo(jarg1, false));

  self.method_upcall(darg1);
}
</pre>
</div>
<p> When you import a SWIG interface file containing class definitions,
 the classes you want to be director-enabled must be have the <code>
feature(&quot;director&quot;)</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 &quot;type symmetry&quot; design will work for simple C++
 inheritance, but will most likely fail for anything more complicated
 such as tree or diamond C++ inheritance hierarchies. Those who are
 interested in challenging problems are more than welcome to hack the <code>
Java::Java_director_declaration</code> method in <code>
Source/Modules/java.cxx</code>.</p>
<p> If all else fails, you can use the downcastXXXXX() method to attempt
 to recover the director class's Java object pointer. For the Java Foo
 proxy class, the Foo director class's java object pointer can be
 accessed through the javaObjectFoo() method. The generated method's
 signature is:</p>
<div class="code">
<pre>
  public static Foo javaObjectFoo(Foo obj);
</pre>
</div>
<p> From your code, this method is invoked as follows:</p>
<div class="code">
<pre>
public class MyClassDerived {
  public void method_upcall(Foo foo_object)
  {
    FooDerived    derived = (foo_object != null ?
                 (FooDerived) Foo.downcastFoo(foo_object) : null);
    /* rest of your code here */
  }
}
</pre>
</div>
<p> An good approach for managing downcasting is placing a static method
 in each derived class that performs the downcast from the superclass,
 e.g.,</p>
<div class="code">
<pre>
public class FooDerived extends Foo {
  /* ... */
  public static FooDerived downcastFooDerived(Foo foo_object)
  {
    try {
      return foo_object != null ? (FooDerived) Foo.downcastFoo(foo_object);
    }

    catch (ClassCastException exc) {
      // Wasn't a FooDerived object, some other subclass of Foo
      return null;
    }
  }
}
</pre>
</div>
<p> Then change the code in MyClassDerived as follows:</p>
<div class="code">
<pre>
public class MyClassDerived extends MyClass {
  /* ... */
  public void method_upcall(Foo foo_object)
  {
    FooDerived    derived = FooDerived.downcastFooDerived(foo_object);
    /* rest of your code here */
  }
}
</pre>
</div></li>
<li>
<p><i>Why isn't the proxy class declared abstract? Why aren't the
 director upcall methods in the proxy class declared abstract?</i></p>
<p> Declaring the proxy class and its methods abstract would break the
 JNI argument marshalling and SWIG's downcall functionality (going from
 Java to C++.) Create an abstract Java subclass that inherits from the
 director-enabled class instead. Using the previous Foo class example:</p>
<div class="code">
<pre>
public abstract class UserVisibleFoo extends Foo {
  /** Make sure user overrides this method, it's where the upcall
   * happens.
   */
  public abstract void method_upcall(Foo foo_object);

  /// Downcast from Foo to UserVisibleFoo
  public static UserVisibleFoo downcastUserVisibleFoo(Foo foo_object)
  {
    try {
      return foo_object != null ? (FooDerived) Foo.downcastFoo(foo_object) : null;
    } catch (ClassCastException exc) {
      // Wasn't a FooDerived object, some other subclass of Foo
      return null;
    }
  }
}
</pre>
</div>
<p>This doesn't prevent the user from creating subclasses derived from
 Foo, however, UserVisibleFoo provides the safety net that reminds the
 user to override the <code>method_upcall()</code> method.</p>
</li>
</ol>
<h2><a name="Java_odds_ends">26.12 Odds and ends</a></h2>
<h3><a name="Java_javadoc_comments">26.12.1 JavaDoc comments</a></h3>
<p> The SWIG documentation system is currently deprecated. When it is
 resurrected JavaDoc comments will be fully supported. If you can't wait
 for the full documentation system a couple of workarounds are
 available. The <tt>%javamethodmodifiers</tt> feature can be used for
 adding proxy class method comments and module class method comments.
 The &quot;javaimports&quot; typemap can be hijacked for adding in proxy class
 JavaDoc comments. The <tt>jniclassimports</tt> or <tt>
jniclassclassmodifiers</tt> pragmas can also be used for adding
 intermediary JNI class comments and likewise the <tt>moduleimports</tt>
 or <tt>moduleclassmodifiers</tt> pragmas for the module class. Here is
 an example adding in a proxy class and method comment:</p>
<div class="code">
<pre>
%javamethodmodifiers Barmy::lose_marbles() &quot;
  /**
    * Calling this method will make you mad.
    * Use with &lt;b&gt;utmost&lt;/b&gt; caution. 
    */
  public&quot;;

%typemap(javaimports) Barmy &quot;
/** The crazy class. Use as a last resort. */&quot;

class Barmy {
public:
  void lose_marbles() {}
};
</pre>
</div>
<p> Note the &quot;public&quot; added at the end of the <tt>%javamethodmodifiers</tt>
 as this is the default for this feature. The generated proxy class with
 JavaDoc comments is then as follows:</p>
<div class="code">
<pre>
/** The crazy class. Use as a last resort. */
public class Barmy {
...
  /**
    * Calling this method will make you mad.
    * Use with &lt;b&gt;utmost&lt;/b&gt; caution. 
    */
  public void lose_marbles() {
    ...
  }
...
}
</pre>
</div>
<h3><a name="Java_functional_interface">26.12.2 Functional interface
 without proxy classes</a></h3>
<p> It is possible to run SWIG in a mode that does not produce proxy
 classes by using the -noproxy commandline option. The interface is
 rather primitive when wrapping structures or classes and is accessed
 through function calls to the module class. All the functions in the
 module class are wrapped by functions with identical names as those in
 the intermediary JNI class.</p>
<p> Consider the example we looked at when examining proxy classes:</p>
<div class="code">
<pre>
class Foo {
public:
  int x;
  int spam(int num, Foo* foo);
};
</pre>
</div>
<p> When using <tt>-noproxy</tt>, type wrapper classes are generated
 instead of proxy classes. Access to all the functions and variables is
 through a C like set of functions where the first parameter passed is
 the pointer to the class, that is an instance of a type wrapper class.
 Here is what the module class looks like:</p>
<div class="code">
<pre>
public class example {
  public static void Foo_x_get(SWIGTYPE_p_Foo self, int x) {...}
  public static int Foo_x_get(SWIGTYPE_p_Foo self) {...}
  public static int Foo_spam(SWIGTYPE_p_Foo self, int num, SWIGTYPE_p_Foo foo) {...}
  public static SWIGTYPE_p_Foo new_Foo() {...}
  public static void delete_Foo(SWIGTYPE_p_Foo self) {...}
}
</pre>
</div>
<p> This approach is not nearly as natural as using proxy classes as the
 functions need to be used like this:</p>
<div class="code">
<pre>
SWIGTYPE_p_Foo foo = example.new_Foo();
example.Foo_x_set(foo, 10);
int var = example.Foo_x_get(foo);
example.Foo_spam(foo, 20, foo);
example.delete_Foo(foo);
</pre>
</div>
<p> Unlike proxy classes, there is no attempt at tracking memory. All
 destructors have to be called manually for example the <tt>
delete_Foo(foo)</tt> call above.</p>
<h3><a name="Java_using_own_jni_functions">26.12.3 Using your own JNI
 functions</a></h3>
<p> You may have some hand written JNI functions that you want to use in
 addition to the SWIG generated JNI functions. Adding these to your SWIG
 generated package is possible using the <tt>%native</tt> directive. If
 you don't want SWIG to wrap your JNI function then of course you can
 simply use the <tt>%ignore</tt> directive. However, if you want SWIG to
 generate just the Java code for a JNI function then use the <tt>%native</tt>
 directive. The C types for the parameters and return type must be
 specified in place of the JNI types and the function name must be the
 native method name. For example:</p>
<div class="code">
<pre>
%native (HandRolled) void HandRolled(int, char *);
%{
JNIEXPORT void JNICALL Java_packageName_moduleName_HandRolled(JNIEnv *, jclass,
                                                              jlong, jstring);
%}
</pre>
</div>
<p> No C JNI function will be generated and the <tt>
Java_packageName_moduleName_HandRolled</tt> function will be accessible
 using the SWIG generated Java native method call in the intermediary
 JNI class which will look like this:</p>
<div class="code">
<pre>
  public final static native void HandRolled(int jarg1, String jarg2);
</pre>
</div>
<p> and as usual this function is wrapped by another which for a global
 C function would appear in the module class:</p>
<div class="code">
<pre>
  public static void HandRolled(int arg0, String arg1) {
    exampleJNI.HandRolled(arg0, arg1);
  }
</pre>
</div>
<p> The <tt>packageName</tt> and <tt>moduleName</tt> must of course be
 correct else you will get linker errors when the JVM dynamically loads
 the JNI function. You may have to add in some &quot;jtype&quot;, &quot;jstype&quot;,
 &quot;javain&quot; and &quot;javaout&quot; typemaps when wrapping some JNI types. Here the
 default typemaps work for <tt>int</tt> and <tt>char *</tt>.</p>
<p> In summary the <tt>%native</tt> directive is telling SWIG to
 generate the Java code to access the JNI C code, but not the JNI C
 function itself. This directive is only really useful if you want to
 mix your own hand crafted JNI code and the SWIG generated code into one
 Java class or package.</p>
<h3><a name="Java_performance">26.12.4 Performance concerns and hints</a>
</h3>
<p> If you're directly manipulating huge arrays of complex objects from
 Java, performance may suffer greatly when using the array functions in <tt>
arrays_java.i</tt>. Try and minimise the expensive JNI calls to C/C++
 functions, perhaps by using temporary Java variables instead of
 accessing the information directly from the C/C++ object.</p>
<p> Java classes without any finalizers generally speed up code
 execution as there is less for the garbage collector to do. Finalizer
 generation can be stopped by using an empty <tt>javafinalize</tt>
 typemap:</p>
<div class="code">
<pre>
%typemap(javafinalize) SWIGTYPE &quot;&quot;
</pre>
</div>
<p> However, you will have to be careful about memory management and
 make sure that you code in a call to the <tt>delete()</tt> member
 function. This method normally calls the C++ destructor or <tt>free()</tt>
 for C code.</p>
<h3><a name="Java_debugging">26.12.5 Debugging</a></h3>
<p> The generated code can be debugged using both a Java debugger and a
 C++ debugger using the usual debugging techniques. Breakpoints can be
 set in either Java or C++ code and so both can be debugged
 simultaneously. Most debuggers do not understand both Java and C++,
 with one noteable exception of Sun Studio, where it is possible to step
 from Java code into a JNI method within one environment.</p>
<p> Alternatively, debugging can involve placing debug printout
 statements in the JNI layer using the <tt>%exception</tt> directive.
 See the <a href="#Customization_exception_special_variables">special
 variables for %exception</a> section. Many of the default typemaps can
 also be overridden and modified for adding in extra logging/debug
 display information.</p>
<p> The <tt>-Xcheck:jni</tt> and <tt>-Xcheck:nabounds</tt> Java
 executable options are useful for debugging to make sure the JNI code
 is behaving. The -verbose:jni and -verbose:gc are also useful options
 for monitoring code behaviour.</p>
<h2><a name="Java_examples">26.13 Java Examples</a></h2>
<p> The directory Examples/java has a number of further examples. Take a
 look at these if you want to see some of the techniques described in
 action. The Examples/index.html file in the parent directory contains
 the SWIG Examples Documentation and is a useful starting point. If your
 SWIG installation went well Unix users should be able to type <tt>make</tt>
 in each example directory, then <tt>java main</tt> to see them running.
 For the benefit of Windows users, there are also Visual C++ project
 files in a couple of the <a href="#Windows_examples">Windows Examples</a>
. There are also many regression tests in the Examples/test-suite
 directory. Many of these have runtime tests in the java subdirectory.</p>
<HR NOSHADE>
<h1><a name="Javascript">27 SWIG and Javascript</a></h1>

<!-- INDEX -->
<div class="sectiontoc">
<ul>
<li><a href="#Javascript_overview">Overview</a></li>
<li><a href="#Javascript_preliminaries">Preliminaries</a>
<ul>
<li><a href="#Javascript_running_swig">Running SWIG</a></li>
<li><a href="#Javascript_running_tests_examples">Running Tests and
 Examples</a></li>
<li><a href="#Javascript_known_issues">Known Issues</a></li>
</ul>
</li>
<li><a href="#Javascript_integration">Integration</a>
<ul>
<li><a href="#Javascript_node_extensions">Creating node.js Extensions</a>
<ul>
<li><a href="#Javascript_troubleshooting">Troubleshooting</a></li>
</ul>
</li>
<li><a href="#Javascript_embedded_webkit">Embedded Webkit</a>
<ul>
<li><a href="#Javascript_osx">Mac OS X</a></li>
<li><a href="#Javascript_gtk">GTK</a></li>
</ul>
</li>
<li><a href="#Javascript_applications_webkit">Creating Applications with
 node-webkit</a></li>
</ul>
</li>
<li><a href="#Javascript_examples">Examples</a>
<ul>
<li><a href="#Javascript_simple_example">Simple</a></li>
<li><a href="#Javascript_class_example">Class</a></li>
</ul>
</li>
<li><a href="#Javascript_implementation">Implementation</a>
<ul>
<li><a href="#Javascript_source_code">Source Code</a></li>
<li><a href="#Javascript_code_templates">Code Templates</a></li>
<li><a href="#Javascript_emitter">Emitter</a></li>
<li><a href="#Javascript_emitter_states">Emitter states</a></li>
<li><a href="#Javascript_jsc_exceptions">Handling Exceptions in
 JavascriptCore</a></li>
</ul>
</li>
</ul>
</div>
<!-- INDEX -->
<p>This chapter describes SWIG's support of Javascript. It does not
 cover SWIG basics, but only information that is specific to this
 module.</p>
<h2><a name="Javascript_overview">27.1 Overview</a></h2>
<p>Javascript is a prototype-based scripting language that is dynamic,
 weakly typed and has first-class functions. Its arguably the most
 popular language for web development. Javascript has gone beyond being
 a browser-based scripting language and with <a href="https://nodejs.org">
node.js</a>, it is also used as a backend development language.</p>
<p>Native Javascript extensions can be used for applications that embed
 a web-browser view or that embed a Javascript engine (such as<em>
 node.js</em>). Extending a general purpose web-browser is not possible
 as this would be a severe security issue.</p>
<p>SWIG Javascript currently supports<strong> JavascriptCore</strong>,
 the Javascript engine used by <code>Safari/Webkit</code>, and <a href="https://v8.dev/">
<strong>v8</strong></a>, which is used by <code>Chromium</code> and <code>
node.js</code>.</p>
<p><a href="https://webkit.org/">WebKit</a> is a modern browser
 implementation available as open-source which can be embedded into an
 application. With <a href="https://github.com/rogerwang/node-webkit">
node-webkit</a> there is a platform which uses Google's <code>Chromium</code>
 as Web-Browser widget and <code>node.js</code> for javascript
 extensions.</p>
<h2><a name="Javascript_preliminaries">27.2 Preliminaries</a></h2>
<h3><a name="Javascript_running_swig">27.2.1 Running SWIG</a></h3>
<p>Suppose that you defined a SWIG module such as the following:</p>
<div class="code">
<pre>
%module example
%{
#include &quot;example.h&quot;
%}
int gcd(int x, int y);
extern double Foo;</pre>
</div>
<p>To build a Javascript module, run SWIG using the <code>-javascript</code>
 option and a desired target engine <code>-jsc</code>, <code>-v8</code>,
 or <code>-node</code>. The generator for <code>node</code> is
 essentially delegating to the <code>v8</code> generator and adds some
 necessary preprocessor definitions.</p>
<div class="shell">
<pre>
$ swig -javascript -jsc example.i</pre>
</div>
<p>If building a C++ extension, add the -c++ option:</p>
<div class="shell">
<pre>
$ swig -c++ -javascript -jsc example.i</pre>
</div>
<p>The V8 code that SWIG generates should work with most versions from
 3.11.10 up to 3.29.14 and later.</p>
<p>The API headers for V8 &gt;= 4.3.0 define constants which SWIG can use
 to determine the V8 version it is compiling for. For versions &lt; 4.3.0,
 you need to specify the V8 version when running SWIG. This is specified
 as a hex constant, but the constant is read as pairs of decimal digits,
 so for V8 3.25.30 use constant 0x032530. This scheme can't represent
 components &gt; 99, but this constant is only useful for V8 &lt; 4.3.0, and
 no V8 versions from that era had a component &gt; 99. For example:</p>
<div class="shell">
<pre>
$ swig -c++ -javascript -v8 -DV8_VERSION=0x032530 example.i</pre>
</div>
<p>If you're targeting V8 &gt;= 4.3.0, you would just run swig like so:</p>
<div class="shell">
<pre>
$ swig -c++ -javascript -v8 example.i</pre>
</div>
<p>This creates a C/C++ source file <code>example_wrap.c</code> or <code>
example_wrap.cxx</code>. The generated C source file contains the
 low-level wrappers that need to be compiled and linked with the rest of
 your C/C++ application to create an extension module.</p>
<p>The name of the wrapper file is derived from the name of the input
 file. For example, if the input file is <code>example.i</code>, the
 name of the wrapper file is <code>example_wrap.c</code>. To change
 this, you can use the -o option. The wrapped module will export one
 function which must be called to register the module with the
 Javascript interpreter. For example, if your module is named <code>
example</code> the corresponding initializer for JavascriptCore would be</p>
<div class="code">
<pre>
bool example_initialize(JSGlobalContextRef context, JSObjectRef *exports)</pre>
</div>
<p>and for v8:</p>
<div class="code">
<pre>
void example_initialize(v8::Handle&lt;v8::Object&gt; exports)</pre>
</div>
<p><b> Note</b>: be aware that <code>v8</code> has a C++ API, and thus,
 the generated modules must be compiled as C++.</p>
<h3><a name="Javascript_running_tests_examples">27.2.2 Running Tests and
 Examples</a></h3>
<p>The configuration for tests and examples currently supports Linux and
 Mac only and not MinGW (Windows) yet.</p>
<p>The default interpreter is <code>node.js</code> as it is available on
 all platforms and convenient to use.</p>
<p>Running the examples with JavascriptCore requires <code>
libjavascriptcoregtk-1.0</code> to be installed, e.g., under Ubuntu with</p>
<div class="shell">
<pre>
$ sudo apt-get install libjavascriptcoregtk-1.0-dev</pre>
</div>
<p>Running with <code>V8</code> requires <code>libv8</code>:</p>
<div class="shell">
<pre>
$ sudo apt-get install libv8-dev</pre>
</div>
<p>Examples can be run using</p>
<div class="shell">
<pre>
$ make check-javascript-examples ENGINE=jsc</pre>
</div>
<p><code>ENGINE</code> can be <code>node</code>, <code>jsc</code>, or <code>
v8</code>.</p>
<p>The test-suite can be run using</p>
<div class="shell">
<pre>
$ make check-javascript-test-suite ENGINE=jsc</pre>
</div>
<p>You can specify a specific <code>V8</code> version for running the
 examples and tests</p>
<div class="shell">
<pre>
$ make check-javascript-examples V8_VERSION=0x032530 ENGINE=v8</pre>
</div>
<h3><a name="Javascript_known_issues">27.2.3 Known Issues</a></h3>
<p>At the moment, the Javascript generators pass all tests
 syntactically, i.e., the generated source code compiles. However, there
 are still remaining runtime issues.</p>
<ul>
<li>
<p>Default optional arguments do not work for all targeted interpreters</p>
</li>
<li>
<p>Multiple output arguments do not work for JSC</p>
</li>
<li>
<p>C89 incompatibility: the JSC generator might still generate C89
 violating code</p>
</li>
<li>
<p><code>long long</code> is not supported</p>
</li>
<li>
<p>Javascript callbacks are not supported</p>
</li>
<li>
<p><code>instanceOf</code> does not work under JSC</p>
</li>
</ul>
<p>The primary development environment has been Linux (Ubuntu 12.04).
 Windows and Mac OS X have been tested sporadically. Therefore, the
 generators might have more issues on those platforms. Please report
 back any problem you observe to help us improving this module quickly.</p>
<h2><a name="Javascript_integration">27.3 Integration</a></h2>
<p>This chapter gives a short introduction how to use a native
 Javascript extension: as a <code>node.js</code> module, and as an
 extension for an embedded Webkit.</p>
<h3><a name="Javascript_node_extensions">27.3.1 Creating node.js
 Extensions</a></h3>
<p>To install <code>node.js</code> you can download an installer from
 their <a href="https://launchpad.net/~chris-lea/+archive/node.js">
web-site</a> for Mac OS X and Windows. For Linux you can either build
 the source yourself and run <code>sudo checkinstall</code> or keep to
 the (probably stone-age) packaged version. For Ubuntu there is a <a href="https://launchpad.net/~chris-lea/+archive/ubuntu/node.js/">
PPA</a> available.</p>
<div class="shell">
<pre>
$ sudo add-apt-repository ppa:chris-lea/node.js
$ sudo apt-get update
$ sudo apt-get install nodejs</pre>
</div>
<p>As <code>v8</code> is written in C++ and comes as a C++ library it is
 crucial to compile your module using the same compiler flags as used
 for building v8. To make things easier, <code>node.js</code> provides a
 build tool called <code>node-gyp</code>.</p>
<p>You have to install it using <code>npm</code>:</p>
<div class="shell">
<pre>
$ sudo npm install -g node-gyp</pre>
</div>
<p><code>node-gyp</code> expects a configuration file named <code>
binding.gyp</code> which is basically in JSON format and conforms to the
 same format that is used with Google's build-tool <code>gyp</code>.</p>
<p><code>binding.gyp</code>:</p>
<div class="code">
<pre>
{
  &quot;targets&quot;: [
    {
      &quot;target_name&quot;: &quot;example&quot;,
      &quot;sources&quot;: [ &quot;example.cxx&quot;, &quot;example_wrap.cxx&quot; ]
    }
  ]
}</pre>
</div>
<p>First create the wrapper using SWIG:</p>
<div class="shell">
<pre>
$ swig -javascript -node -c++ example.i</pre>
</div>
<p>Then run <code>node-gyp build</code> to actually create the module:</p>
<div class="shell">
<pre>
$ node-gyp build</pre>
</div>
<p>This will create a <code>build</code> folder containing the native
 module. To use the extension you need to 'require' it in your
 Javascript source file:</p>
<div class="code">
<pre>
require(&quot;./build/Release/example&quot;)</pre>
</div>
<p>A more detailed explanation is given in the <a href="#Javascript_examples">
Examples</a> section.</p>
<h4><a name="Javascript_troubleshooting">27.3.1.1 Troubleshooting</a></h4>
<ul>
<li><em>'module' object has no attribute 'script_main'</em></li>
</ul>
<p>This error happens when <code>gyp</code> is installed as a
 distribution package. It seems to be outdated. Removing it resolves the
 problem.</p>
<div class="shell">
<pre>
$ sudo apt-get remove gyp</pre>
</div>
<h3><a name="Javascript_embedded_webkit">27.3.2 Embedded Webkit</a></h3>
<p>Webkit is pre-installed on Mac OS X and available as a library for
 GTK.</p>
<h4><a name="Javascript_osx">27.3.2.1 Mac OS X</a></h4>
<p>There is general information about programming with WebKit on <a href="https://developer.apple.com/library/mac/documentation/cocoa/conceptual/DisplayWebContent/DisplayWebContent.html">
Apple Developer Documentation</a>. Details about <code>Cocoa</code>
 programming are not covered here.</p>
<p>An integration of a native extension 'example' would look like this:</p>
<div class="code">
<pre>
#import &quot;appDelegate.h&quot;

extern bool example_initialize(JSGlobalContextRef context, JSObjectRef* exports);


@implementation ExampleAppDelegate

@synthesize webView;

- (void)addGlobalObject:(JSContextRef) context:(NSString *)objectName:(JSObjectRef) theObject {
  JSObjectRef global = JSContextGetGlobalObject(context);
  JSStringRef objectJSName = JSStringCreateWithCFString( (CFStringRef) objectName )
  if ( objectJSName != NULL ) {
    JSObjectSetProperty(context, global, objectJSName, theObject, kJSPropertyAttributeReadOnly, NULL);
    JSStringRelease( objectJSName );
  }
}

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {

  // Start a webview with the bundled index.html file
  NSString *path = [[NSBundle mainBundle] bundlePath];
  NSString *url =  [NSString stringWithFormat: @&quot;file://%@/Contents/Assets/index.html&quot;, path];

  WebFrame *webframe = [webView mainFrame];
  JSGlobalContextRef context = [webframe globalContext];

  JSObjectRef example;
  example_initialize(context, &amp;example);
  [self addGlobalObject:context:@&quot;example&quot;:example]

  JSObjectSetProperty(context, global, JSStringRef propertyName, example, JSPropertyAttributes attributes, NULL);

  [ [webView mainFrame] loadRequest:
    [NSURLRequest requestWithURL: [NSURL URLWithString:url] ]
  ];
}

@end</pre>
</div>
<h4><a name="Javascript_gtk">27.3.2.2 GTK</a></h4>
<p>There is general information about programming GTK at <a href="https://developer.gnome.org/gtk2/">
GTK documentation</a> and in the <a href="https://developer.gnome.org/gtk-tutorial/">
GTK tutorial</a>, and for Webkit there is a <a href="http://webkitgtk.org/reference/webkitgtk/stable/index.html">
Webkit GTK+ API Reference</a>.</p>
<p>An integration of a native extension 'example' would look like this:</p>
<div class="code">
<pre>
#include &lt;gtk/gtk.h&gt;
#include &lt;webkit/webkit.h&gt;

extern bool example_initialize(JSGlobalContextRef context);

int main(int argc, char* argv[])
{
  // Initialize GTK+
  gtk_init(&amp;argc, &amp;argv);

  ...

  // Create a browser instance
  WebKitWebView *webView = WEBKIT_WEB_VIEW(webkit_web_view_new());
  WebFrame *webframe = webkit_web_view_get_main_frame(webView);
  JSGlobalContextRef context = webkit_web_frame_get_global_context(webFrame);
  JSObjectRef global = JSContextGetGlobalObject(context);

  JSObjectRef exampleModule;
  example_initialize(context, &amp;exampleModule);
  JSStringRef jsName = JSStringCreateWithUTF8CString(&quot;example&quot;);
  JSObjectSetProperty(context, global, jsName, exampleModule, kJSPropertyAttributeReadOnly, NULL);
  JSStringRelease(jsName);

  ...

  // Load a web page into the browser instance
  webkit_web_view_load_uri(webView, &quot;http://www.webkitgtk.org/&quot;);

  ...

  // Run the main GTK+ event loop
  gtk_main();

  return 0;
}</pre>
</div>
<h3><a name="Javascript_applications_webkit">27.3.3 Creating
 Applications with node-webkit</a></h3>
<p>To get started with <code>node-webkit</code> there is a very
 informative set of <a href="https://github.com/rogerwang/node-webkit/wiki">
wiki pages</a>.</p>
<p>Similar to <code>node.js</code>, <code>node-webkit</code> is started
 from command line within a <code>node.js</code> project directory.
 Native extensions are created in the very same way as for <code>node.js</code>
, except that a customized <code>gyp</code> derivate has to be used: <a href="https://github.com/rogerwang/nw-gyp">
nw-gyp</a>.</p>
<p> A simple example would have the following structure:</p>
<div class="code">
<pre>
- package.json
- app.html
- app.js
- node_modules
  / example
  ... (as known from node.js)
</pre>
</div>
<p> The configuration file essentially conforms to <code>node.js</code>
 syntax. It has some extras to configure <code>node-webkit</code>. See
 the <a href="https://github.com/rogerwang/node-webkit/wiki/Manifest-format">
Manifest</a> specification for more details.</p>
<p> <code>package.json</code>:</p>
<div class="code">
<pre>
{
  &quot;name&quot;: &quot;example&quot;,
  &quot;main&quot;: &quot;app.html&quot;,
  &quot;window&quot;: {
    &quot;show&quot;: true,
    &quot;width&quot;: 800,
    &quot;height&quot;: 600
  }
}</pre>
</div>
<p> The <code>'main'</code> property of <code>package.json</code>
 specifies a web-page to be rendered in the main window.</p>
<p> <code>app.html</code>:</p>
<div class="code">
<pre>
&lt;html&gt;
  &lt;head&gt;
    &lt;script src=&quot;app.js&quot;&gt;&lt;/script&gt;
  &lt;/head&gt;
  &lt;body&gt;
    &lt;div&gt;
      The greatest common divisor of
      &lt;span id=&quot;x&quot;&gt;&lt;/span&gt; and
      &lt;span id=&quot;y&quot;&gt;&lt;/span&gt; is
      &lt;span id=&quot;z&quot;&gt;&lt;/span&gt;.
    &lt;/div&gt;
  &lt;/body&gt;
&lt;/html&gt;</pre>
</div>
<p> As known from <code>node.js</code> one can use <code>require</code>
 to load javascript modules. Additionally, <code>node-webkit</code>
 provides an API that allows to manipulate the window's menu, open new
 windows, and many more things.</p>
<p> <code>app.js</code>:</p>
<div class="code">
<pre>window.onload = function() {
  var example = require(&quot;example&quot;);
  var x = 18;
  var y = 24;
  var z = example.gcd(x, y);
  document.querySelector('#x').innerHTML = x;
  document.querySelector('#y').innerHTML = y;
  document.querySelector('#z').innerHTML = z;
};</pre>
</div>
<h2><a name="Javascript_examples">27.4 Examples</a></h2>
<p>Some basic examples are shown here in more detail.</p>
<h3><a name="Javascript_simple_example">27.4.1 Simple</a></h3>
<p>The common example <code>simple</code> looks like this:</p>
<div class="code">
<pre>
/* File : example.i */
%module example

%inline %{
extern int    gcd(int x, int y);
extern double Foo;
%}</pre>
</div>
<p>To make this available as a node extension a <code>binding.gyp</code>
 has to be created:</p>
<div class="code">
<pre>
{
  &quot;targets&quot;: [
    {
      &quot;target_name&quot;: &quot;example&quot;,
      &quot;sources&quot;: [ &quot;example.cxx&quot;, &quot;example_wrap.cxx&quot; ]
    }
  ]
}</pre>
</div>
<p>Then <code>node-gyp</code> is used to build the extension:</p>
<div class="shell">
<pre>
$ node-gyp configure build</pre>
</div>
<p>From a 'nodejs` application the extension would be used like this:</p>
<div class="code">
<pre>
// import the extension via require
var example = require(&quot;./build/Release/example&quot;);

// calling the global method
var x = 42;
var y = 105;
var g = example.gcd(x, y);

// Accessing the global variable
var f = example.Foo;
example.Foo = 3.1415926;</pre>
</div>
<p>First the module <code>example</code> is loaded from the previously
 built extension. Global methods and variables are available in the
 scope of the module.</p>
<p><b>Note</b>: ECMAScript 5, the currently implemented Javascript
 standard, does not have modules. <code>node.js</code> and other
 implementations provide this mechanism defined by the <a href="http://wiki.commonjs.org/wiki/CommonJS">
CommonJS</a> group. For browsers this is provided by <a href="http://browserify.org">
Browserify</a>, for instance.</p>
<h3><a name="Javascript_class_example">27.4.2 Class</a></h3>
<p>The common example <code>class</code> defines three classes, <code>
Shape</code>, <code>Circle</code>, and <code>Square</code>:</p>
<div class="code">
<pre>
class Shape {
public:
  Shape() {
    nshapes++;
  }
  virtual ~Shape() {
    nshapes--;
  }
  double  x, y;
  void    move(double dx, double dy);
  virtual double area(void) = 0;
  virtual double perimeter(void) = 0;
  static  int nshapes;
};

class Circle : public Shape {
private:
  double radius;
public:
  Circle(double r) : radius(r) { }
  virtual double area(void);
  virtual double perimeter(void);
};

class Square : public Shape {
private:
  double width;
public:
  Square(double w) : width(w) { }
  virtual double area(void);
  virtual double perimeter(void);
};</pre>
</div>
<p><code>Circle</code> and <code>Square</code> inherit from <code>Shape</code>
. <code>Shape</code> has a static variable <code>nshapes</code>, a
 function <code>move</code> that can't be overridden (non-virtual), and
 two abstract functions <code>area</code> and <code>perimeter</code>
 (pure virtual) that must be overridden by the sub-classes.</p>
<p>A <code>nodejs</code> extension is built the same way as for the <code>
simple</code> example.</p>
<p>In Javascript it can be used as follows:</p>
<div class="code">
<pre>
var example = require(&quot;./build/Release/example&quot;);

// local aliases for convenience
var Shape = example.Shape;
var Circle = example.Circle;
var Square = example.Square;

// creating new instances using the 'new' operator
var c = new Circle(10);
var s = new Square(10);

// accessing a static member
Shape.nshapes;

// accessing member variables
c.x = 20;
c.y = 30;
s.x = -10;
s.y = 5;

// calling some methods
c.area();
c.perimeter();
s.area();
s.perimeter();

// instantiation of Shape is not permitted
new Shape();</pre>
</div>
<p>Running these commands in an interactive node shell results in the
 following output:</p>
<div class="shell">
<pre>
$ node -i
&amp; var example = require(&quot;./build/Release/example&quot;);
undefined
&amp; var Shape = example.Shape;
undefined
&amp; var Circle = example.Circle;
undefined
&amp; var Square = example.Square;
undefined
&amp; var c = new Circle(10);
undefined
&amp; var s = new Square(10);
undefined
&amp; Shape.nshapes;
2
&amp; c.x = 20;
20
&amp; c.y = 30;
30
&amp; s.x = -10;
-10
&amp; s.y = 5;
5
&amp; c.area();
314.1592653589793
&amp; c.perimeter();
62.83185307179586
&amp; s.area();
100
&amp; s.perimeter();
40
&amp; c.move(40, 40)
undefined
&amp; c.x
60
&amp; c.y
70
&amp; new Shape()
Error: Class Shape can not be instantiated
at repl:1:2
at REPLServer.self.eval (repl.js:110:21)
at Interface.&lt;anonymous&gt; (repl.js:239:12)
at Interface.EventEmitter.emit (events.js:95:17)
at Interface._onLine (readline.js:202:10)
at Interface._line (readline.js:531:8)
at Interface._ttyWrite (readline.js:760:14)
at ReadStream.onkeypress (readline.js:99:10)
at ReadStream.EventEmitter.emit (events.js:98:17)
at emitKey (readline.js:1095:12)</pre>
</div>
<p><b> Note</b>: In ECMAScript 5 there is no concept for classes.
 Instead each function can be used as a constructor function which is
 executed by the 'new' operator. Furthermore, during construction the
 key property <code>prototype</code> of the constructor function is used
 to attach a prototype instance to the created object. A prototype is
 essentially an object itself that is the first-class delegate of a
 class used whenever the access to a property of an object fails. The
 very same prototype instance is shared among all instances of one type.
 Prototypal inheritance is explained in more detail on in <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain">
Inheritance and the prototype chain</a>, for instance.</p>
<h2><a name="Javascript_implementation">27.5 Implementation</a></h2>
<p>The Javascript Module implementation has taken a very different
 approach compared to other language modules in order to support
 different Javascript interpreters.</p>
<h3><a name="Javascript_source_code">27.5.1 Source Code</a></h3>
<p>The Javascript module is implemented in <code>
Source/Modules/javascript.cxx</code>. It dispatches the code generation
 to a <code>JSEmitter</code> instance, <code>V8Emitter</code> or <code>
JSCEmitter</code>. Additionally there are some helpers: <code>Template</code>
, for templated code generation, and <code>JSEmitterState</code>, which
 is used to manage state information during AST traversal. This rough
 map shall make it easier to find a way through this huge source file:</p>
<div class="code">
<pre>
// module wide defines

#define NAME &quot;name&quot;
...

// ###############################
// #  Helper class declarations

class JSEmitterState { ... };

class Template { ... };

// ###############################
// # JSEmitter declaration

class JSEmitter { ... };

// Emitter factory declarations

JSEmitter *swig_javascript_create_JSCEmitter();
JSEmitter *swig_javascript_create_V8Emitter();

// ###############################
// # Javascript module

// Javascript module declaration

class JAVASCRIPT:public Language { ... };

// Javascript module implementation

int JAVASCRIPT::functionWrapper(Node *n) { ... }
...

// Module factory implementation

static Language *new_swig_javascript() { ... }

extern &quot;C&quot; Language *swig_javascript(void) { ... }

// ###############################
// # JSEmitter base implementation

JSEmitter::JSEmitter() { ... }

Template JSEmitter::getTemplate(const String *name) { ... }
...

// ###############################
// # JSCEmitter

// JSCEmitter declaration

class JSCEmitter: public JSEmitter { ... };

// JSCEmitter implementation

JSCEmitter::JSCEmitter() { ... }

void JSCEmitter::marshalInputArgs(Node *n, ParmList *parms, Wrapper *wrapper, MarshallingMode mode, bool is_member, bool is_static) { ... }
...

// JSCEmitter factory

JSEmitter *swig_javascript_create_JSCEmitter() { ... }


// ###############################
// # V8Emitter

// V8Emitter declaration

class V8Emitter: public JSEmitter { ... };

// V8Emitter implementation

V8Emitter::V8Emitter() { ... }

int V8Emitter::initialize(Node *n) { ... }

// V8Emitter factory

JSEmitter *swig_javascript_create_V8Emitter() { ... }


// ###############################
// # Helper implementation (JSEmitterState, Template)

JSEmitterState::JSEmitterState() { ... }
...

Template::Template(const String *code_) { ... }
...</pre>
</div>
<h3><a name="Javascript_code_templates">27.5.2 Code Templates</a></h3>
<p>All generated code is created on the basis of code templates. The
 templates for<em> JavascriptCore</em> can be found in <code>
Lib/javascript/jsc/javascriptcode.swg</code>, for<em> v8</em> in <code>
Lib/javascript/v8/javascriptcode.swg</code>.</p>
<p>To track the originating code template for generated code you can run</p>
<div class="shell">
<pre>
$ swig -javascript -jsc -debug-codetemplates</pre>
</div>
<p>which wraps generated code with a descriptive comment</p>
<div class="code">
<pre>
/* begin fragment(&quot;template_name&quot;) */

...generated code ...

/* end fragment(&quot;template_name&quot;) */</pre>
</div>
<p>The Template class is used like this:</p>
<div class="code">
<pre>
Template t_register = getTemplate(&quot;jsv8_register_static_variable&quot;);
t_register.replace(&quot;$jsparent&quot;, state.clazz(NAME_MANGLED))
    .replace(&quot;$jsname&quot;, state.variable(NAME))
    .replace(&quot;$jsgetter&quot;, state.variable(GETTER))
    .replace(&quot;$jssetter&quot;, state.variable(SETTER))
    .trim().
    print(f_init_static_wrappers);</pre>
</div>
<p>A code template is registered with the<em> JSEmitter</em> via <code>
fragment(name, &quot;template&quot;)</code>, e.g.,</p>
<div class="code">
<pre>
%fragment (&quot;jsc_variable_declaration&quot;, &quot;templates&quot;)
%{
  {&quot;$jsname&quot;, $jsgetter, $jssetter, kJSPropertyAttributeNone},
%}</pre>
</div>
<p><code>Template</code> creates a copy of that string and <code>
Template::replace</code> uses Swig's <code>Replaceall</code> to replace
 variables in the template. <code>Template::trim</code> can be used to
 eliminate leading and trailing whitespaces. <code>Template::print</code>
 is used to write the final template string to a Swig <code>DOH</code>
 (based on <code>Printv</code>). All methods allow chaining.</p>
<h3><a name="Javascript_emitter">27.5.3 Emitter</a></h3>
<p>The Javascript module delegates code generation to a <code>JSEmitter</code>
 instance. The following extract shows the essential interface:</p>
<div class="code">
<pre>
class JSEmitter {
  ...

  /**
   * Opens output files and temporary output DOHs.
   */
  virtual int initialize(Node *n);

  /**
   * Writes all collected code into the output file(s).
   */
  virtual int dump(Node *n) = 0;

  /**
   * Cleans up all open output DOHs.
   */
  virtual int close() = 0;

  ...

  /**
   * Invoked at the beginning of the classHandler.
   */
  virtual int enterClass(Node *);

  /**
   * Invoked at the end of the classHandler.
   */
  virtual int exitClass(Node *) {
    return SWIG_OK;
  }

  /**
   * Invoked at the beginning of the variableHandler.
   */
  virtual int enterVariable(Node *);

  /**
   * Invoked at the end of the variableHandler.
   */
  virtual int exitVariable(Node *) {
    return SWIG_OK;
  }

  /**
   * Invoked at the beginning of the functionHandler.
   */
  virtual int enterFunction(Node *);

  /**
   * Invoked at the end of the functionHandler.
   */
  virtual int exitFunction(Node *) {
    return SWIG_OK;
  }

  /**
   * Invoked by functionWrapper callback after call to Language::functionWrapper.
   */
  virtual int emitWrapperFunction(Node *n);

  /**
   * Invoked from constantWrapper after call to Language::constantWrapper.
   **/
  virtual int emitConstant(Node *n);

  /**
   * Registers a given code snippet for a given key name.
   *
   * This method is called by the fragmentDirective handler
   * of the JAVASCRIPT language module.
   **/
  int registerTemplate(const String *name, const String *code);

  /**
   * Retrieve the code template registered for a given name.
   */
  Template getTemplate(const String *name);

  State &amp;getState();

  ...

}</pre>
</div>
<p>The module calls <code>initialize</code>, <code>dump</code>, and <code>
close</code> from within the <code>top</code> method:</p>
<div class="code">
<pre>
int JAVASCRIPT::top(Node *n) {
  emitter-&gt;initialize(n);

  Language::top(n);

  emitter-&gt;dump(n);
  emitter-&gt;close();

  return SWIG_OK;
}</pre>
</div>
<p>The methods <code>enterClass</code> and <code>exitClass</code> are
 called from within the <code>classHandler</code> method:</p>
<div class="code">
<pre>
int JAVASCRIPT::classHandler(Node *n) {

  emitter-&gt;enterClass(n);
  Language::classHandler(n);
  emitter-&gt;exitClass(n);

  return SWIG_OK;
}</pre>
</div>
<p>In <code>enterClass</code> the emitter stores state information that
 is necessary when processing class members. In <code>exitClass</code>
 the wrapper code for the whole class is generated.</p>
<h3><a name="Javascript_emitter_states">27.5.4 Emitter states</a></h3>
<p>For storing information during the AST traversal the emitter provides
 a <code>JSEmitterState</code> with different slots to store data
 representing the scopes global, class, function, and variable.</p>
<div class="code">
<pre>
class JSEmitterState {

public:

  JSEmitterState();

  ~JSEmitterState();

  DOH *global();

  DOH *global(const char* key, DOH *initial = 0);

  DOH *clazz(bool reset = false);

  DOH *clazz(const char* key, DOH *initial = 0);

  DOH *function(bool reset = false);

  DOH *function(const char* key, DOH *initial = 0);

  DOH *variable(bool reset = false);

  DOH *variable(const char* key, DOH *initial = 0);

  static int IsSet(DOH *val);

  ...
};</pre>
</div>
<p>When entering a scope, such as in <code>enterClass</code>, the
 corresponding state is reset and new data is stored:</p>
<div class="code">
<pre>
state.clazz(RESET);
state.clazz(NAME, Getattr(n, &quot;sym:name&quot;));</pre>
</div>
<p>State information can be retrieved using <code>state.clazz(NAME)</code>
 or with <code>Getattr</code> on <code>state.clazz()</code> which
 actually returns a <code>Hash</code> instance.</p>
<h3><a name="Javascript_jsc_exceptions">27.5.5 Handling Exceptions in
 JavascriptCore</a></h3>
<p>Applications with an embedded JavascriptCore should be able to
 present detailed exception messages that occur in the Javascript
 engine. Below is an example derived from code provided by Brian Barnes
 on how these exception details can be extracted.</p>
<div class="code">
<pre>
void script_exception_to_string(JSContextRef js_context, JSValueRef exception_value_ref, char* return_error_string, int return_error_string_max_length)
{
  JSObjectRef exception_object;
  JSValueRef value_ref;
  JSStringRef jsstring_property_name = NULL;
  JSValueRef temporary_exception = NULL;
  JSStringRef js_return_string = NULL;
  size_t bytes_needed;
  char* c_result_string = NULL;
  exception_object = JSValueToObject(js_context, exception_value_ref, NULL);

  /* source url */
  strcpy(return_error_string, &quot;[&quot;);
  jsstring_property_name = JSStringCreateWithUTF8CString(&quot;sourceURL&quot;);
  value_ref = JSObjectGetProperty(js_context, exception_object, jsstring_property_name, &amp;temporary_exception);
  JSStringRelease(jsstring_property_name);
  js_return_string = JSValueToStringCopy(js_context, value_ref, NULL);
  bytes_needed = JSStringGetMaximumUTF8CStringSize(js_return_string);
  c_result_string = (char*)calloc(bytes_needed, sizeof(char));
  JSStringGetUTF8CString(js_return_string, c_result_string, bytes_needed);
  JSStringRelease(js_return_string);
  strncat(return_error_string, c_result_string, return_error_string_max_length-1);
  free(c_result_string);

  strncat(return_error_string, &quot;:&quot;, return_error_string_max_length-1);

  /* line number */

  jsstring_property_name = JSStringCreateWithUTF8CString(&quot;line&quot;);
  value_ref = JSObjectGetProperty(js_context, exception_object, jsstring_property_name, &amp;temporary_exception);
  JSStringRelease(jsstring_property_name);
  js_return_string = JSValueToStringCopy(js_context, value_ref, NULL);
  bytes_needed = JSStringGetMaximumUTF8CStringSize(js_return_string);
  c_result_string = (char*)calloc(bytes_needed, sizeof(char));
  JSStringGetUTF8CString(js_return_string, c_result_string, bytes_needed);
  JSStringRelease(js_return_string);
  strncat(return_error_string, c_result_string, return_error_string_max_length-1);
  free(c_result_string);

  strncat(return_error_string, &quot;]&quot;, return_error_string_max_length-1);

  /* error message */

  jsstring_property_name = JSStringCreateWithUTF8CString(&quot;message&quot;);
  value_ref = JSObjectGetProperty(js_context, exception_object, jsstring_property_name, &amp;temporary_exception);
  JSStringRelease(jsstring_property_name);
  if(NULL == value_ref)
  {
    strncat(return_error_string, &quot;Unknown Error&quot;, return_error_string_max_length-1);
  }
  else
  {
    js_return_string = JSValueToStringCopy(js_context, value_ref, NULL);
    bytes_needed = JSStringGetMaximumUTF8CStringSize(js_return_string);
    c_result_string = (char*)calloc(bytes_needed, sizeof(char));
    JSStringGetUTF8CString(js_return_string, c_result_string, bytes_needed);
    JSStringRelease(js_return_string);
    strncat(return_error_string, c_result_string, return_error_string_max_length-1);
    free(c_result_string);
  }
}</pre>
</div>
<p>It would be used in the following way:</p>
<div class="code">
<pre>
if(js_exception)
{
  char return_error_string[256];
  script_exception_to_string(js_context, js_exception, return_error_string, 256);
  printf(&quot;Compile error is %s&quot;, return_error_string);
}</pre>
</div><HR NOSHADE>
<h1><a name="Lua">28 SWIG and Lua</a></h1>

<!-- INDEX -->
<div class="sectiontoc">
<ul>
<li><a href="#Lua_nn2">Preliminaries</a></li>
<li><a href="#Lua_nn3">Running SWIG</a>
<ul>
<li><a href="#Lua_commandline">Additional command line options</a></li>
<li><a href="#Lua_nn4">Compiling and Linking and Interpreter</a></li>
<li><a href="#Lua_nn5">Compiling a dynamic module</a></li>
<li><a href="#Lua_nn6">Using your module</a></li>
</ul>
</li>
<li><a href="#Lua_nn7">A tour of basic C/C++ wrapping</a>
<ul>
<li><a href="#Lua_nn8">Modules</a></li>
<li><a href="#Lua_nn9">Functions</a></li>
<li><a href="#Lua_nn10">Global variables</a></li>
<li><a href="#Lua_nn11">Constants and enums</a>
<ul>
<li><a href="#Lua_nn13">Constants/enums and classes/structures</a></li>
</ul>
</li>
<li><a href="#Lua_nn12">Pointers</a></li>
<li><a href="#Lua_structures">Structures</a></li>
<li><a href="#Lua_nn14">C++ classes</a></li>
<li><a href="#Lua_nn15">C++ inheritance</a></li>
<li><a href="#Lua_nn16">Pointers, references, values, and arrays</a></li>
<li><a href="#Lua_nn17">C++ overloaded functions</a></li>
<li><a href="#Lua_nn18">C++ operators</a></li>
<li><a href="#Lua_nn19">Class extension with %extend</a></li>
<li><a href="#Lua_nn20">Using %newobject to release memory</a></li>
<li><a href="#Lua_nn21">C++ templates</a></li>
<li><a href="#Lua_nn22">C++ Smart Pointers</a></li>
<li><a href="#Lua_nn23">C++ Exceptions</a></li>
<li><a href="#Lua_namespaces">Namespaces</a>
<ul>
<li><a href="#Lua_nn27">Compatibility Note</a></li>
<li><a href="#Lua_nn29">Names</a></li>
<li><a href="#Lua_nn30">Inheritance</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#Lua_nn24">Typemaps</a>
<ul>
<li><a href="#Lua_nn25">What is a typemap?</a></li>
<li><a href="#Lua_nn26">Using typemaps</a></li>
<li><a href="#Lua_typemap_arrays">Typemaps and arrays</a></li>
<li><a href="#Lua_typemaps_ptr_ptr_functions">Typemaps and
 pointer-pointer functions</a></li>
</ul>
</li>
<li><a href="#Lua_writing_typemaps">Writing typemaps</a>
<ul>
<li><a href="#Lua_typemaps_write">Typemaps you can write</a></li>
<li><a href="#Lua_nn31">SWIG's Lua-C API</a></li>
</ul>
</li>
<li><a href="#Lua_nn32">Customization of your Bindings</a>
<ul>
<li><a href="#Lua_nn33">Writing your own custom wrappers</a></li>
<li><a href="#Lua_nn34">Adding additional Lua code</a></li>
</ul>
</li>
<li><a href="#Lua_nn35">Details on the Lua binding</a>
<ul>
<li><a href="#Lua_nn36">Binding global data into the module.</a></li>
<li><a href="#Lua_nn37">Userdata and Metatables</a></li>
<li><a href="#Lua_nn38">Memory management</a></li>
</ul>
</li>
</ul>
</div>
<!-- INDEX -->
<p> Lua is an extension programming language designed to support general
 procedural programming with data description facilities. It also offers
 good support for object-oriented programming, functional programming,
 and data-driven programming. Lua is intended to be used as a powerful,
 light-weight configuration language for any program that needs one. Lua
 is implemented as a library, written in clean C (that is, in the common
 subset of ISO C and C++). It's also a<em> really</em> tiny language,
 less than 6000 lines of code, which compiles to &lt;100 kilobytes of
 binary code. It can be found at <a href="http://www.lua.org">
http://www.lua.org</a></p>
<p> eLua stands for Embedded Lua (can be thought of as a flavor of Lua)
 and offers the full implementation of the Lua programming language to
 the embedded world, extending it with specific features for efficient
 and portable software embedded development. eLua runs on smaller
 devices like microcontrollers and provides the full features of the
 regular Lua desktop version. More information on eLua can be found
 here: <a href="http://www.eluaproject.net">http://www.eluaproject.net</a>
</p>
<h2><a name="Lua_nn2">28.1 Preliminaries</a></h2>
<p> The current SWIG implementation is designed to work with Lua 5.0.x,
 5.1.x and 5.2.x. It should work with later versions of Lua, but
 certainly not with Lua 4.0 due to substantial API changes. It is
 possible to either static link or dynamic link a Lua module into the
 interpreter (normally Lua static links its libraries, as dynamic
 linking is not available on all platforms). SWIG also has support for
 eLua starting from eLua 0.8. Due to substantial changes between SWIG
 2.x and SWIG 3.0 and unavailability of testing platform, eLua status
 was downgraded to 'experimental'.</p>
<h2><a name="Lua_nn3">28.2 Running SWIG</a></h2>
<p> Suppose that you defined a SWIG module such as the following:</p>
<div class="code">
<pre>
%module example
%{
#include &quot;example.h&quot;
%}
int gcd(int x, int y);
extern double Foo;
</pre>
</div>
<p> To build a Lua module, run SWIG using the <tt>-lua</tt> option.</p>
<div class="shell">
<pre>
$ swig -lua example.i
</pre>
</div>
<p> If building a C++ extension, add the <tt>-c++</tt> option:</p>
<div class="shell">
<pre>
$ swig -c++ -lua example.i
</pre>
</div>
<p> This creates a C/C++ source file <tt>example_wrap.c</tt> or <tt>
example_wrap.cxx</tt>. The generated C source file contains the
 low-level wrappers that need to be compiled and linked with the rest of
 your C/C++ application to create an extension module.</p>
<p> The name of the wrapper file is derived from the name of the input
 file. For example, if the input file is <tt>example.i</tt>, the name of
 the wrapper file is <tt>example_wrap.c</tt>. To change this, you can
 use the -o option. The wrapped module will export one function <tt>&quot;int
 luaopen_example(lua_State* L)&quot;</tt> which must be called to register
 the module with the Lua interpreter. The name &quot;luaopen_example&quot; depends
 upon the name of the module.</p>
<p> To build an eLua module, run SWIG using <tt>-lua</tt> and add either
 <tt>-elua</tt> or <tt>-eluac</tt>.</p>
<div class="shell">
<pre>
$ swig -lua -elua example.i
</pre>
</div>
<p> or</p>
<div class="shell">
<pre>
$ swig -lua -eluac example.i
</pre>
</div>
<p> The <tt>-elua</tt> option puts all the C function wrappers and
 variable get/set wrappers in rotables. It also generates a metatable
 which will control the access to these variables from eLua. It also
 offers a significant amount of module size compression. On the other
 hand, the <tt>-eluac</tt> option puts all the wrappers in a single
 rotable. With this option, no matter how huge the module, it will
 consume no additional microcontroller SRAM (crass compression). There
 is a catch though: Metatables are not generated with <tt>-eluac</tt>.
 To access any value from eLua, one must directly call the wrapper
 function associated with that value.</p>
<h3><a name="Lua_commandline">28.2.1 Additional command line options</a></h3>
<p> The following table list the additional commandline options
 available for the Lua module. They can also be seen by using:</p>
<div class="shell">
<pre>
swig -lua -help 
</pre>
</div>
<table summary="Lua specific options">
<tr><th>Lua specific options</th></tr>
<tr><td>-elua</td><td>Generates LTR compatible wrappers for smaller
 devices running elua.</td></tr>
<tr><td>-eluac</td><td>LTR compatible wrappers in &quot;crass compress&quot; mode
 for elua.</td></tr>
<tr><td>-nomoduleglobal</td><td>Do not register the module name as a
 global variable but return the module table from calls to require.</td></tr>
<tr><td>-no-old-metatable-bindings</td><td>Disable backward
 compatibility: old-style binding names generations and a few other
 things. Explanations are included in appropriate later sections.</td></tr>
<tr><td>-squash-bases</td><td>Squashes symbols from all inheritance tree
 of a given class into itself. Emulates pre-SWIG3.0 inheritance.
 Insignificantly speeds things up, but increases memory consumption.</td>
</tr>
</table>
<h3><a name="Lua_nn4">28.2.2 Compiling and Linking and Interpreter</a></h3>
<p> Normally Lua is embedded into another program and will be statically
 linked. An extremely simple stand-alone interpreter (<tt>min.c</tt>) is
 given below:</p>
<div class="code">
<pre>
#include &lt;stdio.h&gt;
#include &quot;lua.h&quot;
#include &quot;lualib.h&quot;
#include &quot;lauxlib.h&quot;

extern int luaopen_example(lua_State* L); // declare the wrapped module

int main(int argc, char* argv[])
{
 lua_State *L;
 if (argc&lt;2)
 {
  printf(&quot;%s: &lt;filename.lua&gt;\n&quot;, argv[0]);
  return 0;
 }
 L=lua_open();
 luaopen_base(L);       // load basic libs (eg. print)
 luaopen_example(L);    // load the wrapped module
 if (luaL_loadfile(L, argv[1])==0) // load and run the file
  lua_pcall(L, 0, 0, 0);
 else
  printf(&quot;unable to load %s\n&quot;, argv[1]);
 lua_close(L);
 return 0;
}
</pre>
</div>
<p> A much improved set of code can be found in the Lua distribution <tt>
src/lua/lua.c</tt>. Include your module, just add the external
 declaration &amp; add a <tt>#define LUA_EXTRALIBS {&quot;example&quot;,
 luaopen_example}</tt>, at the relevant place.</p>
<p> The exact commands for compiling and linking vary from platform to
 platform. Here is a possible set of commands of doing this:</p>
<div class="shell">
<pre>
$ swig -lua example.i -o example_wrap.c
$ gcc -I/usr/include/lua -c min.c -o min.o
$ gcc -I/usr/include/lua -c example_wrap.c -o example_wrap.o
$ gcc -c example.c -o example.o
$ gcc -I/usr/include/lua -L/usr/lib/lua min.o example_wrap.o example.o -o my_lua
</pre>
</div>
<p> For eLua, the source must be built along with the wrappers generated
 by SWIG. Make sure the eLua source files <tt>platform_conf.h</tt> and <tt>
auxmods.h</tt> are updated with the entries of your new module. Please
 note: <tt>&quot;mod&quot;</tt> is the module name.</p>
<div class="code">
<pre>
/* Sample platform_conf.h */
#define LUA_PLATFORM_LIBS_ROM\
  _ROM( AUXLIB_PIO, luaopen_pio, pio_map )\
  _ROM( AUXLIB_TMR, luaopen_tmr, tmr_map )\
  _ROM( AUXLIB_MOD, luaopen_mod, mod_map )\
  ....
</pre>
</div><div class="code">
<pre>
/* Sample auxmods.h */
#define AUXLIB_PIO       &quot;pio&quot;
LUALIB_API int ( luaopen_pio )(lua_State *L );

#define AUXLIB_MOD       &quot;mod&quot;
LUALIB_API int ( luaopen_mod )(lua_State *L );
....
</pre>
</div>
<p> More information on building and configuring eLua can be found here:
 <a href="http://www.eluaproject.net/doc/v0.8/en_building.html">
http://www.eluaproject.net/doc/v0.8/en_building.html</a></p>
<h3><a name="Lua_nn5">28.2.3 Compiling a dynamic module</a></h3>
<p> Most, but not all platforms support the dynamic loading of modules
 (Windows &amp; Linux do). Refer to the Lua manual to determine if your
 platform supports it. For compiling a dynamically loaded module the
 same wrapper can be used. Assuming you have code you need to link to in
 a file called <tt>example.c</tt>, the commands will be something like
 this:</p>
<div class="shell">
<pre>
$ swig -lua example.i -o example_wrap.c
$ gcc -fPIC -I/usr/include/lua -c example_wrap.c -o example_wrap.o
$ gcc -fPIC -c example.c -o example.o
$ gcc -shared -I/usr/include/lua -L/usr/lib/lua example_wrap.o example.o -o example.so
</pre>
</div>
<p> The wrappers produced by SWIG can be compiled and linked with Lua
 5.1.x and later. The loading is extremely simple.</p>
<div class="targetlang">
<pre>
require(&quot;example&quot;)
</pre>
</div>
<p> For those using Lua 5.0.x, you will also need an interpreter with
 the loadlib function (such as the default interpreter compiled with
 Lua). In order to dynamically load a module you must call the loadlib
 function with two parameters: the filename of the shared library, and
 the function exported by SWIG. Calling loadlib should return the
 function, which you then call to initialise the module</p>
<div class="targetlang">
<pre>
my_init=loadlib(&quot;example.so&quot;, &quot;luaopen_example&quot;) -- for Unix/Linux
--my_init=loadlib(&quot;example.dll&quot;, &quot;luaopen_example&quot;) -- for Windows
assert(my_init) -- make sure it's not nil
my_init()       -- call the init fn of the lib
</pre>
</div>
<p> Or can be done in a single line of Lua code</p>
<div class="targetlang">
<pre>
assert(loadlib(&quot;example.so&quot;, &quot;luaopen_example&quot;))()
</pre>
</div>
<p> If the code didn't work, don't panic. The best thing to do is to
 copy the module and your interpreter into a single directory and then
 execute the interpreter and try to manually load the module (take care,
 all this code is case sensitive).</p>
<div class="targetlang">
<pre>
a, b, c=package.loadlib(&quot;example.so&quot;, &quot;luaopen_example&quot;) -- for Unix/Linux
--a, b, c=package.loadlib(&quot;example.dll&quot;, &quot;luaopen_example&quot;) -- for Windows
print(a, b, c)
</pre>
</div>
<p> Note: for Lua 5.0:
<br> The loadlib() function is in the global namespace, not in a
 package. So it's just loadlib().</p>
<p> if 'a' is a function, this is all working fine, all you need to do
 is call it</p>
<div class="targetlang">
<pre>
  a()
</pre>
</div>
<p> to load your library which will add a table 'example' with all the
 functions added.</p>
<p> If it doesn't work, look at the error messages, in particular
 message 'b'
<br> <tt> The specified module could not be found.</tt>
<br> Means that is cannot find the module, check your the location and
 spelling of the module.
<br> <tt> The specified procedure could not be found.</tt>
<br> Means that it loaded the module, but cannot find the named
 function. Again check the spelling, and if possible check to make sure
 the functions were exported correctly.
<br> <tt> 'loadlib' not installed/supported</tt>
<br> Is quite obvious (Go back and consult the Lua documents on how to
 enable loadlib for your platform).</p>
<h3><a name="Lua_nn6">28.2.4 Using your module</a></h3>
<p> Assuming all goes well, you will be able to this:</p>
<div class="targetlang">
<pre>
$ ./my_lua
&gt; print(example.gcd(4, 6))
2
&gt; print(example.Foo)
3
&gt; example.Foo=4
&gt; print(example.Foo)
4
&gt;
</pre>
</div>
<h2><a name="Lua_nn7">28.3 A tour of basic C/C++ wrapping</a></h2>
<p> By default, SWIG tries to build a very natural Lua interface to your
 C/C++ code. This section briefly covers the essential aspects of this
 wrapping.</p>
<h3><a name="Lua_nn8">28.3.1 Modules</a></h3>
<p> The SWIG module directive specifies the name of the Lua module. If
 you specify `module example', then everything is wrapped into a Lua
 table 'example' containing all the functions and variables. When
 choosing a module name, make sure you don't use the same name as a
 built-in Lua command or standard module name.</p>
<h3><a name="Lua_nn9">28.3.2 Functions</a></h3>
<p> Global functions are wrapped as new Lua built-in functions. For
 example,</p>
<div class="code">
<pre>
%module example
int fact(int n);</pre>
</div>
<p> creates a built-in function <tt>example.fact(n)</tt> that works
 exactly like you think it does:</p>
<div class="targetlang">
<pre>
&gt; print example.fact(4)
24
&gt;
</pre>
</div>
<p> To avoid name collisions, SWIG create a Lua table which keeps all
 the functions, constants, classes and global variables in. It is
 possible to copy the functions, constants and classes (but not
 variables) out of this and into the global environment with the
 following code. This can easily overwrite existing functions, so this
 must be used with care. This option is considered deprecated and will
 be removed in the near future.</p>
<div class="targetlang">
<pre>
&gt; for k, v in pairs(example) do _G[k]=v end
&gt; print(fact(4))
24
&gt;
</pre>
</div>
<p> It is also possible to rename the module with an assignment.</p>
<div class="targetlang">
<pre>
&gt; e=example
&gt; print(e.fact(4))
24
&gt; print(example.fact(4))
24
</pre>
</div>
<h3><a name="Lua_nn10">28.3.3 Global variables</a></h3>
<p> Global variables (which are linked to C code) are supported, and
 appear to be just another variable in Lua. However the actual mechanism
 is more complex. Given a global variable:</p>
<div class="code">
<pre>%module example
extern double Foo;
</pre>
</div>
<p> SWIG will effectively generate two functions <tt>example.Foo_set()</tt>
 and <tt>example.Foo_get()</tt>. It then adds a metatable to the table
 'example' to call these functions at the correct time (when you attempt
 to set or get examples.Foo). Therefore if you were to attempt to assign
 the global to another variable, you will get a local copy within the
 interpreter, which is no longer linked to the C code.</p>
<div class="targetlang">
<pre>
&gt; print(example.Foo)
3
&gt; c=example.Foo   -- c is a COPY of example.Foo, not the same thing
&gt; example.Foo=4
&gt; print(c)
3
&gt; c=5 -- this will not effect the original example.Foo
&gt; print(example.Foo, c)
4    5
</pre>
</div>
<p> It is therefore not possible to 'move' the global variable into the
 global namespace as it is with functions. It is however, possible to
 rename the module with an assignment, to make it more convenient.</p>
<div class="targetlang">
<pre>
&gt; e=example
&gt; -- e and example are the same table
&gt; -- so e.Foo and example.Foo are the same thing
&gt; example.Foo=4
&gt; print(e.Foo)
4
</pre>
</div>
<p> If a variable is marked with the %immutable directive then any
 attempts to set this variable will cause a Lua error. Given a global
 variable:</p>
<div class="code">
<pre>%module example
%immutable;
extern double Foo;
%mutable;
</pre>
</div>
<p> SWIG will allow the reading of <tt>Foo</tt> but when a set attempt
 is made, an error function will be called.</p>
<div class="targetlang">
<pre>
&gt; print(e.Foo) -- reading works ok
4
&gt; example.Foo=40 -- but writing does not
This variable is immutable
stack traceback:
        [C]: ?
        [C]: ?
        stdin:1: in main chunk
        [C]: ?
</pre>
</div>
<p> For those people who would rather that SWIG silently ignore the
 setting of immutables (as previous versions of the Lua bindings did),
 adding a <tt>-DSWIGLUA_IGNORE_SET_IMMUTABLE</tt> compile option will
 remove this.</p>
<p> Unlike earlier versions of the binding, it is now possible to add
 new functions or variables to the module, just as if it were a normal
 table. This also allows the user to rename/remove existing functions
 and constants (but not linked variables, mutable or immutable).
 Therefore users are recommended to be careful when doing so.</p>
<div class="targetlang">
<pre>
&gt; -- example.PI does not exist
&gt; print(example.PI)
nil
&gt; example.PI=3.142 -- new value added
&gt; print(example.PI)
3.142
</pre>
</div>
<p> If you have used the <tt>-eluac</tt> option for your eLua module,
 you will have to follow a different approach while manipulating global
 variables. (This is not applicable for wrappers generated with <tt>
-elua</tt>)</p>
<div class="targetlang">
<pre>
&gt; -- Applicable only with -eluac. (num is defined)
&gt; print(example.num_get())
20
&gt; example.num_set(50) -- new value added
&gt; print(example.num_get())
50
</pre>
</div>
<p> In general, functions of the form <tt>&quot;variable_get()&quot;</tt> and <tt>
&quot;variable_set()&quot;</tt> are automatically generated by SWIG for use with <tt>
-eluac</tt>.</p>
<h3><a name="Lua_nn11">28.3.4 Constants and enums</a></h3>
<p> Because Lua doesn't really have the concept of constants, C/C++
 constants are not really constant in Lua. They are actually just a copy
 of the value into the Lua interpreter. Therefore they can be changed
 just as any other value. For example given some constants:</p>
<div class="code">
<pre>%module example
%constant int ICONST=42;
#define    SCONST      &quot;Hello World&quot;
enum Days{SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY};
</pre>
</div>
<p> This is 'effectively' converted into the following Lua code:</p>
<div class="targetlang">
<pre>
example.ICONST=42
example.SCONST=&quot;Hello World&quot;
example.SUNDAY=0
....
</pre>
</div>
<p> Constants are not guaranteed to remain constant in Lua. The name of
 the constant could be accidentally reassigned to refer to some other
 object. Unfortunately, there is no easy way for SWIG to generate code
 that prevents this. You will just have to be careful.</p>
<p> If you're using eLua and have used <tt>-elua</tt> or <tt>-eluac</tt>
 to generate your wrapper, macro constants and enums should be accessed
 through a rotable called <tt>&quot;const&quot;</tt>. In eLua, macro constants and
 enums are guaranteed to remain constants since they are all contained
 within a rotable. A regular C constant is accessed from eLua just as if
 it were a regular global variable, just that the property of value
 immutability is demonstrated if an attempt at modifying a C constant is
 made.</p>
<div class="targetlang">
<pre>
&gt; print(example.ICONST)
10
&gt; print(example.const.SUNDAY)
0
&gt; print(example.const.SCONST)
Hello World
</pre>
</div>
<h4><a name="Lua_nn13">28.3.4.1 Constants/enums and classes/structures</a>
</h4>
<p> Enums are exported into a class table. For example, given some
 enums:</p>
<div class="code">
<pre>%module example
enum Days { SUNDAY = 0, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY };
struct Test {
  enum { TEST1 = 10, TEST2 = 20 };
#ifdef __cplusplus // There are no static members in C
  static const int ICONST = 12;
#endif
};
</pre>
</div>
<p> There is a slight difference in behaviour wrapping C and C++ code
 due to the different scoping rules of C and C++. The wrapped C++ code
 is used as follows from Lua code:</p>
<div class="targetlang">
<pre>
&gt; print(example.SUNDAY)
0
&gt; print(example.Test.TEST1)
10
&gt; print(example.Test.ICONST)
12
</pre>
</div>
<p>Enums within a C struct are in the global namespace and are used as
 follows from Lua</p>
<div class="targetlang">
<pre>
&gt; print(example.SUNDAY)
0
&gt; -- See the difference here
&gt; print(example.TEST1)
10
</pre>
</div>
<p><b> Compatibility Note:</b> Versions of SWIG prior to SWIG-3.0.0 did
 not generate the class table members above. There is no change in the C
 wrappers, but the following code was the only way to access these
 constants/enums when wrapping C++ member constants:</p>
<div class="targetlang">
<pre>
&gt; print(example.Test_TEST1)
10
&gt; print(example.Test_ICONST)
12
</pre>
</div>
<p> The old-style bindings are still generated in addition to the new
 ones. If the <tt>-no-old-metatable-bindings</tt> option is used, then
 these old-style bindings are not generated.</p>
<p> It is worth mentioning, that <tt>example.Test.TEST1</tt> and <tt>
example.Test_TEST1</tt> are different entities and changing one does not
 change the other. Given the fact that these are constantes and they are
 not supposed to be changed, it is up to you to avoid such issues.</p>
<h3><a name="Lua_nn12">28.3.5 Pointers</a></h3>
<p> C/C++ pointers are fully supported by SWIG. Furthermore, SWIG has no
 problem working with incomplete type information. Given a wrapping of
 the &lt;file.h&gt; interface:</p>
<div class="code">
<pre>%module example

FILE *fopen(const char *filename, const char *mode);
int fputs(const char *, FILE *);
int fclose(FILE *);
</pre>
</div>
<p> When wrapped, you will be able to use the functions in a natural way
 from Lua. For example:</p>
<div class="targetlang">
<pre>
&gt; f=example.fopen(&quot;junk&quot;, &quot;w&quot;)
&gt; example.fputs(&quot;Hello World&quot;, f)
&gt; example.fclose(f)
</pre>
</div>
<p> Unlike many scripting languages, Lua has had support for pointers to
 C/C++ object built in for a long time. They are called 'userdata'.
 Unlike many other SWIG versions which use some kind of encoded
 character string, all objects will be represented as a userdata. The
 SWIG-Lua bindings provides a special function <tt>swig_type()</tt>,
 which if given a userdata object will return the type of object pointed
 to as a string (assuming it was a SWIG wrapped object).</p>
<div class="targetlang">
<pre>
&gt; print(f)
userdata: 003FDA80
&gt; print(swig_type(f))
FILE * -- it's a FILE*
</pre>
</div>
<p> Lua enforces the integrity of its userdata, so it is virtually
 impossible to corrupt the data. But as the user of the pointer, you are
 responsible for freeing it, or closing any resources associated with it
 (just as you would in a C program). This does not apply so strictly to
 classes &amp; structs (see below). One final note: if a function returns a
 NULL pointer, this is not encoded as a userdata, but as a Lua nil.</p>
<div class="targetlang">
<pre>
&gt; f=example.fopen(&quot;not there&quot;, &quot;r&quot;) -- this will return a NULL in C
&gt; print(f)
nil
</pre>
</div>
<h3><a name="Lua_structures">28.3.6 Structures</a></h3>
<p> If you wrap a C structure, it is also mapped to a Lua userdata. By
 adding a metatable to the userdata, this provides a very natural
 interface. For example,</p>
<div class="code">
<pre>struct Point{
  int x, y;
};
</pre>
</div>
<p> is used as follows:</p>
<div class="targetlang">
<pre>
&gt; p=example.new_Point()
&gt; p.x=3
&gt; p.y=5
&gt; print(p.x, p.y)
3       5
&gt;
</pre>
</div>
<p> Similar access is provided for unions and the data members of C++
 classes.
<br> C structures can be created using a function <tt>new_Point()</tt>,
 and both C structures and C++ classes can be created using just the
 name <tt>Point()</tt>.</p>
<p> If you print out the value of p in the above example, you will see
 something like this:</p>
<div class="targetlang">
<pre>
&gt; print(p)
userdata: 003FA320
</pre>
</div>
<p> Like the pointer in the previous section, this is held as a
 userdata. However, additional features have been added to make this
 more usable. SWIG effectively creates some accessor/mutator functions
 to get and set the data. These functions will be added to the
 userdata's metatable. This provides the natural access to the member
 variables that were shown above (see end of the document for full
 details).</p>
<p> <tt>const</tt> members of a structure are read-only. Data members
 can also be forced to be read-only using the immutable directive. As
 with other immutables, setting attempts will be cause an error. For
 example:</p>
<div class="code">
<pre>struct Foo {
  ...
  %immutable;
  int x;        // Read-only members
  char *name;
  %mutable;
  ...
};
</pre>
</div>
<p> The mechanism for managing char* members as well as array members is
 similar to other languages. It is somewhat cumbersome and should
 probably be better handled by defining of typemaps (described later).</p>
<p> When a member of a structure is itself a structure, it is handled as
 a pointer. For example, suppose you have two structures like this:</p>
<div class="code">
<pre>struct Foo {
  int a;
};

struct Bar {
  Foo f;
};
</pre>
</div>
<p> Now, suppose that you access the f attribute of Bar like this:</p>
<div class="targetlang">
<pre>
&gt; b = Bar()
&gt; x = b.f
</pre>
</div>
<p> In this case, x is a pointer that points to the Foo that is inside
 b. This is the same value as generated by this C code:</p>
<div class="code">
<pre>
Bar b;
Foo *x = &amp;b-&gt;f;       // Points inside b
</pre>
</div>
<p> Because the pointer points inside the structure, you can modify the
 contents and everything works just like you would expect. For example:</p>
<div class="targetlang">
<pre>
&gt; b = Bar()
&gt; b.f.a = 3               -- Modify attribute of structure member
&gt; x = b.f
&gt; x.a = 3                 -- Modifies the same structure
</pre>
</div>
<p> For eLua with the <tt>-eluac</tt> option, structure manipulation has
 to be performed with specific structure functions generated by SWIG.
 Let's say you have the following structure definition:</p>
<div class="code">
<pre>struct data {
  int x, y;
  double z;
};

&gt; --From eLua
&gt; a = example.new_data()
&gt; example.data_x_set(a, 10)
&gt; example.data_y_set(a, 20)
&gt; print(example.data_x_get(a), example.data_y_get(a))
10 20
</pre>
</div>
<p> In general, functions of the form <tt>&quot;new_struct()&quot;</tt>, <tt>
&quot;struct_member_get()&quot;</tt>, <tt>&quot;struct_member_set()&quot;</tt> and <tt>
&quot;free_struct()&quot;</tt> are automatically generated by SWIG for each
 structure defined in C. (Please note: This doesn't apply for modules
 generated with the <tt>-elua</tt> option)</p>
<h3><a name="Lua_nn14">28.3.7 C++ classes</a></h3>
<p> C++ classes are wrapped by a Lua userdata as well. For example, if
 you have this class,</p>
<div class="code">
<pre>class List {
public:
  List();
  ~List();
  int  search(char *item);
  void insert(char *item);
  void remove(char *item);
  char *get(int n);
  int  length;
};
</pre>
</div>
<p> you can use it in Lua like this:</p>
<div class="targetlang">
<pre>
&gt; l = example.List()
&gt; l:insert(&quot;Ale&quot;)
&gt; l:insert(&quot;Stout&quot;)
&gt; l:insert(&quot;Lager&quot;)
&gt; print(l:get(1))
Stout
&gt; print(l:length)
3
&gt;
</pre>
</div>
<p> (Note: for calling methods of a class, you use <tt>
class:method(args)</tt>, not <tt>class.method(args)</tt>, it's an easy
 mistake to make. However for data attributes it is <tt>class.attribute</tt>
)</p>
<p> Class data members are accessed in the same manner as C structures.
 Static class members present a special problem for Lua, as Lua doesn't
 have support for such features. Therefore, SWIG generates wrappers that
 try to work around some of these issues. To illustrate, suppose you
 have a class like this:</p>
<div class="code">
<pre>
class Spam {
public:
  static void foo();
  static int bar;
};
</pre>
</div>
<p> In Lua, C++ static members can be accessed as follows:</p>
<div class="targetlang">
<pre>
&gt; example.Spam.foo()            -- calling Spam::foo()
&gt; a=example.Spam.bar            -- reading Spam::bar 
&gt; example.Spam.bar=b            -- writing to Spam::bar
</pre>
</div>
<p> It is not (currently) possible to access static members of an
 instance:</p>
<div class="targetlang">
<pre>
&gt; s=example.Spam()              -- s is a Spam instance
&gt; s.foo()                       -- Spam::foo() via an instance
                                -- does NOT work
</pre>
</div>
<p><b> Compatibility Note:</b> In versions prior to SWIG-3.0.0 only the
 following names would work:</p>
<div class="targetlang">
<pre>
&gt; example.Spam_foo()            -- calling Spam::foo()
&gt; a=example.Spam_bar            -- reading Spam::bar 
&gt; example.Spam_bar=b            -- writing to Spam::bar
</pre>
</div>
<p> Both style names are generated by default now. However, if the <tt>
-no-old-metatable-bindings</tt> option is used, then the backward
 compatible names are not generated in addition to ordinary ones.</p>
<h3><a name="Lua_nn15">28.3.8 C++ inheritance</a></h3>
<p> SWIG is fully aware of issues related to C++ inheritance. Therefore,
 if you have classes like this</p>
<div class="code">
<pre>class Foo {
...
};

class Bar : public Foo {
...
};
</pre>
</div>
<p> And if you have functions like this</p>
<div class="code">
<pre>void spam(Foo *f);
</pre>
</div>
<p> then the function <tt>spam()</tt> accepts a Foo pointer or a pointer
 to any class derived from Foo.</p>
<p> It is safe to use multiple inheritance with SWIG.</p>
<h3><a name="Lua_nn16">28.3.9 Pointers, references, values, and arrays</a>
</h3>
<p> In C++, there are many different ways a function might receive and
 manipulate objects. For example:</p>
<div class="code">
<pre>void spam1(Foo *x);      // Pass by pointer
void spam2(Foo &amp;x);      // Pass by reference
void spam3(Foo x);       // Pass by value
void spam4(Foo x[]);     // Array of objects
</pre>
</div>
<p> In SWIG, there is no detailed distinction like this--specifically,
 there are only &quot;objects&quot;. There are no pointers, references, arrays,
 and so forth. 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:</p>
<div class="targetlang">
<pre>
&gt; f = Foo()           -- Create a Foo
&gt; spam1(f)            -- Ok. Pointer
&gt; spam2(f)            -- Ok. Reference
&gt; spam3(f)            -- Ok. Value.
&gt; spam4(f)            -- Ok. Array (1 element)
</pre>
</div>
<p> Similar behaviour occurs for return values. For example, if you had
 functions like this,</p>
<div class="code">
<pre>Foo *spam5();
Foo &amp;spam6();
Foo  spam7();
</pre>
</div>
<p> then all three functions will return a pointer to some Foo object.
 Since the third function (spam7) returns a value, newly allocated
 memory is used to hold the result and a pointer is returned (Lua will
 release this memory when the return value is garbage collected). The
 other two are pointers which are assumed to be managed by the C code
 and so will not be garbage collected.</p>
<h3><a name="Lua_nn17">28.3.10 C++ overloaded functions</a></h3>
<p> C++ overloaded functions, methods, and constructors are mostly
 supported by SWIG. For example, if you have two functions like this:</p>
<div class="code">
<pre>void foo(int);
void foo(char *c);
</pre>
</div>
<p> You can use them in Lua in a straightforward manner:</p>
<div class="targetlang">
<pre>
&gt; foo(3)           -- foo(int)
&gt; foo(&quot;Hello&quot;)     -- foo(char *c)
</pre>
</div>
<p> However due to Lua's coercion mechanism is can sometimes do strange
 things.</p>
<div class="targetlang">
<pre>
&gt; foo(&quot;3&quot;)           -- &quot;3&quot; can be coerced into an int, so it calls foo(int)!
</pre>
</div>
<p> As this coercion mechanism is an integral part of Lua, there is no
 easy way to get around this other than renaming of functions (see
 below).</p>
<p> Similarly, if you have a class like this,</p>
<div class="code">
<pre>class Foo {
public:
  Foo();
  Foo(const Foo &amp;);
  ...
};
</pre>
</div>
<p> you can write Lua code like this:</p>
<div class="targetlang">
<pre>
&gt; f = Foo()          -- Create a Foo
&gt; g = Foo(f)         -- Copy f
</pre>
</div>
<p> Overloading support is not quite as flexible as in C++. Sometimes
 there are methods that SWIG can't disambiguate. For example:</p>
<div class="code">
<pre>void spam(int);
void spam(short);
</pre>
</div>
<p> or</p>
<div class="code">
<pre>void foo(Bar *b);
void foo(Bar &amp;b);
</pre>
</div>
<p> If declarations such as these appear, you will get a warning message
 like this:</p>
<div class="shell">
<pre>
example.i:12: Warning 509: Overloaded method spam(short) effectively ignored,
example.i:11: Warning 509: as it is shadowed by spam(int).
</pre>
</div>
<p> To fix this, you either need to ignore or rename one of the methods.
 For example:</p>
<div class="code">
<pre>%rename(spam_short) spam(short);
...
void spam(int);
void spam(short);   // Accessed as spam_short
</pre>
</div>
<p> or</p>
<div class="code">
<pre>%ignore spam(short);
...
void spam(int);
void spam(short);   // Ignored
</pre>
</div>
<p> SWIG resolves overloaded functions and methods using a
 disambiguation scheme that ranks and sorts declarations according to a
 set of type-precedence rules. The order in which declarations appear in
 the input does not matter except in situations where ambiguity
 arises--in this case, the first declaration takes precedence.</p>
<p> Please refer to the &quot;SWIG and C++&quot; chapter for more information
 about overloading.</p>
<p> Dealing with the Lua coercion mechanism, the priority is roughly
 (integers, floats, strings, userdata). But it is better to rename the
 functions rather than rely upon the ordering.</p>
<h3><a name="Lua_nn18">28.3.11 C++ operators</a></h3>
<p> Certain C++ overloaded operators can be handled automatically by
 SWIG. For example, consider a class like this:</p>
<div class="code">
<pre>class Complex {
private:
  double rpart, ipart;
public:
  Complex(double r = 0, double i = 0) : rpart(r), ipart(i) { }
  Complex(const Complex &amp;c) : rpart(c.rpart), ipart(c.ipart) { }
  Complex &amp;operator=(const Complex &amp;c);
  Complex operator+(const Complex &amp;c) const;
  Complex operator-(const Complex &amp;c) const;
  Complex operator*(const Complex &amp;c) const;
  Complex operator-() const;

  double re() const { return rpart; }
  double im() const { return ipart; }
};
</pre>
</div>
<p> When wrapped, it works like you expect:</p>
<div class="targetlang">
<pre>
&gt; c = Complex(3, 4)
&gt; d = Complex(7, 8)
&gt; e = c + d
&gt; e:re()
10.0
&gt; e:im()
12.0
</pre>
</div>
<p> One restriction with operator overloading support is that SWIG is
 not able to fully handle operators that aren't defined as part of the
 class. For example, if you had code like this</p>
<div class="code">
<pre>
class Complex {
...
friend Complex operator+(double, const Complex &amp;c);
...
};
</pre>
</div>
<p> then SWIG doesn't know what to do with the friend function--in fact,
 it simply ignores it and issues a warning. You can still wrap the
 operator, but you may have to encapsulate it in a special function. For
 example:</p>
<div class="code">
<pre>
%rename(Complex_add_dc) operator+(double, const Complex &amp;);
...
Complex operator+(double, const Complex &amp;c);
</pre>
</div>
<p> There are ways to make this operator appear as part of the class
 using the <tt>%extend</tt> directive. Keep reading.</p>
<p> Also, be aware that certain operators don't map cleanly to Lua, and
 some Lua operators don't map cleanly to C++ operators. For instance,
 overloaded assignment operators don't map to Lua semantics and will be
 ignored, and C++ doesn't support Lua's concatenation operator (<tt>..</tt>
).</p>
<p> In order to keep maximum compatibility within the different
 languages in SWIG, the Lua bindings uses the same set of operator names
 as Python. Although internally it renames the functions to something
 else (on order to work with Lua).</p>
<p> The current list of operators which can be overloaded (and the
 alternative function names) are:</p>
<ul>
<li><tt>__add__</tt> operator+</li>
<li><tt>__sub__</tt> operator-</li>
<li><tt>__mul__</tt> operator *</li>
<li><tt>__div__</tt> operator/</li>
<li><tt>__unm__</tt> unary minus</li>
<li><tt>__call__</tt> operator<tt>()</tt> (often used in functor
 classes)</li>
<li><tt>__pow__</tt> the exponential fn (no C++ equivalent, Lua uses <tt>
^</tt>)</li>
<li><tt>__concat__</tt> the concatenation operator (Lua's <tt>..</tt>)</li>
<li><tt>__eq__</tt> operator<tt>==</tt></li>
<li><tt>__lt__</tt> operator<tt>&lt;</tt></li>
<li><tt>__le__</tt> operator<tt>&lt;=</tt></li>
</ul>
<p> Note: in Lua, only the equals, less than, and less than equals
 operators are defined. The other operators (!=, &gt;, &gt;=) are achieved by
 using a logical not applied to the results of other operators.</p>
<p> The following operators cannot be overloaded (mainly because they
 are not supported in Lua)</p>
<ul>
<li>++ and --</li>
<li>+=, -=, *= etc</li>
<li>% operator (you have to use math.mod)</li>
<li>assignment operator</li>
<li>all bitwise/logical operations</li>
</ul>
<p> SWIG also accepts the <tt>__str__()</tt> member function which
 converts an object to a string. This function should return a const
 char*, preferably to static memory. This will be used for the <tt>
print()</tt> and <tt>tostring()</tt> functions in Lua. Assuming the
 complex class has a function</p>
<div class="code">
<pre>const char* __str__() {
  static char buffer[255];
  sprintf(buffer, &quot;Complex(%g, %g)&quot;, this-&gt;re(), this-&gt;im());
  return buffer;
}
</pre>
</div>
<p> Then this will support the following code in Lua</p>
<div class="targetlang">
<pre>
&gt; c = Complex(3, 4)
&gt; d = Complex(7, 8)
&gt; e = c + d
&gt; print(e)
Complex(10, 12)
&gt; s=tostring(e) -- s is the number in string form
&gt; print(s)
Complex(10, 12)
</pre>
</div>
<p> It is also possible to overload the operator<tt>[]</tt>, but
 currently this cannot be automatically performed. To overload the
 operator<tt>[]</tt> you need to provide two functions, <tt>
__getitem__()</tt> and <tt>__setitem__()</tt></p>
<div class="code">
<pre>class Complex {
  //....
  double __getitem__(int i)const; // i is the index, returns the data
  void __setitem__(int i, double d); // i is the index, d is the data
};
</pre>
</div>
<p> C++ operators are mapped to Lua predefined metafunctions. Class
 inherits from its bases the following list of metafunctions ( thus
 inheriting the folloging operators and pseudo-operators):</p>
<ul>
<li><tt>__add__</tt></li>
<li><tt>__sub__</tt></li>
<li><tt>__mul__</tt></li>
<li><tt>__div__</tt></li>
<li><tt>__unm__</tt></li>
<li><tt>__mod__</tt></li>
<li><tt>__call__</tt></li>
<li><tt>__pow__</tt></li>
<li><tt>__concat__</tt></li>
<li><tt>__eq__</tt></li>
<li><tt>__lt__</tt></li>
<li><tt>__le__</tt></li>
<li><tt>__len__</tt></li>
<li><tt>__getitem__</tt></li>
<li><tt>__setitem__</tt></li>
<li><tt>__tostring</tt> used internally by Lua for tostring() function.
 __str__ is mapped to this function</li>
</ul>
<p>No other lua metafunction is inherited. For example, __gc is not
 inherited and must be redefined in every class. <tt>__tostring</tt> is
 subject to a special handling. If absent in class and in class bases, a
 default one will be provided by SWIG.</p>
<h3><a name="Lua_nn19">28.3.12 Class extension with %extend</a></h3>
<p> One of the more interesting features of SWIG is that it can extend
 structures and classes with new methods. In the previous section, the
 Complex class would have benefited greatly from an __str__() method as
 well as some repairs to the operator overloading. It can also be used
 to add additional functions to the class if they are needed.</p>
<p> Take the original Complex class</p>
<div class="code">
<pre>class Complex {
private:
  double rpart, ipart;
public:
  Complex(double r = 0, double i = 0) : rpart(r), ipart(i) { }
  Complex(const Complex &amp;c) : rpart(c.rpart), ipart(c.ipart) { }
  Complex &amp;operator=(const Complex &amp;c);
  Complex operator+(const Complex &amp;c) const;
  Complex operator-(const Complex &amp;c) const;
  Complex operator*(const Complex &amp;c) const;
  Complex operator-() const;

  double re() const { return rpart; }
  double im() const { return ipart; }
};
</pre>
</div>
<p> Now we extend it with some new code</p>
<div class="code">
<pre>%extend Complex {
  const char *__str__() {
    static char tmp[1024];
    sprintf(tmp, &quot;Complex(%g, %g)&quot;, $self-&gt;re(), $self-&gt;im());
    return tmp;
  }
  bool operator==(const Complex&amp; c) {
    return ($self-&gt;re()==c.re() &amp;&amp; $self-&gt;im()==c.im());
  }
};
</pre>
</div>
<p> Now, in Lua</p>
<div class="targetlang">
<pre>
&gt; c = Complex(3, 4)
&gt; d = Complex(7, 8)
&gt; e = c + d
&gt; print(e)      -- print uses __str__ to get the string form to print
Complex(10, 12)
&gt; print(e==Complex(10, 12))  -- testing the == operator
true
&gt; print(e!=Complex(12, 12))  -- the != uses the == operator
true
</pre>
</div>
<p> Extend works with both C and C++ code, on classes and structs. It
 does not modify the underlying object in any way---the extensions only
 show up in the Lua interface. The only item to take note of is the code
 has to use the '$self' instead of 'this', and that you cannot access
 protected/private members of the code (as you are not officially part
 of the class).</p>
<h3><a name="Lua_nn20">28.3.13 Using %newobject to release memory</a></h3>
<p> If you have a function that allocates memory like this,</p>
<div class="code">
<pre>char *foo() {
  char *result = (char *) malloc(...);
  ...
  return result;
}
</pre>
</div>
<p> then the SWIG generated wrappers will have a memory leak--the
 returned data will be copied into a string object and the old contents
 ignored.</p>
<p> To fix the memory leak, use the <a href="#Customization_ownership">
%newobject directive</a>.</p>
<div class="code">
<pre>%newobject foo;
...
char *foo();
</pre>
</div>
<p> This will release the allocated memory.</p>
<h3><a name="Lua_nn21">28.3.14 C++ templates</a></h3>
<p> C++ templates don't present a huge problem for SWIG. However, in
 order to create wrappers, you have to tell SWIG to create wrappers for
 a particular template instantiation. To do this, you use the template
 directive. For example:</p>
<div class="code">
<pre>%module example
%{
#include &quot;pair.h&quot;
%}

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

%template(pairii) pair&lt;int, int&gt;;
</pre>
</div>
<p> In Lua:</p>
<div class="targetlang">
<pre>
&gt; p = example.pairii(3, 4)
&gt; print(p.first, p.second)
3    4
</pre>
</div>
<p> Obviously, there is more to template wrapping than shown in this
 example. More details can be found in the SWIG and C++ chapter. Some
 more complicated examples will appear later.</p>
<h3><a name="Lua_nn22">28.3.15 C++ Smart Pointers</a></h3>
<p> In certain C++ programs, it is common to use classes that have been
 wrapped by so-called &quot;smart pointers.&quot; Generally, this involves the use
 of a template class that implements operator-&gt;() like this:</p>
<div class="code">
<pre>template&lt;class T&gt; class SmartPtr {
  ...
  T *operator-&gt;();
  ...
}
</pre>
</div>
<p> Then, if you have a class like this,</p>
<div class="code">
<pre>class Foo {
public:
  int x;
  int bar();
};
</pre>
</div>
<p> A smart pointer would be used in C++ as follows:</p>
<div class="code">
<pre>SmartPtr&lt;Foo&gt; p = CreateFoo();   // Created somehow (not shown)
...
p-&gt;x = 3;                        // Foo::x
int y = p-&gt;bar();                // Foo::bar
</pre>
</div>
<p> To wrap this, simply tell SWIG about the SmartPtr class and the
 low-level Foo object. Make sure you instantiate SmartPtr using template
 if necessary. For example:</p>
<div class="code">
<pre>%module example
...
%template(SmartPtrFoo) SmartPtr&lt;Foo&gt;;
...
</pre>
</div>
<p> Now, in Lua, everything should just &quot;work&quot;:</p>
<div class="targetlang">
<pre>
&gt; p = example.CreateFoo()          -- Create a smart-pointer somehow
&gt; p.x = 3                          -- Foo::x
&gt; print(p:bar())                   -- Foo::bar
</pre>
</div>
<p> If you ever need to access the underlying pointer returned by <tt>
operator-&gt;()</tt> itself, simply use the <tt>__deref__()</tt> method.
 For example:</p>
<div class="targetlang">
<pre>
&gt; f = p:__deref__()     -- Returns underlying Foo *
</pre>
</div>
<h3><a name="Lua_nn23">28.3.16 C++ Exceptions</a></h3>
<p> Lua does not natively support exceptions, but it has errors which
 are similar. When a Lua function terminates with an error it returns
 one value back to the caller. SWIG automatically maps any basic type
 which is thrown into a Lua error. Therefore for a function:</p>
<div class="code">
<pre>
int message() throw(const char *) {
  throw(&quot;I died.&quot;);
  return 1;
}
</pre>
</div>
<p> SWIG will automatically convert this to a Lua error.</p>
<div class="targetlang">
<pre>
&gt; message()
I died.
stack traceback:
        [C]: in function 'message'
        stdin:1: in main chunk
        [C]: ?
&gt;
</pre>
</div>
<p> If you want to catch an exception, you must use either pcall() or
 xpcall(), which are documented in the Lua manual. Using xpcall will
 allow you to obtain additional debug information (such as a
 stacktrace).</p>
<div class="targetlang">
<pre>
&gt; function a() b() end -- function a() calls function b()
&gt; function b() message() end -- function b() calls C++ function message(), which throws 
&gt; ok, res=pcall(a)  -- call the function
&gt; print(ok, res)
false   I died.
&gt; ok, res=xpcall(a, debug.traceback)  -- call the function
&gt; print(ok, res)
false   I died.
stack traceback:
        [C]: in function 'message'
        runme.lua:70: in function 'b'
        runme.lua:67: in function &lt;runme.lua:66&gt;
        [C]: in function 'xpcall'
        runme.lua:95: in main chunk
        [C]: ?
</pre>
</div>
<p> SWIG is able to throw numeric types, enums, chars, char*'s and
 std::string's without problem. It has also written typemaps for
 std::exception and its derived classes, which convert the exception
 into an error string.</p>
<p> However it's not so simple to throw other types of objects. Thrown
 objects are not valid outside the 'catch' block. Therefore they cannot
 be returned to the interpreter. The obvious ways to overcome this would
 be to either return a copy of the object, or to convert the object to a
 string and return that. Though it seems obvious to perform the former,
 in some cases this is not possible, most notably when SWIG has no
 information about the object, or the object is not copyable/creatable.</p>
<p> Therefore by default SWIG converts all thrown object into strings
 and returns them. So given a function:</p>
<div class="code">
<pre>
void throw_A() throw(A*) {
  throw new A();
}
</pre>
</div>
<p> SWIG will just convert it (poorly) to a string and use that as its
 error. (This is not that useful, but it always works).</p>
<div class="targetlang">
<pre>
&gt; throw_A()
object exception:A *
stack traceback:
        [C]: in function 'unknown'
        stdin:1: in main chunk
        [C]: ?
&gt;
</pre>
</div>
<p> To get a more useful behaviour out of SWIG you must either: provide
 a way to convert your exceptions into strings, or throw objects which
 can be copied.</p>
<p> If you have your own class which you want output as a string you
 will need to add a typemap something like this:</p>
<div class="code">
<pre>
%typemap(throws) my_except
%{ 
  lua_pushstring(L, $1.what()); // assuming my_except::what() returns a const char* message
  SWIG_fail; // trigger the error handler
%}
</pre>
</div>
<p> If you wish your exception to be returned to the interpreter, it
 must firstly be copyable. Then you must have an additional <tt>%apply</tt>
 statement, to tell SWIG to return a copy of this object to the
 interpreter. For example:</p>
<div class="code">
<pre>
%apply SWIGTYPE EXCEPTION_BY_VAL {Exc}; // tell SWIG to return Exc by value to interpreter

class Exc {
public:
  Exc(int c, const char *m) {
    code = c;
    strncpy(msg, m, 256);
  }
  int code;
  char msg[256];
};

void throw_exc() throw(Exc) {
  throw(Exc(42, &quot;Hosed&quot;));
} 
</pre>
</div>
<p> Then the following code can be used (note: we use pcall to catch the
 error so we can process the exception).</p>
<div class="targetlang">
<pre>
&gt; ok, res=pcall(throw_exc)
&gt; print(ok)
false
&gt; print(res)
userdata: 0003D880
&gt; print(res.code, res.msg)
42      Hosed
&gt;
</pre>
</div>
<p> Note: it is also possible (though tedious) to have a function throw
 several different kinds of exceptions. To process this will require a
 pcall, followed by a set of if statements checking the type of the
 error.</p>
<p> All of this code assumes that your C++ code uses exception
 specification (which a lot doesn't). If it doesn't consult the &quot;<a href="#SWIGPlus_catches">
Exception handling with %catches</a>&quot; section and the &quot;<a href="#Customization_exception">
Exception handling with %exception</a>&quot; section, for more details on how
 to add exception specification to functions or globally (respectively).</p>
<h3><a name="Lua_namespaces">28.3.17 Namespaces</a></h3>
<p> Since SWIG-3.0.0 C++ namespaces are supported via the %nspace
 feature.</p>
<p> Namespaces are mapped into Lua tables. Each of those tables contains
 names that were defined within appropriate namespace. Namespaces
 structure (a.k.a nested namespaces) is preserved. Consider the
 following C++ code:</p>
<div class="code">
<pre>%module example
%nspace MyWorld::Nested::Dweller;
%nspace MyWorld::World;

int module_function() { return 7; }
int module_variable = 9;

namespace MyWorld {
  class World {
  public:
    World() : world_max_count(9) {}
    int create_world() { return 17; }
    const int world_max_count; // = 9
  };
  namespace Nested {
    class Dweller {
      public:
        enum Gender { MALE = 0, FEMALE = 1 };
        static int count() { return 19; }
    };
  }
}
</pre>
</div>
<p> Now, from Lua usage is as follows:</p>
<div class="targetlang">
<pre>
&gt; print(example.module_function())
7
&gt; print(example.module_variable)
9
&gt; print(example.MyWorld.World():create_world())
17
&gt; print(example.MyWorld.World.world_max_count)
9
&gt; print(example.MyWorld.Nested.Dweller.MALE)
0
&gt; print(example.MyWorld.Nested.Dweller.count())
19
&gt;
</pre>
</div>
<h4><a name="Lua_nn27">28.3.17.1 Compatibility Note</a></h4>
<p> If SWIG is running in a backwards compatible way, i.e. without the <tt>
-no-old-metatable-bindings</tt> option, then additional old-style names
 are generated (notice the underscore):</p>
<div class="targetlang">
<pre>
9
&gt; print(example.MyWorld.Nested.Dweller_MALE)
0
&gt; print(example.MyWorld.Nested.Dweller_count())
11
&gt;
</pre>
</div>
<h4><a name="Lua_nn29">28.3.17.2 Names</a></h4>
<p> If SWIG is launched without <tt>-no-old-metatable-bindings</tt>
 option, then it enters backward-compatible mode. While in this mode, it
 tries to generate additional names for static functions, class static
 constants and class enums. Those names are in a form <tt>
$classname_$symbolname</tt> and are added to the scope surrounding the
 class. If %nspace is enabled, then class namespace is taken as scope.
 If there is no namespace, or %nspace is disabled, then module is
 considered a class namespace.</p>
<p> Consider the following C++ code</p>
<div class="code">
<pre>%module example
%nspace MyWorld::Test;
namespace MyWorld {
class Test {
  public:
  enum { TEST1 = 10, TEST2 }
  static const int ICONST = 12;
};
class Test2 {
  public:
  enum { TEST3 = 20, TEST4 }
  static const int ICONST2 = 23;
}
</pre>
</div>
<p> When in backward compatible mode, in addition to the usual names,
 the following ones will be generated (notice the underscore):</p>
<div class="targetlang">
<pre>
9
&gt; print(example.MyWorld.Test_TEST1) -- Test has %nspace enabled
10
&gt; print(example.MyWorld.Test_ICONST) -- Test has %nspace enabled
12
&gt; print(example.Test2_TEST3) -- Test2 doesn't have %nspace enabled
20
&gt; print(example.Test2_ICONST2) -- Test2 doesn't have %nspace enabled
23
&gt;
</pre>
</div>
<p> There is a slight difference with enums when in C mode. As per C
 standard, enums from C structures are exported to surrounding scope
 without any prefixing. Pretending that Test2 is a struct, not class,
 that would be:</p>
<div class="targetlang">
<pre>
&gt; print(example.TEST3) -- NOT Test2_TEST3
20
&gt;
</pre>
</div>
<h4><a name="Lua_nn30">28.3.17.3 Inheritance</a></h4>
<p> The internal organization of inheritance has changed. Consider the
 following C++ code:</p>
<div class="code">
<pre>%module example
class Base {
  public:
  int base_func()
};
class Derived : public Base {
  public:
  int derived_func()
}
</pre>
</div>
<p>Lets assume for a moment that class member functions are stored in <tt>
.fn</tt> table. Previously, when classes were exported to Lua during
 module initialization, for every derived class all service tables <tt>
ST(i.e. &quot;.fn&quot;)</tt> were squashed and added to corresponding derived
 class <tt>ST</tt>: Everything from <tt>.fn</tt> table of class Base was
 copied to <tt>.fn</tt> table of class Derived and so on. This was a
 recursive procedure, so in the end the whole inheritance tree of
 derived class was squashed into derived class.</p>
<p> That means that any changes done to class Base after module
 initialization wouldn't affect class Derived:</p>
<div class="targetlang">
<pre>
base = example.Base()
der = example.Derived()
&gt; print(base.base_func)
function: 0x1367940
&gt; getmetatable(base)[&quot;.fn&quot;].new_func = function (x) return x -- Adding new function to class Base (to class, not to an instance!)
&gt; print(base.new_func) -- Checking this function
function
&gt; print(der.new_func) -- Wouldn't work. Derived doesn't check Base any more.
nil
&gt;
</pre>
</div>
<p> This behaviour was changed. Now unless -squash-bases option is
 provided, Derived store a list of it's bases and if some symbol is not
 found in it's own service tables then its bases are searched for it.
 Option -squash-bases will effectively return old behaviour.</p>
<div class="targetlang">
<pre>
&gt; print(der.new_func) -- Now it works
function
&gt;
</pre>
</div>
<h2><a name="Lua_nn24">28.4 Typemaps</a></h2>
<p>This section explains what typemaps are and how to use them. The
 default wrapping behaviour of SWIG is enough in most cases. However
 sometimes SWIG may need a little additional assistance to know which
 typemap to apply to provide the best wrapping. This section will be
 explaining how to use typemaps to best effect</p>
<h3><a name="Lua_nn25">28.4.1 What is a typemap?</a></h3>
<p>A typemap is nothing more than a code generation rule that is
 attached to a specific C datatype. For example, to convert integers
 from Lua to C, you might define a typemap like this:</p>
<div class="code">
<pre>%module example

%typemap(in) int {
  $1 = (int) lua_tonumber(L, $input);
  printf(&quot;Received an integer : %d\n&quot;, $1);
}
%inline %{
extern int fact(int n);
%}
</pre>
</div>
<p><i>Note: you shouldn't use this typemap, as SWIG already has a
 typemap for this task. This is purely for example.</i></p>
<p>Typemaps are always associated with some specific aspect of code
 generation. In this case, the &quot;in&quot; method refers to the conversion of
 input arguments to C/C++. The datatype int 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 variable prefaced by a $ are used. The
 $1 variable is placeholder for a local variable of type int. The $input
 is the index on the Lua stack for the value to be used.</p>
<p>When this example is compiled into a Lua module, it operates as
 follows:</p>
<div class="targetlang">
<pre>&gt; require &quot;example&quot;
&gt; print(example.fact(6))
Received an integer : 6
720
</pre>
</div>
<h3><a name="Lua_nn26">28.4.2 Using typemaps</a></h3>
<p>There are many ready written typemaps built into SWIG for all common
 types (int, float, short, long, char*, enum and more), which SWIG uses
 automatically, with no effort required on your part.</p>
<p>However for more complex functions which use input/output parameters
 or arrays, you will need to make use of &lt;typemaps.i&gt;, which contains
 typemaps for these situations. For example, consider these functions:</p>
<div class="code">
<pre>void add(int x, int y, int *result) {
  *result = x + y;
}

int sub(int *x1, int *y1) {
  return *x1-*y1;
}

void swap(int *sx, int *sy) {
  int t=*sx;
  *sx=*sy;
  *sy=t;
}
</pre>
</div>
<p>It is clear to the programmer, that 'result' is an output parameter,
 'x1' and 'y1' are input parameters and 'sx' and 'sy' are input/output
 parameters. However is not apparent to SWIG, so SWIG must to informed
 about which kind they are, so it can wrapper accordingly.</p>
<p>One means would be to rename the argument name to help SWIG, eg <tt>
void add(int x, int y, int *OUTPUT)</tt>, however it is easier to use
 the <tt>%apply</tt> to achieve the same result, as shown below.</p>
<div class="code">
<pre>%include &lt;typemaps.i&gt;
%apply int* OUTPUT {int *result}; // int *result is output
%apply int* INPUT {int *x1, int *y1}; // int *x1 and int *y1 are input
%apply int* INOUT {int *sx, int *sy}; // int *sx and int *sy are input and output

void add(int x, int y, int *result);
int sub(int *x1, int *y1);
void swap(int *sx, int *sy);
</pre>
</div>
<p>When wrapped, it gives the following results:</p>
<div class="targetlang">
<pre>&gt; require &quot;example&quot;
&gt; print(example.add(1, 2))
3
&gt; print(demo.sub(1, 2))
-1
&gt; a, b=1, 2
&gt; c, d=demo.swap(a, b)
&gt; print(a, b, c, d)
1       2       2       1
</pre>
</div>
<p>Notice, that 'result' is not required in the arguments to call the
 function, as it an output parameter only. For 'sx' and 'sy' they must
 be passed in (as they are input), but the original value is not
 modified (Lua does not have a pass by reference feature). The modified
 results are then returned as two return values. All INPUT/OUTPUT/INOUT
 arguments will behave in a similar manner.</p>
<p>Note: C++ references must be handled exactly the same way. However
 SWIG will automatically wrap a <tt>const int&amp;</tt> as an input
 parameter (since that it obviously input).</p>
<h3><a name="Lua_typemap_arrays">28.4.3 Typemaps and arrays</a></h3>
<p>Arrays present a challenge for SWIG, because like pointers SWIG does
 not know whether these are input or output values, nor does SWIG have
 any indication of how large an array should be. However with the proper
 guidance SWIG can easily wrapper arrays for convenient usage.</p>
<p>Given the functions:</p>
<div class="code">
<pre>extern void sort_int(int* arr, int len);
extern void sort_double(double* arr, int len);
</pre>
</div>
<p>There are basically two ways that SWIG can deal with this. The first
 way, uses the <tt>&lt;carrays.i&gt;</tt> library to create an array in C/C++
 then this can be filled within Lua and passed into the function. It
 works, but it's a bit tedious. More details can be found in the <a href="#Library_carrays">
carrays.i</a> documentation.</p>
<p>The second and more intuitive way, would be to pass a Lua table
 directly into the function, and have SWIG automatically convert between
 Lua-table and C-array. Within the <tt>&lt;typemaps.i&gt;</tt> file there are
 typemaps ready written to perform this task. To use them is again a
 matter of using %apply in the correct manner.</p>
<p>The wrapper file below, shows both the use of carrays as well as the
 use of the typemap to wrap arrays.</p>
<div class="code">
<pre>// using the C-array
%include &lt;carrays.i&gt;
// this declares a batch of function for manipulating C integer arrays
%array_functions(int, int)

extern void sort_int(int* arr, int len); // the function to wrap

// using typemaps
%include &lt;typemaps.i&gt;
%apply (double *INOUT, int) {(double* arr, int len)};

extern void sort_double(double* arr, int len); // the function to wrap
</pre>
</div>
<p>Once wrapped, the functions can both be called, though with different
 ease of use:</p>
<div class="targetlang">
<pre>require &quot;example&quot;
ARRAY_SIZE=10

-- passing a C array to the sort_int()
arr=example.new_int(ARRAY_SIZE) -- create the array
for i=0, ARRAY_SIZE-1 do -- index 0..9 (just like C)
    example.int_setitem(arr, i, math.random(1000))
end
example.sort_int(arr, ARRAY_SIZE)  -- call the function
example.delete_int(arr) -- must delete the allocated memory

-- use a typemap to call with a Lua-table
-- one item of note: the typemap creates a copy, rather than edit-in-place
t={} -- a Lua table
for i=1, ARRAY_SIZE do -- index 1..10 (Lua style)
    t[i]=math.random(1000)/10
end
t=example.sort_double(t) -- replace t with the result
</pre>
</div>
<p>Obviously the first version could be made less tedious by writing a
 Lua function to perform the conversion from a table to a C-array. The <tt>
%luacode</tt> directive is good for this. See SWIG\Examples\lua\arrays
 for an example of this.</p>
<p><b>Warning:</b> in C indexes start at ZERO, in Lua indexes start at
 ONE. SWIG expects C-arrays to be filled for 0..N-1 and Lua tables to be
 1..N, (the indexing follows the norm for the language). In the typemap
 when it converts the table to an array it quietly changes the indexing
 accordingly. Take note of this behaviour if you have a C function which
 returns indexes.</p>
<p>Note: SWIG also can support arrays of pointers in a similar manner.</p>
<h3><a name="Lua_typemaps_ptr_ptr_functions">28.4.4 Typemaps and
 pointer-pointer functions</a></h3>
<p>Several C++ libraries use a pointer-pointer functions to create its
 objects. These functions require a pointer to a pointer which is then
 filled with the pointer to the new object. Microsoft's COM and DirectX
 as well as many other libraries have this kind of function. An example
 is given below:</p>
<div class="code">
<pre>struct iMath;    // some structure
int Create_Math(iMath** pptr); // its creator (assume it mallocs)
</pre>
</div>
<p>Which would be used with the following C code:</p>
<div class="code">
<pre>iMath* ptr;
int ok;
ok=Create_Math(&amp;ptr);
// do things with ptr
//...
free(ptr); // dispose of iMath
</pre>
</div>
<p>SWIG has a ready written typemap to deal with such a kind of function
 in &lt;typemaps.i&gt;. It provides the correct wrapping as well as setting
 the flag to inform Lua that the object in question should be garbage
 collected. Therefore the code is simply:</p>
<div class="code">
<pre>%include &lt;typemaps.i&gt;
%apply SWIGTYPE** OUTPUT{iMath **pptr }; // tell SWIG it's an output

struct iMath;    // some structure
int Create_Math(iMath** pptr); // its creator (assume it mallocs)
</pre>
</div>
<p>The usage is as follows:</p>
<div class="targetlang">
<pre>ok, ptr=Create_Math() -- ptr is an iMath* which is returned with the int (ok)
ptr=nil -- the iMath* will be GC'ed as normal
</pre>
</div>
<h2><a name="Lua_writing_typemaps">28.5 Writing typemaps</a></h2>
<p>This section describes how you can modify SWIG's default wrapping
 behavior for various C/C++ datatypes using the <tt>%typemap</tt>
 directive. This is an advanced topic that assumes familiarity with the
 Lua C API as well as the material in the &quot;<a href="#Typemaps">Typemaps</a>
&quot; chapter.</p>
<p>Before proceeding, it should be stressed that writing typemaps is
 rarely needed unless you want to change some aspect of the wrapping, or
 to achieve an effect which in not available with the default bindings.</p>
<p>Before proceeding, you should read the previous section on using
 typemaps, and look at the existing typemaps found in luatypemaps.swg
 and typemaps.i. These are both well documented and fairly easy to read.
 You should not attempt to write your own typemaps until you have read
 and can understand both of these files (they may well also give you an
 idea to base your work on).</p>
<h3><a name="Lua_typemaps_write">28.5.1 Typemaps you can write</a></h3>
<p>There are many different types of typemap that can be written, the
 full list can be found in the &quot;<a href="#Typemaps">Typemaps</a>&quot;
 chapter. However the following are the most commonly used ones.</p>
<ul>
<li><tt>in</tt> this is for input arguments to functions</li>
<li><tt>out</tt> this is for return types from functions</li>
<li><tt>argout</tt> this is for a function argument which is actually
 returning something</li>
<li><tt>typecheck</tt> this is used to determine which overloaded
 function should be called (the syntax for the typecheck is different
 from the typemap, see typemaps for details).</li>
</ul>
<h3><a name="Lua_nn31">28.5.2 SWIG's Lua-C API</a></h3>
<p>This section explains the SWIG specific Lua-C API. It does not cover
 the main Lua-C api, as this is well documented and not worth covering.</p>
<p><tt>int SWIG_ConvertPtr(lua_State* L, int index, void** ptr,
 swig_type_info *type, int flags);</tt></p>
<div class="indent"> This is the standard function used for converting a
 Lua userdata to a void*. It takes the value at the given index in the
 Lua state and converts it to a userdata. It will then provide the
 necessary type checks, confirming that the pointer is compatible with
 the type given in 'type'. Then finally setting '*ptr' to the pointer.
 If flags is set to SWIG_POINTER_DISOWN, this is will clear any
 ownership flag set on the object.
<br> This returns a value which can be checked with the macro
 SWIG_IsOK()</div>
<p><tt>void SWIG_NewPointerObj(lua_State* L, void* ptr, swig_type_info
 *type, int own);</tt></p>
<div class="indent"> This is the opposite of SWIG_ConvertPtr, as it
 pushes a new userdata which wrappers the pointer 'ptr' of type 'type'.
 The parameter 'own' specifies if the object is owned be Lua and if it
 is 1 then Lua will GC the object when the userdata is disposed of.</div>
<p><tt>void* SWIG_MustGetPtr(lua_State* L, int index, swig_type_info
 *type, int flags, int argnum, const char* func_name);</tt></p>
<div class="indent"> This function is a version of SWIG_ConvertPtr(),
 except that it will either work, or it will trigger a lua_error() with
 a text error message. This function is rarely used, and may be
 deprecated in the future.</div>
<p><tt>SWIG_fail</tt></p>
<div class="indent"> This macro, when called within the context of a
 SWIG wrapped function, will jump to the error handler code. This will
 call any cleanup code (freeing any temp variables) and then triggers a
 lua_error.
<br> A common use for this code is:
<br>
<pre>
if (!SWIG_IsOK(SWIG_ConvertPtr( .....)){
 lua_pushstring(L, &quot;something bad happened&quot;);
 SWIG_fail;
}</pre>
</div>
<p><tt>SWIG_fail_arg(char* func_name, int argnum, char* type)</tt></p>
<div class="indent"> This macro, when called within the context of a
 SWIG wrapped function, will display the error message and jump to the
 error handler code. The error message is of the form
<pre>
&quot;Error in <i>func_name</i> (arg <i>argnum</i>), expected '<i>type</i>' got '<i>whatever the type was</i>'&quot;
</pre>
</div>
<p><tt>SWIG_fail_ptr(const char* fn_name, int argnum, swig_type_info*
 type);</tt></p>
<div class="indent"> Similar to SWIG_fail_arg, except that it will
 display the swig_type_info information instead.</div>
<h2><a name="Lua_nn32">28.6 Customization of your Bindings</a></h2>
<p> This section covers adding of some small extra bits to your module
 to add the last finishing touches.</p>
<h3><a name="Lua_nn33">28.6.1 Writing your own custom wrappers</a></h3>
<p> Sometimes, it may be necessary to add your own special functions,
 which bypass the normal SWIG wrapper method, and just use the native
 Lua API calls. These 'native' functions allow direct adding of your own
 code into the module. This is performed with the <tt>%native</tt>
 directive as follows:</p>
<div class="code">
<pre>%native(my_func) int native_function(lua_State*L);  // registers native_function() with SWIG
...
%{
int native_function(lua_State*L) // my native code
{
 ...
}
%}
</pre>
</div>
<p> The <tt>%native</tt> directive in the above example, tells SWIG that
 there is a function <tt>int native_function(lua_State*L);</tt> which is
 to be added into the module under the name '<tt>my_func</tt>'. SWIG
 will not add any wrapper for this function, beyond adding it into the
 function table. How you write your code is entirely up to you.</p>
<h3><a name="Lua_nn34">28.6.2 Adding additional Lua code</a></h3>
<p> As well as adding additional C/C++ code, it's also possible to add
 your own Lua code to the module as well. This code is executed once all
 other initialisation, including the %init code has been called.</p>
<p> The directive <tt>%luacode</tt> adds code into the module which is
 executed upon loading. Normally you would use this to add your own
 functions to the module. Though you could easily perform other tasks.</p>
<div class="code">
<pre>%module example;

%luacode {
  function example.greet() 
    print &quot;hello world&quot; 
  end

  print &quot;Module loaded ok&quot;
}
...
%}
</pre>
</div>
<p> Notice that the code is not part of the module table. Therefore any
 references to the module must have the module name added.</p>
<p> Should there be an error in the Lua code, this will<em> not</em>
 stop loading of the module. The default behaviour of SWIG is to print
 an error message to stderr and then continue. It is possible to change
 this behaviour by using a <tt>#define SWIG_DOSTRING_FAIL(STR)</tt> to
 define a different behaviour should the code fail.</p>
<p> Good uses for this feature is adding of new code, or writing helper
 functions to simplify some of the code. See Examples/lua/arrays for an
 example of this code.</p>
<h2><a name="Lua_nn35">28.7 Details on the Lua binding</a></h2>
<p> In the previous section, a high-level view of Lua wrapping was
 presented. Obviously a lot of stuff happens behind the scenes to make
 this happen. This section will explain some of the low-level details on
 how this is achieved.</p>
<p><i> If you just want to use SWIG and don't care how it works, then
 stop reading here. This is going into the guts of the code and how it
 works. It's mainly for people who need to know what's going on within
 the code.</i></p>
<h3><a name="Lua_nn36">28.7.1 Binding global data into the module.</a></h3>
<p> Assuming that you had some global data that you wanted to share
 between C and Lua. How does SWIG do it?</p>
<div class="code">
<pre>%module example;
extern double Foo;
</pre>
</div>
<p> SWIG will effectively generate the pair of functions</p>
<div class="code">
<pre>void Foo_set(double);
double Foo_get();
</pre>
</div>
<p> At initialisation time, it will then add to the interpreter a table
 called 'example', which represents the module. It will then add all its
 functions to the module. (Note: older versions of SWIG actually added
 the Foo_set() and Foo_get() functions, current implementation does not
 add these functions any more.) But it also adds a metatable to this
 table, which has two functions (<tt>__index</tt> and <tt>__newindex</tt>
) as well as two tables (<tt>.get</tt> and <tt>.set</tt>) The following
 Lua code will show these hidden features.</p>
<div class="targetlang">
<pre>
&gt; print(example)
table: 003F8F90
&gt; m=getmetatable(example)
&gt; table.foreach(m, print)
.set    table: 003F9088
.get    table: 003F9038
__index function: 003F8FE0
__newindex      function: 003F8FF8
&gt; g=m['.get']
&gt; table.foreach(g, print)
Foo     function: 003FAFD8
&gt;
</pre>
</div>
<p> The .get and .set tables are lookups connecting the variable name
 'Foo' to the accessor/mutator functions (Foo_set, Foo_get)</p>
<p> The Lua equivalent of the code for the <tt>__index</tt> and <tt>
__newindex</tt> looks a bit like this</p>
<div class="targetlang">
<pre>
function __index(mod, name)
        local g=getmetatable(mod)['.get'] -- gets the table
        if not g then return nil end
        local f=g[name] -- looks for the function
        -- calls it &amp; returns the value
        if type(f)==&quot;function&quot; then return f() end
        return nil
end

function __newindex(mod, name, value)
        local s=getmetatable(mod)['.set'] -- gets the table
        if not s then return end
        local f=s[name] -- looks for the function
        -- calls it to set the value
        if type(f)==&quot;function&quot; then f(value)
        else rawset(mod, name, value) end
end
</pre>
</div>
<p> That way when you call '<tt>a=example.Foo</tt>', the interpreter
 looks at the table 'example' sees that there is no field 'Foo' and
 calls __index. This will in turn check in '.get' table and find the
 existence of 'Foo' and then return the value of the C function call
 'Foo_get()'. Similarly for the code '<tt>example.Foo=10</tt>', the
 interpreter will check the table, then call the __newindex which will
 then check the '.set' table and call the C function 'Foo_set(10)'.</p>
<h3><a name="Lua_nn37">28.7.2 Userdata and Metatables</a></h3>
<p> As mentioned earlier, classes and structures, are all held as
 pointer, using the Lua 'userdata' structure. This structure is actually
 a pointer to a C structure 'swig_lua_userdata', which contains the
 pointer to the data, a pointer to the swig_type_info (an internal SWIG
 struct) and a flag which marks if the object is to be disposed of when
 the interpreter no longer needs it. The actual accessing of the object
 is done via the metatable attached to this userdata.</p>
<p> The metatable is a Lua 5.0 feature (which is also why SWIG cannot
 wrap Lua 4.0). It's a table which holds a list of functions, operators
 and attributes. This is what gives the userdata the feeling that it is
 a real object and not just a hunk of memory.</p>
<p> Given a class</p>
<div class="code">
<pre>%module excpp;

class Point
{
public:
 int x, y;
 Point(){x=y=0;}
 ~Point(){}
 virtual void Print(){printf(&quot;Point @%p (%d, %d)\n&quot;, this, x, y);}
};
</pre>
</div>
<p> SWIG will create a module excpp, with all the various functions
 inside. However to allow the intuitive use of the userdata, SWIG also
 creates up a set of metatables. As seen in the above section on global
 variables, use of the metatables allows for wrappers to be used
 intuitively. To save effort, the code creates one metatable per class
 and stores it inside Lua's registry. Then when a new object is
 instantiated, the metatable is found in the registry and the userdata
 associated with the metatable. Currently, derived classes make a
 complete copy of the base class' table and then add on their own
 additional functions.</p>
<p> Some of the internals can be seen by looking at the metatable of a
 class:</p>
<div class="targetlang">
<pre>
&gt; p=excpp.Point()
&gt; print(p)
userdata: 003FDB28
&gt; m=getmetatable(p)
&gt; table.foreach(m, print)
.type   Point
__gc    function: 003FB6C8
__newindex      function: 003FB6B0
__index function: 003FB698
.get    table: 003FB4D8
.set    table: 003FB500
.fn     table: 003FB528
</pre>
</div>
<p> The '.type' attribute is the name of the class. The '.get' and
 '.set' tables work in a similar manner to the modules, the main
 difference is the '.fn' table which also holds all the member
 functions. (The '__gc' function is the class' destructor function)</p>
<p> The Lua equivalent of the code for enabling functions looks a little
 like this</p>
<div class="targetlang">
<pre>
function __index(obj, name)
        local m=getmetatable(obj) -- gets the metatable
        if not m then return nil end
        local g=m['.get'] -- gets the attribute table
        if not g then return nil end
        local f=g[name] -- looks for the get_attribute function
        -- calls it &amp; returns the value
        if type(f)==&quot;function&quot; then return f() end
        -- ok, so it not an attribute, maybe it's a function
        local fn=m['.fn'] -- gets the function table
        if not fn then return nil end
        local f=fn[name] -- looks for the function
        -- if found the fn then return the function
        -- so the interpreter can call it
        if type(f)==&quot;function&quot; then return f end
        return nil
end
</pre>
</div>
<p> So when 'p:Print()' is called, the __index looks on the object
 metatable for a 'Print' attribute, then looks for a 'Print' function.
 When it finds the function, it returns the function, and then
 interpreter can call 'Point_Print(p)'</p>
<p> In theory, you can play with this usertable &amp; add new features, but
 remember that it is a shared table between all instances of one class,
 and you could very easily corrupt the functions in all the instances.</p>
<p> Note: Both the opaque structures (like the FILE*) and normal wrapped
 classes/structs use the same 'swig_lua_userdata' structure. Though the
 opaque structures has do not have a metatable attached, or any
 information on how to dispose of them when the interpreter has finished
 with them.</p>
<p> Note: Operator overloads are basically done in the same way, by
 adding functions such as '__add' &amp; '__call' to the class' metatable.
 The current implementation is a bit rough as it will add any member
 function beginning with '__' into the metatable too, assuming its an
 operator overload.</p>
<h3><a name="Lua_nn38">28.7.3 Memory management</a></h3>
<p> Lua is very helpful with the memory management. The
 'swig_lua_userdata' is fully managed by the interpreter itself. This
 means that neither the C code nor the Lua code can damage it. Once a
 piece of userdata has no references to it, it is not instantly
 collected, but will be collected when Lua deems is necessary. (You can
 force collection by calling the Lua function <tt>collectgarbage()</tt>
). Once the userdata is about to be free'ed, the interpreter will check
 the userdata for a metatable and for a function '__gc'. If this exists
 this is called. For all complete types (ie normal wrapped classes &amp;
 structs) this should exist. The '__gc' function will check the
 'swig_lua_userdata' to check for the 'own' field and if this is true
 (which is will be for all owned data) it will then call the destructor
 on the pointer.</p>
<p> It is currently not recommended to edit this field or add some user
 code, to change the behaviour. Though for those who wish to try, here
 is where to look.</p>
<p> It is also currently not possible to change the ownership flag on
 the data (unlike most other scripting languages, Lua does not permit
 access to the data from within the interpreter).</p>
<HR NOSHADE>
<h1><a name="Octave">29 SWIG and Octave</a></h1>

<!-- INDEX -->
<div class="sectiontoc">
<ul>
<li><a href="#Octave_nn2">Preliminaries</a></li>
<li><a href="#Octave_nn3">Running SWIG</a>
<ul>
<li><a href="#Octave_nn4">Command-line options</a></li>
<li><a href="#Octave_nn5">Compiling a dynamic module</a></li>
<li><a href="#Octave_nn6">Using your module</a></li>
</ul>
</li>
<li><a href="#Octave_nn7">A tour of basic C/C++ wrapping</a>
<ul>
<li><a href="#Octave_nn8">Modules</a></li>
<li><a href="#Octave_nn9">Functions</a></li>
<li><a href="#Octave_nn10">Global variables</a></li>
<li><a href="#Octave_nn11">Constants and enums</a></li>
<li><a href="#Octave_nn12">Pointers</a></li>
<li><a href="#Octave_nn13">Structures and C++ classes</a></li>
<li><a href="#Octave_nn15">C++ inheritance</a></li>
<li><a href="#Octave_nn17">C++ overloaded functions</a></li>
<li><a href="#Octave_nn18">C++ operators</a></li>
<li><a href="#Octave_nn19">Class extension with %extend</a></li>
<li><a href="#Octave_nn20">C++ templates</a></li>
<li><a href="#Octave_nn21">C++ Smart Pointers</a>
<ul>
<li><a href="#Octave_smart_pointers_shared_ptr">The shared_ptr Smart
 Pointer</a></li>
<li><a href="#Octave_smart_pointers_generic">Generic Smart Pointers</a></li>
</ul>
</li>
<li><a href="#Octave_nn22">Directors (calling Octave from C++ code)</a></li>
<li><a href="#Octave_nn23">Threads</a></li>
<li><a href="#Octave_nn24">Memory management</a></li>
<li><a href="#Octave_nn25">STL support</a></li>
<li><a href="#Octave_nn26">Matrix typemaps</a></li>
</ul>
</li>
</ul>
</div>
<!-- INDEX -->
<p> Octave is a high-level language intended for numerical programming
 that is mostly compatible with MATLAB. More information can be found at
 <a href="http://www.gnu.org/software/octave/">Octave web site</a>.</p>
<p> This chapter is intended to give an introduction to using the
 module. You should also read the SWIG documentation that is not
 specific to Octave. Also, there are a dozen or so examples in the
 Examples/octave directory, and hundreds in the test suite
 (Examples/test-suite and Examples/test-suite/octave).</p>
<h2><a name="Octave_nn2">29.1 Preliminaries</a></h2>
<p> SWIG is regularly tested against the following versions of Octave:
 3.8, 4.0, 4.2.</p>
<p> Every effort is made to maintain backward compatibility with older
 versions of Octave. This cannot be guaranteed however, as in recent
 times new Octave releases have required nontrivial updates to SWIG,
 which may break backward compatibility for older Octave versions
 against which SWIG is not regularly tested.</p>
<p> The SWIG runtime exports the function <tt>swig_octave_prereq()</tt>
 for checking the version of Octave.</p>
<h2><a name="Octave_nn3">29.2 Running SWIG</a></h2>
<p> Let's start with a very simple SWIG interface file, example.i:</p>
<div class="code">
<pre>
%module swigexample
%{
#include &quot;example.h&quot;
%}
int gcd(int x, int y);
extern double Foo; </pre>
</div>
<p> To build an Octave module when wrapping C code, run SWIG using the <tt>
-octave</tt> option:</p>
<div class="shell">
<pre>$ swig -octave -o example_wrap.cpp example.i </pre>
</div>
<p> The <tt>-c++</tt> option is also required when wrapping C++ code:</p>
<div class="shell">
<pre>$ swig -octave -c++ -o example_wrap.cpp example.i </pre>
</div>
<p> This creates a C++ source file &quot;example_wrap.cpp&quot;. A C++ file is
 generated even when wrapping C code as Octave is itself written in C++
 and requires wrapper code to be in the same language. The generated C++
 source file contains the low-level wrappers that need to be compiled
 and linked with the rest of your C/C++ application (in this case, the
 gcd implementation) to create an extension module.</p>
<h3><a name="Octave_nn4">29.2.1 Command-line options</a></h3>
<p> The swig command line has a number of options you can use, like to
 redirect its output. Use <tt>swig -help</tt> to learn about these.
 Options specific to the Octave module are:</p>
<div class="shell">
<pre>$ swig -octave -help
...
Octave Options (available with -octave)
     -globals <em>name</em> - Set <em>name</em> used to access C global variables [default: 'cvar']
                     Use '.' to load C global variables into module namespace
     -opprefix <em>str</em> - Prefix <em>str</em> for global operator functions [default: 'op_']
</pre>
</div>
<p> The<em> -globals</em> option sets the name of the variable which is
 the namespace for C global variables exported by the module. The
 special name &quot;.&quot; loads C global variables into the module namespace,
 i.e. alongside C functions and structs exported by the module. The<em>
 -opprefix</em> options sets the prefix of the names of global/friend <a href="#Octave_nn18">
operator</a> functions.</p>
<h3><a name="Octave_nn5">29.2.2 Compiling a dynamic module</a></h3>
<p> Octave modules are DLLs/shared objects having the &quot;.oct&quot; suffix.
 Building an oct file is usually done with the mkoctfile command (either
 within Octave itself, or from the shell). For example,</p>
<div class="shell">
<pre>
$ swig -octave -c++ -o example_wrap.cpp example.i
$ mkoctfile example_wrap.cpp example.c
</pre>
</div>
<p> where &quot;example.c&quot; is the file containing the gcd() implementation.</p>
<p> mkoctfile can also be used to extract the build parameters required
 to invoke the compiler and linker yourself. See the Octave manual and
 mkoctfile man page.</p>
<p> mkoctfile will produce &quot;swigexample.oct&quot;, which contains the
 compiled extension module. Loading it into Octave is then a matter of
 invoking</p>
<div class="targetlang">
<pre>octave:1&gt; swigexample</pre>
</div>
<h3><a name="Octave_nn6">29.2.3 Using your module</a></h3>
<p> Assuming all goes well, you will be able to do this:
<br></p>
<div class="targetlang">
<pre>$ octave -q
octave:1&gt; swigexample
octave:2&gt; swigexample.gcd(4, 6)
ans =  2
octave:3&gt; swigexample.cvar.Foo
ans =  3
octave:4&gt; swigexample.cvar.Foo=4;
octave:5&gt; swigexample.cvar.Foo
ans =  4 </pre>
</div>
<h2><a name="Octave_nn7">29.3 A tour of basic C/C++ wrapping</a></h2>
<h3><a name="Octave_nn8">29.3.1 Modules</a></h3>
<p> The SWIG module directive specifies the name of the Octave module.
 If you specify &quot;module swigexample&quot;, then in Octave everything in the
 module will be accessible under &quot;swigexample&quot;, as in the above example.
 When choosing a module name, make sure you don't use the same name as a
 built-in Octave command or standard module name.</p>
<p> When Octave is asked to invoke <tt>swigexample</tt>, it will try to
 find the &quot;.m&quot; or &quot;.oct&quot; file that defines the function &quot;swigexample&quot;.
 You therefore need to make sure that &quot;swigexample.oct&quot; is in Octave's
 search path, which can be specified with the environment variable
 &quot;OCTAVE_PATH&quot;.</p>
<p> To load an Octave module, simply type its name:</p>
<div class="targetlang">
<pre>
octave:1&gt; swigexample;
octave:2&gt; gcd(4, 6)
ans =  2
octave:3&gt; cvar.Foo
ans =  3
octave:4&gt; cvar.Foo=4;
octave:5&gt; cvar.Foo
ans =  4
</pre>
</div>
<p> Modules can also be loaded from within functions, even before being
 loaded in the base context. If the module is also used in the base
 context, however, it must first be loaded again:</p>
<div class="targetlang">
<pre>
octave:1&gt; function l = my_lcm(a, b)
&gt; swigexample
&gt; l = abs(a*b)/swigexample.gcd(a, b);
&gt; endfunction
octave:2&gt; my_lcm(4, 6)
ans =  12
octave:3&gt; swigexample.gcd(4, 6)
error: can't perform indexing operations for &lt;unknown type&gt; type
octave:3&gt; swigexample;
octave:4&gt; swigexample.gcd(4, 6)
ans =  2
</pre>
</div>
<h3><a name="Octave_nn9">29.3.2 Functions</a></h3>
<p> Global functions are wrapped as new Octave built-in functions. For
 example,</p>
<div class="code">
<pre>%module swigexample
int fact(int n); </pre>
</div>
<p> creates a built-in function <tt>swigexample.fact(n)</tt> that works
 exactly like you think it does:</p>
<div class="targetlang">
<pre>octave:1&gt; swigexample.fact(4)
24 </pre>
</div>
<h3><a name="Octave_nn10">29.3.3 Global variables</a></h3>
<p> Global variables are a little special in Octave. Given a global
 variable:</p>
<div class="code">
<pre>%module swigexample
extern double Foo;
</pre>
</div>
<p> To expose variables, SWIG actually generates two functions, to get
 and set the value. In this case, Foo_set and Foo_set would be
 generated. SWIG then automatically calls these functions when you get
 and set the variable-- in the former case creating a local copy in the
 interpreter of the C variables, and in the latter case copying an
 interpreter variables onto the C variable.</p>
<div class="targetlang">
<pre>octave:1&gt; swigexample;
octave:2&gt; c=swigexample.cvar.Foo
c =  3
octave:3&gt; swigexample.cvar.Foo=4;
octave:4&gt; c
c =  3
octave:5&gt; swigexample.cvar.Foo
ans =  4</pre>
</div>
<p> If a variable is marked with the %immutable directive then any
 attempts to set this variable will cause an Octave error. Given a
 global variable:</p>
<div class="code">
<pre>%module swigexample
%immutable;
extern double Foo;
%mutable;
</pre>
</div>
<p> SWIG will allow the reading of <tt>Foo</tt> but when a set attempt
 is made, an error function will be called.</p>
<div class="targetlang">
<pre>octave:1&gt; swigexample
octave:2&gt; swigexample.Foo=4
error: attempt to set immutable member variable
error: assignment failed, or no method for `swig_type = scalar'
error: evaluating assignment expression near line 2, column 12 </pre>
</div>
<p> It is possible to add new functions or variables to the module. This
 also allows the user to rename/remove existing functions and constants
 (but not linked variables, mutable or immutable). Therefore users are
 recommended to be careful when doing so.</p>
<div class="targetlang">
<pre>octave:1&gt; swigexample;
octave:2&gt; swigexample.PI=3.142;
octave:3&gt; swigexample.PI
ans =  3.1420 </pre>
</div>
<h3><a name="Octave_nn11">29.3.4 Constants and enums</a></h3>
<p> Because Octave doesn't really have the concept of constants, C/C++
 constants are not really constant in Octave. They are actually just a
 copy of the value into the Octave interpreter. Therefore they can be
 changed just as any other value. For example given some constants:</p>
<div class="code">
<pre>%module swigexample
%constant int ICONST=42;
#define    SCONST      &quot;Hello World&quot;
enum Days{SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY};
</pre>
</div>
<p> This is 'effectively' converted into the following Octave code:</p>
<div class="targetlang">
<pre>swigexample.ICONST=42
swigexample.SCONST=&quot;Hello World&quot;
swigexample.SUNDAY=0
.... </pre>
</div>
<h3><a name="Octave_nn12">29.3.5 Pointers</a></h3>
<p> C/C++ pointers are fully supported by SWIG. Furthermore, SWIG has no
 problem working with incomplete type information. Given a wrapping of
 the &lt;file.h&gt; interface: C/C++ pointers are fully supported by SWIG.
 Furthermore, SWIG has no problem working with incomplete type
 information. Given a wrapping of the &lt;file.h&gt; interface:</p>
<div class="code">
<pre>%module swigexample
FILE *fopen(const char *filename, const char *mode);
int fputs(const char *, FILE *);
int fclose(FILE *);
</pre>
</div>
<p> When wrapped, you will be able to use the functions in a natural way
 from Octave. For example:</p>
<div class="targetlang">
<pre>
octave:1&gt; swigexample;
octave:2&gt; f=swigexample.fopen(&quot;w&quot;, &quot;junk&quot;);
octave:3&gt; swigexample.fputs(&quot;Hello world&quot;, f);
octave:4&gt; swigexample.fclose(f);
</pre>
</div>
<p> Simply printing the value of a wrapped C++ type will print its
 typename. E.g.,</p>
<div class="targetlang">
<pre>octave:1&gt; swigexample;
octave:2&gt; f=swigexample.fopen(&quot;junk&quot;, &quot;w&quot;);
octave:3&gt; f
f =

{
  _p_FILE, ptr = 0x9b0cd00
} </pre>
</div>
<p> As the user of the pointer, you are responsible for freeing it, or
 closing any resources associated with it (just as you would in a C
 program). This does not apply so strictly to classes and structs (see
 below).</p>
<div class="targetlang">
<pre>octave:1&gt; swigexample;
octave:2&gt; f=swigexample.fopen(&quot;not there&quot;, &quot;r&quot;);
error: value on right hand side of assignment is undefined
error: evaluating assignment expression near line 2, column 2 </pre>
</div>
<h3><a name="Octave_nn13">29.3.6 Structures and C++ classes</a></h3>
<p> SWIG wraps C structures and C++ classes by using a special Octave
 type called a <tt>swig_ref</tt>. A <tt>swig_ref</tt> contains a
 reference to one or more instances of C/C++ objects, or just the type
 information for an object. For each wrapped structure and class, a <tt>
swig_ref</tt> will be exposed that has the name of the type. When
 invoked as a function, it creates a new object of its type and returns
 a <tt>swig_ref</tt> that points to that instance. This provides a very
 natural interface. For example,</p>
<div class="code">
<pre>struct Point{
  int x, y;
};
</pre>
</div>
<p> is used as follows:</p>
<div class="targetlang">
<pre>octave:1&gt; swigexample;
octave:2&gt; p=swigexample.Point();
octave:3&gt; p.x=3;
octave:4&gt; p.y=5;
octave:5&gt; p.x, p.y
ans =  3
ans =  5 
</pre>
</div>
<p> In C++, invoking the type object in this way calls the object's
 constructor. <tt>swig_ref</tt> objects can also be acquired by having a
 wrapped function return a pointer, reference, or value of a
 non-primitive type.</p>
<p> The swig_ref type handles indexing operations such that usage maps
 closely to what you would have in C/C++. Structure members are accessed
 as in the above example, by calling set and get methods for C++
 variables. Methods also work as expected. For example, code wrapped in
 the following way</p>
<div class="code">
<pre>class Point{
public:
  int x, y;
  Point(int _x, int _y) : x(_x), y(_y) {}
  double distance(const Point&amp; rhs) {
    return sqrt(pow(x-rhs.x, 2)+pow(y-rhs.y, 2));
  }
  void set(int _x, int _y) {
    x=_x; y=_y;
  }
};
</pre>
</div>
<p> can be used from Octave like this</p>
<div class="targetlang">
<pre>octave:1&gt; swigexample;
octave:2&gt; p1=swigexample.Point(3, 5);
octave:3&gt; p2=swigexample.Point(1, 2);
octave:4&gt; p1.distance(p2)
ans =  3.6056
</pre>
</div>
<p> By using the <tt>swig_this()</tt> and <tt>swig_type()</tt>
 functions, one can discover the pointers to and types of the underlying
 C/C++ object.</p>
<div class="targetlang">
<pre>
octave:5&gt; swig_this(p1)
ans = 162504808
octave:6&gt; swig_type(p1)
ans = Point
</pre>
</div>
<p> Note that <tt>swig_ref</tt> is a reference-counted pointer to a
 C/C++ object/type, and as such has pass-by-reference semantics. For
 example if one has a allocated a single object but has two <tt>swig_ref</tt>
's pointing to it, modifying the object through either of them will
 change the single allocated object. This differs from the usual
 pass-by-value (copy-on-write) semantics that Octave maintains for
 built-in types. For example, in the following snippet, modifying <tt>b</tt>
 does not modify <tt>a</tt>,</p>
<div class="targetlang">
<pre>
octave:7&gt; a=struct('x', 4)
a =
{
  x =  4
}

octave:8&gt; b=a
b =
{
  x =  4
}

octave:9&gt; b.y=4
b =
{
  x =  4
  y =  4
}

octave:10&gt; a
a =
{
  x =  4
}
</pre>
</div>
<p> However, when dealing with wrapped objects, one gets the behavior</p>
<div class="targetlang">
<pre>
octave:2&gt; a=Point(3, 5)
a =

{
  Point, ptr = 0x9afbbb0
}

octave:3&gt; b=a
b =

{
  Point, ptr = 0x9afbbb0
}

octave:4&gt; b.set(2, 1);
octave:5&gt; b.x, b.y
ans =  2
ans =  1
octave:6&gt; a.x, a.y
ans =  2
ans =  1
</pre>
</div>
<p> Depending on the ownership setting of a <tt>swig_ref</tt>, it may
 call C++ destructors when its reference count goes to zero. See the
 section on memory management below for details.</p>
<h3><a name="Octave_nn15">29.3.7 C++ inheritance</a></h3>
<p> Single and multiple inheritance are fully supported. The <tt>
swig_ref</tt> type carries type information along with any C++ object
 pointer it holds. This information contains the full class hierarchy.
 When an indexing operation (such as a method invocation) occurs, the
 tree is walked to find a match in the current class as well as any of
 its bases. The lookup is then cached in the <tt>swig_ref</tt>.</p>
<h3><a name="Octave_nn17">29.3.8 C++ overloaded functions</a></h3>
<p> Overloaded functions are supported, and handled as in other modules.
 That is, each overload is wrapped separately (under internal names),
 and a dispatch function is also emitted under the external/visible
 name. The dispatch function selects which overload to call (if any)
 based on the passed arguments. <tt>typecheck</tt> typemaps are used to
 analyze each argument, as well as assign precedence. See the chapter on
 typemaps for details.</p>
<h3><a name="Octave_nn18">29.3.9 C++ operators</a></h3>
<p> C++ operator overloading is supported, in a way similar to other
 modules. The <tt>swig_ref</tt> type supports all unary and binary
 operators between itself and all other types that exist in the system
 at module load time. When an operator is used (where one of the
 operands is a <tt>swig_ref</tt>), the runtime routes the call to either
 a member function of the given object, or to a global function whose
 named is derived from the types of the operands (either both or just
 the lhs or rhs).</p>
<p> For example, if <tt>a</tt> and <tt>b</tt> are SWIG variables in
 Octave, <tt>a+b</tt> becomes <tt>a.__add__(b)</tt>. The wrapper is then
 free to implement __add__ to do whatever it wants. A wrapper may define
 the <tt>__add__</tt> function manually, %rename some other function to
 it, or %rename a C++ operator to it.</p>
<p> By default the C++ operators are renamed to their corresponding
 Octave operators. So without doing any work, the following interface</p>
<div class="code">
<pre>
%inline {
struct A {
  int value;
  A(int _value) : value(_value) {}
  A operator+ (const A&amp; x) {
    return A(value+x.value);
  }
};
}
</pre>
</div>
<p> is usable from Octave like this:</p>
<div class="targetlang">
<pre>
a=A(2), b=A(3), c=a+b
assert(c.value==5);
</pre>
</div>
<p> Octave operators are mapped in the following way:</p>
<div class="code">
<pre>
__brace__      a{args}
__brace_asgn__ a{args} = rhs
__paren__      a(args)
__paren_asgn__ a(args) = rhs
__str__        generates string rep
__not__        !a
__uplus__      +a
__uminus__     -a
__transpose__  a.'
__hermitian__  a'
__incr__       a++
__decr__       a--
__add__        a + b
__sub__        a - b
__mul__        a * b
__div__        a / b
__pow__        a ^ b
__ldiv__       a \ b
__lshift__     a &lt;&lt;b
__rshift__     a &gt;&gt; b
__lt__         a  &lt;b
__le__         a  &lt;= b
__eq__         a == b
__ge__         a &gt;= b
__gt__         a &gt; b
__ne__         a != b
__el_mul__     a .* b
__el_div__     a ./ b
__el_pow__     a .^ b
__el_ldiv__    a .\ b
__el_and__     a &amp; b
__el_or__      a | b
</pre>
</div>
<p> On the C++ side, the default mappings are as follows:</p>
<div class="code">
<pre>
%rename(__add__)       *::operator+;
%rename(__add__)       *::operator+();
%rename(__add__)       *::operator+() const;
%rename(__sub__)       *::operator-;
%rename(__uminus__)    *::operator-();
%rename(__uminus__)    *::operator-() const;
%rename(__mul__)       *::operator*;
%rename(__div__)       *::operator/;
%rename(__mod__)       *::operator%;
%rename(__lshift__)    *::operator&lt;
<!--;
%rename(__rshift__)    *::operator-->
&gt;;
%rename(__el_and__)    *::operator&amp;&amp;;
%rename(__el_or__)     *::operator||;
%rename(__xor__)       *::operator^;
%rename(__invert__)    *::operator~;
%rename(__lt__)        *::operator
<!--;
%rename(__le__)        *::operator&lt;=;
%rename(__gt__)        *::operator-->
;
%rename(__ge__)        *::operator&gt;=;
%rename(__eq__)        *::operator==;
%rename(__ne__)        *::operator!=;
%rename(__not__)       *::operator!;
%rename(__incr__)      *::operator++;
%rename(__decr__)      *::operator--;
%rename(__paren__)     *::operator();
%rename(__brace__)     *::operator[];
</pre>
</div>
<p> Octave can also utilise friend (i.e. non-member) operators with a
 simple %rename: see the example in the Examples/octave/operator
 directory.</p>
<h3><a name="Octave_nn19">29.3.10 Class extension with %extend</a></h3>
<p> The %extend directive works the same as in other modules.</p>
<p> You can use it to define special behavior, like for example defining
 Octave operators not mapped to C++ operators, or defining certain
 Octave mechanisms such as how an object prints. For example, the <tt>
octave_value::{is_string, string_value, print}</tt> functions are routed
 to a special method <tt>__str__</tt> that can be defined inside an
 %extend.</p>
<div class="code">
<pre>
%extend A {
string __str__() {
  stringstream sout;
  sout&lt;&lt;$self-&gt;value;
  return sout.str();
}
}
</pre>
</div>
<p> Then in Octave one gets,</p>
<div class="targetlang">
<pre>
octave:1&gt; a=A(4);
octave:2&gt; a
a = 4
octave:3&gt; printf(&quot;%s\n&quot;, a);
4
octave:4&gt; a.__str__()
4
</pre>
</div>
<p> Similarly, Octave can use the <tt>__float__</tt> method to convert
 an object to a numeric value.</p>
<p> Octave 3.8.0 and later versions will also map unary functions X() to
 the corresponding <tt>__X__</tt> method, where X includes: abs(),
 acos(), acosh(), angle(), arg(), asin(), asinh(), atan(), atanh(),
 cbrt(), ceil(), conj(), cos(), cosh(), dawson(), erf(), erfc(),
 erfcinv(), erfcx(), erfi(), erfinv(), exp(), expm1(), finite(), fix(),
 floor(), gamma(), imag(), isalnum(), isalpha(), isascii(), iscntrl(),
 isdigit(), isgraph(), isinf(), islower(), isna(), isnan(), isprint(),
 ispunct(), isspace(), isupper(), isxdigit(), lgamma(), log(), log10(),
 log1p(), log2(), real(), round(), roundb(), signbit(), signum(), sin(),
 sinh(), sqrt(), tan(), tanh(), toascii(), tolower(), toupper()</p>
<h3><a name="Octave_nn20">29.3.11 C++ templates</a></h3>
<p> C++ class and function templates are fully supported as in other
 modules, in that the %template directive may used to create explicit
 instantiations of templated types. For example, function templates can
 be instantiated as follows:</p>
<div class="code">
<pre>%module swigexample
%inline {
  template&lt;class __scalar&gt;
    __scalar mul(__scalar a, __scalar b) {
    return a*b;
  }
}
%include &lt;std_complex.i&gt;
%template(mul) mul&lt;std::complex&lt;double&gt; &gt;
%template(mul) mul&lt;double&gt;
</pre>
</div>
<p> and then used from Octave</p>
<div class="targetlang">
<pre>
octave:1&gt; mul(4, 3)
ans =  12
octave:2&gt; mul(4.2, 3.6)
ans =  15.120
octave:3&gt; mul(3+4i, 10+2i)
ans =  22 + 46i
</pre>
</div>
<p> Similarly, class templates can be instantiated as in the following
 example,</p>
<div class="code">
<pre>%module swigexample
%include &lt;std_complex.i&gt;
%include &lt;std_string.i&gt;
%inline {
  #include &lt;sstream&gt;
  template&lt;class __scalar&gt; class sum {
    __scalar s;
  public:
    sum(__scalar _s=0) : s(_s) {}
    sum&amp; add(__scalar _s) {
      s+=_s;
      return *this;
    }
    std::string __str__() const {
      std::stringstream sout;
      sout&lt;&lt;s;
      return sout.str();
    }
  };
}
%template(sum_complex) sum&lt;std::complex&lt;double&gt; &gt;;
%template(sum_double) sum&lt;double&gt;;
</pre>
</div>
<p> and then used from Octave</p>
<div class="targetlang">
<pre>
octave:2&gt; a=sum_complex(2+3i);
octave:3&gt; a.add(2)
ans =

(4, 3)
octave:4&gt; a.add(3+i)
ans =

(7, 4)
</pre>
</div>
<h3><a name="Octave_nn21">29.3.12 C++ Smart Pointers</a></h3>
<h4><a name="Octave_smart_pointers_shared_ptr">29.3.12.1 The shared_ptr
 Smart Pointer</a></h4>
<p> The C++11 standard provides <tt>std::shared_ptr</tt> which was
 derived from the Boost implementation, <tt>boost::shared_ptr</tt>. Both
 of these are available for Octave in the SWIG library and usage is
 outlined in the <a href="#Library_std_shared_ptr">shared_ptr smart
 pointer</a> library section.</p>
<h4><a name="Octave_smart_pointers_generic">29.3.12.2 Generic Smart
 Pointers</a></h4>
<p> C++ smart pointers are fully supported as in other modules.</p>
<h3><a name="Octave_nn22">29.3.13 Directors (calling Octave from C++
 code)</a></h3>
<p> There is full support for SWIG Directors, which permits Octave code
 to subclass C++ classes, and implement their virtual methods.</p>
<p> Octave has no direct support for object oriented programming,
 however the <tt>swig_ref</tt> type provides some of this support. You
 can manufacture a <tt>swig_ref</tt> using the <tt>subclass</tt>
 function (provided by the SWIG/Octave runtime).</p>
<p> For example,</p>
<div class="targetlang">
<pre>
octave:1&gt; a=subclass();
octave:2&gt; a.my_var = 4;
octave:3&gt; a.my_method = @(self) printf(&quot;my_var = &quot;, self.my_var);
octave:4&gt; a.my_method();
my_var = 4
</pre>
</div>
<p> <tt>subclass()</tt> can also be used to subclass one or more C++
 types. Suppose you have an interface defined by</p>
<div class="code">
<pre>
%inline {
class A {
public:
  virtual my_method() {
    printf(&quot;c-side routine called\n&quot;);
  }
};
void call_your_method(A&amp; a) {
  a.my_method();
}
}
</pre>
</div>
<p> Then from Octave you can say:</p>
<div class="targetlang">
<pre>
octave:1&gt; B=@() subclass(A(), @my_method);
octave:2&gt; function my_method(self)
octave:3&gt;   printf(&quot;octave-side routine called\n&quot;);
octave:4&gt; end
octave:5&gt; call_your_method(B());
octave-side routine called
</pre>
</div>
<p> or more concisely,</p>
<div class="targetlang">
<pre>
octave:1&gt; B=@() subclass(A(), 'my_method', @(self) printf(&quot;octave-side routine called\n&quot;));
octave:2&gt; call_your_method(B());
octave-side routine called
</pre>
</div>
<p> Note that you have to enable directors via the %feature directive
 (see other modules for this).</p>
<p> <tt>subclass()</tt> will accept any number of C++ bases or other <tt>
subclass()</tt>'ed objects, <tt>(string, octave_value)</tt> pairs, and <tt>
function_handles</tt>. In the first case, these are taken as base
 classes; in the second case, as named members (either variables or
 functions, depending on whether the given value is a function handle);
 in the third case, as member functions whose name is taken from the
 given function handle. E.g.,</p>
<div class="targetlang">
<pre>
octave:1&gt; B=@(some_var=2) subclass(A(), 'some_var', some_var, @some_func, 'another_func',
@(self) do_stuff())
</pre>
</div>
<p> You can also assign non-C++ member variables and functions after
 construct time. There is no support for non-C++ static members.</p>
<p> There is limited support for explicitly referencing C++ bases. So,
 in the example above, we could have</p>
<div class="targetlang">
<pre>
octave:1&gt; B=@() subclass(A(), @my_method);
octave:2&gt; function my_method(self)
octave:3&gt;   self.A.my_method();
octave:4&gt;   printf(&quot;octave-side routine called\n&quot;);
octave:5&gt; end
octave:6&gt; call_your_method(B());
c-side routine called
octave-side routine called
</pre>
</div>
<h3><a name="Octave_nn23">29.3.14 Threads</a></h3>
<p> The use of threads in wrapped Director code is not supported; i.e.,
 an Octave-side implementation of a C++ class must be called from the
 Octave interpreter's thread. Anything fancier (apartment/queue model,
 whatever) is left to the user. Without anything fancier, this amounts
 to the limitation that Octave must drive the module... like, for
 example, an optimization package that calls Octave to evaluate an
 objective function.</p>
<h3><a name="Octave_nn24">29.3.15 Memory management</a></h3>
<p> As noted above, <tt>swig_ref</tt> represents a reference counted
 pointer to a C/C++-side object. It also contains a flag indicating
 whether Octave or the C/C++ code owns the object. If Octave owns it,
 any destructors will be called when the reference count reaches zero.
 If the C/C++ side owns the object, then destructors will not be called
 when the reference count goes to zero.</p>
<p> For example,<div class="code">
<pre>
%inline {
class A {
public:
  A() { printf(&quot;A constructing\n&quot;); }
  ~A() { printf(&quot;A destructing\n&quot;); }
};
}
</pre>
</div></p>
<p> Would produce this behavior in Octave:</p>
<div class="targetlang">
<pre>
octave:1&gt; a=A();
A constructing
octave:2&gt; b=a;
octave:3&gt; clear a;
octave:4&gt; b=4;
A destructing
</pre>
</div>
<p> The %newobject directive may be used to control this behavior for
 pointers returned from functions.</p>
<p> In the case where one wishes for the C++ side to own an object that
 was created in Octave (especially a Director object), one can use the
 __disown() method to invert this logic. Then letting the Octave
 reference count go to zero will not destroy the object, but destroying
 the object will invalidate the Octave-side object if it still exists
 (and call destructors of other C++ bases in the case of multiple
 inheritance/<tt>subclass()</tt>'ing).</p>
<h3><a name="Octave_nn25">29.3.16 STL support</a></h3>
<p> Various STL library files are provided for wrapping STL containers.</p>
<h3><a name="Octave_nn26">29.3.17 Matrix typemaps</a></h3>
<p> Octave provides a rich set of classes for dealing with matrices.
 Currently there are no built-in typemaps to deal with those. However,
 these are relatively straight forward for users to add themselves (see
 the docs on typemaps). Without much work (a single typemap decl-- say,
 5 lines of code in the interface file), it would be possible to have a
 function</p>
<div class="code">
<pre>
double my_det(const double* mat, int m, int n);
</pre>
</div>
<p> that is accessed from Octave as,</p>
<div class="targetlang">
<pre>
octave:1&gt; my_det(rand(4));
ans = -0.18388
</pre>
</div> <tt>
<br></tt><HR NOSHADE>
<h1><a name="Perl5">30 SWIG and Perl5</a></h1>

<!-- INDEX -->
<div class="sectiontoc">
<ul>
<li><a href="#Perl5_nn2">Overview</a></li>
<li><a href="#Perl5_nn3">Preliminaries</a>
<ul>
<li><a href="#Perl5_nn4">Getting the right header files</a></li>
<li><a href="#Perl5_nn5">Compiling a dynamic module</a></li>
<li><a href="#Perl5_nn6">Building a dynamic module with MakeMaker</a></li>
<li><a href="#Perl5_nn7">Building a static version of Perl</a></li>
<li><a href="#Perl5_nn8">Using the module</a></li>
<li><a href="#Perl5_nn9">Compilation problems and compiling with C++</a></li>
<li><a href="#Perl5_nn10">Compiling for 64-bit platforms</a></li>
</ul>
</li>
<li><a href="#Perl5_nn11">Building Perl Extensions under Windows</a>
<ul>
<li><a href="#Perl5_nn12">Running SWIG from Developer Studio</a></li>
<li><a href="#Perl5_nn13">Using other compilers</a></li>
</ul>
</li>
<li><a href="#Perl5_nn14">The low-level interface</a>
<ul>
<li><a href="#Perl5_nn15">Functions</a></li>
<li><a href="#Perl5_nn16">Global variables</a></li>
<li><a href="#Perl5_nn17">Constants</a></li>
<li><a href="#Perl5_nn18">Pointers</a></li>
<li><a href="#Perl5_nn19">Structures</a></li>
<li><a href="#Perl5_nn20">C++ classes</a></li>
<li><a href="#Perl5_nn21">C++ classes and type-checking</a></li>
<li><a href="#Perl5_nn22">C++ overloaded functions</a></li>
<li><a href="#Perl5_nn23">Operators</a></li>
<li><a href="#Perl5_nn24">Modules and packages</a></li>
</ul>
</li>
<li><a href="#Perl5_nn25">Input and output parameters</a></li>
<li><a href="#Perl5_nn26">Exception handling</a></li>
<li><a href="#Perl5_nn27">Remapping datatypes with typemaps</a>
<ul>
<li><a href="#Perl5_nn28">A simple typemap example</a></li>
<li><a href="#Perl5_nn29">Perl5 typemaps</a></li>
<li><a href="#Perl5_nn30">Typemap variables</a></li>
<li><a href="#Perl5_nn31">Useful functions</a></li>
</ul>
</li>
<li><a href="#Perl5_nn32">Typemap Examples</a>
<ul>
<li><a href="#Perl5_nn33">Converting a Perl5 array to a char **</a></li>
<li><a href="#Perl5_nn34">Return values</a></li>
<li><a href="#Perl5_nn35">Returning values from arguments</a></li>
<li><a href="#Perl5_nn36">Accessing array structure members</a></li>
<li><a href="#Perl5_nn37">Turning Perl references into C pointers</a></li>
<li><a href="#Perl5_nn38">Pointer handling</a></li>
</ul>
</li>
<li><a href="#Perl5_nn39">Proxy classes</a>
<ul>
<li><a href="#Perl5_nn40">Preliminaries</a></li>
<li><a href="#Perl5_nn41">Structure and class wrappers</a></li>
<li><a href="#Perl5_nn42">Object Ownership</a></li>
<li><a href="#Perl5_nn43">Nested Objects</a></li>
<li><a href="#Perl5_nn44">Proxy Functions</a></li>
<li><a href="#Perl5_nn45">Inheritance</a></li>
<li><a href="#Perl5_nn46">Modifying the proxy methods</a></li>
</ul>
</li>
<li><a href="#Perl5_nn47">Adding additional Perl code</a></li>
<li><a href="#Perl5_directors">Cross language polymorphism</a>
<ul>
<li><a href="#Perl5_nn48">Enabling directors</a></li>
<li><a href="#Perl5_nn49">Director classes</a></li>
<li><a href="#Perl5_nn50">Ownership and object destruction</a></li>
<li><a href="#Perl5_nn51">Exception unrolling</a></li>
<li><a href="#Perl5_nn52">Overhead and code bloat</a></li>
<li><a href="#Perl5_nn53">Typemaps</a></li>
</ul>
</li>
</ul>
</div>
<!-- INDEX -->
<p><b> Caution: This chapter is under repair!</b></p>
<p> This chapter describes SWIG's support of Perl5. Although the Perl5
 module is one of the earliest SWIG modules, it has continued to evolve
 and has been improved greatly with the help of SWIG users. For the best
 results, it is recommended that SWIG be used with Perl 5.8 or later.
 We're no longer testing regularly with older versions, but Perl 5.6
 seems to mostly work, while older versions don't.</p>
<h2><a name="Perl5_nn2">30.1 Overview</a></h2>
<p> To build Perl extension modules, SWIG uses a layered approach. At
 the lowest level, simple procedural wrappers are generated for
 functions, classes, methods, and other declarations in the input file.
 Then, for structures and classes, an optional collection of Perl proxy
 classes can be generated in order to provide a more natural object
 oriented Perl interface. These proxy classes simply build upon the
 low-level interface.</p>
<p> In describing the Perl interface, this chapter begins by covering
 the essentials. First, the problem of configuration, compiling, and
 installing Perl modules is discussed. Next, the low-level procedural
 interface is presented. Finally, proxy classes are described. Advanced
 customization features, typemaps, and other options are found near the
 end of the chapter.</p>
<h2><a name="Perl5_nn3">30.2 Preliminaries</a></h2>
<p> To build a Perl5 module, run SWIG using the <tt>-perl</tt> or <tt>
-perl5</tt> option as follows:</p>
<div class="code">
<pre>
swig -perl example.i

</pre>
</div>
<p> This produces two files. The first file, <tt>example_wrap.c</tt>
 contains all of the C code needed to build a Perl5 module. The second
 file, <tt>example.pm</tt> contains supporting Perl code needed to
 properly load the module.</p>
<p> To build the module, you will need to compile the file <tt>
example_wrap.c</tt> and link it with the rest of your program.</p>
<h3><a name="Perl5_nn4">30.2.1 Getting the right header files</a></h3>
<p> In order to compile, SWIG extensions need the following Perl5 header
 files:</p>
<div class="code">
<pre>
#include &quot;Extern.h&quot;
#include &quot;perl.h&quot;
#include &quot;XSUB.h&quot;
</pre>
</div>
<p> These are typically located in a directory like this</p>
<div class="code">
<pre>
/usr/lib/perl/5.14/CORE
</pre>
</div>
<p> The SWIG configuration script automatically tries to locate this
 directory so that it can compile examples. However, if you need to find
 out where the directory is located, an easy way to find out is to ask
 Perl itself:</p>
<div class="code">
<pre>
$ perl -e 'use Config; print &quot;$Config{archlib}\n&quot;;'
/usr/lib/perl/5.14
</pre>
</div>
<h3><a name="Perl5_nn5">30.2.2 Compiling a dynamic module</a></h3>
<p> The preferred approach to building an extension module is to compile
 it into a shared object file or DLL. Assuming you have code you need to
 link to in a file called <tt>example.c</tt>, you will need to compile
 your program using commands like this (shown for Linux):</p>
<div class="code">
<pre>
$ swig -perl example.i
$ gcc -fPIC example.c
$ gcc -fPIC -c example_wrap.c -I/usr/lib/perl/5.14/CORE -Dbool=char
$ gcc -shared example.o example_wrap.o -o example.so
</pre>
</div>
<p> The exact compiler options vary from platform to platform. 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>
SWIG/Examples/perl5</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="https://github.com/swig/swig/wiki">
SWIG Wiki</a> for additional information.</p>
<p> When linking the module, the name of the shared object file must
 match the module name used in the SWIG interface file. If you used `<tt>
%module example</tt>', then the target should be named `<tt>example.so</tt>
', `<tt>example.sl</tt>', or the appropriate dynamic module name on your
 system.</p>
<h3><a name="Perl5_nn6">30.2.3 Building a dynamic module with MakeMaker</a>
</h3>
<p> It is also possible to use Perl to build dynamically loadable
 modules for you using the MakeMaker utility. To do this, write a Perl
 script such as the following:</p>
<div class="targetlang">
<pre>
# File : Makefile.PL
use ExtUtils::MakeMaker;
WriteMakefile(
        `NAME'    =&gt; `example',                  # Name of package
        `LIBS'    =&gt; [`-lm'],                    # Name of custom libraries
        `OBJECT'  =&gt; `example.o example_wrap.o'  # Object files
);

</pre>
</div>
<p> Now, to build a module, simply follow these steps:</p>
<div class="code">
<pre>
$ perl Makefile.PL
$ make
$ make install
</pre>
</div>
<p> If you are planning to distribute a SWIG-generated module, this is
 the preferred approach to compilation. More information about MakeMaker
 can be found in &quot;Programming Perl, 2nd ed.&quot; by Larry Wall, Tom
 Christiansen, and Randal Schwartz.</p>
<h3><a name="Perl5_nn7">30.2.4 Building a static version of Perl</a></h3>
<p> If you machine does not support dynamic loading or if you've tried
 to use it without success, you can build a new version of the Perl
 interpreter with your SWIG extensions added to it. To build a static
 extension, you first need to invoke SWIG as follows:</p>
<div class="code">
<pre>
$ swig -perl -static example.i
</pre>
</div>
<p> By default SWIG includes code for dynamic loading, but the <tt>
-static</tt> option takes it out.</p>
<p> Next, you will need to supply a <tt>main()</tt> function that
 initializes your extension and starts the Perl interpreter. While, this
 may sound daunting, SWIG can do this for you automatically as follows:</p>
<div class="targetlang">
<pre>
%module example

%inline %{
extern double My_variable;
extern int fact(int);
%}

// Include code for rebuilding Perl
%include &lt;perlmain.i&gt;
</pre>
</div>
<p> The same thing can be accomplished by running SWIG as follows:</p>
<div class="code">
<pre>
$ swig -perl -static -lperlmain.i example.i
</pre>
</div>
<p> The <tt>perlmain.i</tt> file inserts Perl's <tt>main()</tt> function
 into the wrapper code and automatically initializes the SWIG generated
 module. If you just want to make a quick a dirty module, this may be
 the easiest way. By default, the <tt>perlmain.i</tt> code does not
 initialize any other Perl extensions. If you need to use other
 packages, you will need to modify it appropriately. You can do this by
 just copying <tt>perlmain.i</tt> out of the SWIG library, placing it in
 your own directory, and modifying it to suit your purposes.</p>
<p> To build your new Perl executable, follow the exact same procedure
 as for a dynamic module, but change the link line to something like
 this:</p>
<div class="code">
<pre>
$ gcc example.o example_wrap.o -L/usr/lib/perl/5.14/CORE \
        -lperl -lsocket -lnsl -lm -o myperl
</pre>
</div>
<p> This will produce a new version of Perl called <tt>myperl</tt>. It
 should be functionality identical to Perl with your C/C++ extension
 added to it. Depending on your machine, you may need to link with
 additional libraries such as <tt>-lsocket, -lnsl, -ldl</tt>, etc.</p>
<h3><a name="Perl5_nn8">30.2.5 Using the module</a></h3>
<p> To use the module, simply use the Perl <tt>use</tt> statement. If
 all goes well, you will be able to do this:</p>
<div class="targetlang">
<pre>
$ perl
use example;
print example::fact(4), &quot;\n&quot;;
24
</pre>
</div>
<p> A common error received by first-time users is the following:</p>
<div class="targetlang">
<pre>
use example;
Can't locate example.pm in @INC (@INC contains: /etc/perl /usr/local/lib/perl/5.14.2 /usr/local/share/perl/5.14.2 /usr/lib/perl5 /usr/share/perl5 /usr/lib/perl/5.14 /usr/share/perl/5.14 /usr/local/lib/site_perl .) at - line 1.
BEGIN failed--compilation aborted at - line 1.
</pre>
</div>
<p> This error is almost caused when the name of the shared object file
 you created doesn't match the module name you specified with the <tt>
%module</tt> directive.</p>
<p> A somewhat related, but slightly different error is this:</p>
<div class="targetlang">
<pre>
use example;
Can't find 'boot_example' symbol in ./example.so
 at - line 1
BEGIN failed--compilation aborted at - line 1.
</pre>
</div>
<p> This error is generated because Perl can't locate the module
 bootstrap function in the SWIG extension module. This could be caused
 by a mismatch between the module name and the shared library name.
 However, another possible cause is forgetting to link the
 SWIG-generated wrapper code with the rest of your application when you
 linked the extension module.</p>
<p> Another common error is the following:</p>
<div class="targetlang">
<pre>
use example;
Can't load './example.so' for module example: ./example.so: 
undefined symbol: Foo at /usr/lib/perl/5.14/i386-linux/DynaLoader.pm line 169.

 at - line 1
BEGIN failed--compilation aborted at - line 1.
</pre>
</div>
<p> This error usually indicates that you forgot to include some object
 files or libraries in the linking of the shared library file. Make sure
 you compile both the SWIG wrapper file and your original program into a
 shared library file. Make sure you pass all of the required libraries
 to the linker.</p>
<p> Sometimes unresolved symbols occur because a wrapper has been
 created for a function that doesn't actually exist in a library. This
 usually occurs when a header file includes a declaration for a function
 that was never actually implemented or it was removed from a library
 without updating the header file. To fix this, you can either edit the
 SWIG input file to remove the offending declaration or you can use the <tt>
%ignore</tt> directive to ignore the declaration. Better yet, update the
 header file so that it doesn't have an undefined declaration.</p>
<p> Finally, suppose that your extension module is linked with another
 library like this:</p>
<div class="code">
<pre>
$ gcc -shared example.o example_wrap.o -L/home/beazley/projects/lib -lfoo \
      -o example.so
</pre>
</div>
<p> If the <tt>foo</tt> library is compiled as a shared library, you
 might get the following error when you try to use your module:</p>
<div class="targetlang">
<pre>
use example;
Can't load './example.so' for module example: libfoo.so: cannot open shared object file: 
No such file or directory at /usr/lib/perl/5.14/i386-linux/DynaLoader.pm line 169.

 at - line 1
BEGIN failed--compilation aborted at - line 1.
&gt;&gt;&gt;                 
</pre>
</div>
<p> This error is generated because the dynamic linker can't locate the <tt>
libfoo.so</tt> library. When shared libraries are loaded, the system
 normally only checks a few standard locations such as <tt>/usr/lib</tt>
 and <tt>/usr/local/lib</tt>. To get the loader to look in other
 locations, there are several things you can do. First, you can
 recompile your extension module with extra path information. For
 example, on Linux you can do this:</p>
<div class="code">
<pre>
$ gcc -shared example.o example_wrap.o -L/home/beazley/projects/lib -lfoo \
      <b>-Xlinker -rpath /home/beazley/projects/lib \</b>
      -o example.so
</pre>
</div>
<p> Alternatively, you can set the <tt>LD_LIBRARY_PATH</tt> environment
 variable to include the directory with your shared libraries. If
 setting <tt>LD_LIBRARY_PATH</tt>, be aware that setting this variable
 can introduce a noticeable performance impact on all other applications
 that you run. To set it only for Perl, you might want to do this
 instead:</p>
<div class="code">
<pre>
$ env LD_LIBRARY_PATH=/home/beazley/projects/lib perl
</pre>
</div>
<p> Finally, you can 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>
<h3><a name="Perl5_nn9">30.2.6 Compilation problems and compiling with
 C++</a></h3>
<p> Compilation of C++ extensions has traditionally been a tricky
 problem. Since the Perl interpreter is written in C, you need to take
 steps to make sure C++ is properly initialized and that modules are
 compiled correctly.</p>
<p> On most machines, C++ extension modules should be linked using the
 C++ compiler. For example:</p>
<div class="code">
<pre>
$ swig -c++ -perl example.i
$ g++ -fPIC -c example.cxx
$ g++ -fPIC -c example_wrap.cxx -I/usr/lib/perl/5.14/i386-linux/CORE
$ <b>g++ -shared example.o example_wrap.o -o example.so</b>
</pre>
</div>
<p> In addition to this, you may need to include additional library
 files to make it work. For example, if you are using the Sun C++
 compiler on Solaris, you often need to add an extra library <tt>-lCrun</tt>
 like this:</p>
<div class="code">
<pre>
$ swig -c++ -perl example.i
$ CC -Kpic -c example.cxx
$ CC -Kpic -c example_wrap.cxx -I/usr/lib/perl/5.14/i386-linux/CORE
$ CC -shared example.o example_wrap.o -o example.so <b>-lCrun</b>
</pre>
</div>
<p> Of course, the names of the extra libraries are completely
 non-portable---you will probably need to do some experimentation.</p>
<p> Another possible compile problem comes from recent versions of Perl
 (5.8.0) and the GNU tools. If you see errors having to do with
 _crypt_struct, that means _GNU_SOURCE is not defined and it needs to
 be. So you should compile the wrapper like:</p>
<div class="code">
<pre>
$ g++ -fPIC -c example_wrap.cxx -I/usr/lib/perl/5.8.0/CORE -D_GNU_SOURCE
</pre>
</div>
<p> -D_GNU_SOURCE is also included in the Perl ccflags, which can be
 found by running</p>
<div class="code">
<pre>
$ perl -e 'use Config; print &quot;$Config{ccflags}\n&quot;;'
</pre>
</div>
<p> So you could also compile the wrapper like</p>
<div class="code">
<pre>
$ g++ -fPIC -c example_wrap.cxx -I/usr/lib/perl/5.8.0/CORE \
`perl -MConfig -e 'print $Config{ccflags}'`
</pre>
</div>
<p> Sometimes people have suggested that it is necessary to relink the
 Perl interpreter using the C++ compiler to make C++ extension modules
 work. In the experience of this author, this has never actually
 appeared to be necessary on most platforms. Relinking the interpreter
 with C++ really only includes the special run-time libraries described
 above---as long as you link your extension modules with these
 libraries, it should not be necessary to rebuild Perl.</p>
<p> If you aren't entirely sure about the linking of a C++ extension,
 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
 extension module. For example, notice the first line of output here:</p>
<div class="code">
<pre>
$ ldd swig
        <b>libstdc++-libc6.1-1.so.2 =&gt; /usr/lib/libstdc++-libc6.1-1.so.2 (0x40019000)</b>
        libm.so.6 =&gt; /lib/libm.so.6 (0x4005b000)
        libc.so.6 =&gt; /lib/libc.so.6 (0x40077000)
        /lib/ld-linux.so.2 =&gt; /lib/ld-linux.so.2 (0x40000000)
$
</pre>
</div>
<p> If linking wasn't enough of a problem, another major complication of
 C++ is that it does not define any sort of standard for binary linking
 of libraries. This means that C++ code compiled by different compilers
 will not link together properly as libraries nor is the memory layout
 of classes and data structures implemented in any kind of portable
 manner. In a monolithic C++ program, this problem may be unnoticed.
 However, in Perl, it is possible for different extension modules to be
 compiled with different C++ compilers. As long as these modules are
 self-contained, this probably won't matter. However, if these modules
 start sharing data, you will need to take steps to avoid segmentation
 faults and other erratic program behavior. Also, be aware that certain
 C++ features, especially RTTI, can behave strangely when working with
 multiple modules.</p>
<p> It should be noted that you may get a lot of error messages about
 the '<tt>bool</tt>' datatype when compiling a C++ Perl module. If you
 experience this problem, you can try the following:</p>
<ul>
<li>Use <tt>-DHAS_BOOL</tt> when compiling the SWIG wrapper code</li>
<li>Or use <tt>-Dbool=char</tt> when compiling.</li>
</ul>
<p> Finally, recent versions of Perl (5.8.0) have namespace conflict
 problems. Perl defines a bunch of short macros to make the Perl API
 function names shorter. For example, in
 /usr/lib/perl/5.8.0/CORE/embed.h there is a line:</p>
<div class="code">
<pre>
#define do_open Perl_do_open
</pre>
</div>
<p> The problem is, in the &lt;iostream&gt; header from GNU libstdc++v3 there
 is a private function named do_open. If &lt;iostream&gt; is included after
 the perl headers, then the Perl macro causes the iostream do_open to be
 renamed, which causes compile errors. Hopefully in the future Perl will
 support a PERL_NO_SHORT_NAMES flag, but for now the only solution is to
 undef the macros that conflict. Lib/perl5/noembed.h in the SWIG source
 has a list of macros that are known to conflict with either standard
 headers or other headers. But if you get macro type conflicts from
 other macros not included in Lib/perl5/noembed.h while compiling the
 wrapper, you will have to find the macro that conflicts and add an
 #undef into the .i file. Please report any conflicting macros you find
 to <a href="http://www.swig.org/mail.html">swig-user mailing list</a>.</p>
<h3><a name="Perl5_nn10">30.2.7 Compiling for 64-bit platforms</a></h3>
<p> On platforms that support 64-bit applications (Solaris, Irix, etc.),
 special care is required when building extension modules. On these
 machines, 64-bit applications are compiled and linked using a different
 set of compiler/linker options. In addition, it is not generally
 possible to mix 32-bit and 64-bit code together in the same
 application.</p>
<p> To utilize 64-bits, the Perl executable will need to be recompiled
 as a 64-bit application. In addition, all libraries, wrapper code, and
 every other part of your application will need to be compiled for
 64-bits. If you plan to use other third-party extension modules, they
 will also have to be recompiled as 64-bit extensions.</p>
<p> If you are wrapping commercial software for which you have no source
 code, you will be forced to use the same linking standard as used by
 that software. This may prevent the use of 64-bit extensions. It may
 also introduce problems on platforms that support more than one linking
 standard (e.g., -o32 and -n32 on Irix).</p>
<h2><a name="Perl5_nn11">30.3 Building Perl Extensions under Windows</a></h2>
<p> Building a SWIG extension to Perl under Windows is roughly similar
 to the process used with Unix. Normally, you will want to produce a DLL
 that can be loaded into the Perl interpreter. This section assumes you
 are using SWIG with Microsoft Visual C++ although the procedure may be
 similar with other compilers.</p>
<h3><a name="Perl5_nn12">30.3.1 Running SWIG from Developer Studio</a></h3>
<p> If you are developing your application within Microsoft developer
 studio, SWIG can be invoked as a custom build option. The process
 roughly requires these steps:</p>
<ul>
<li>Open up a new workspace and use the AppWizard to select a DLL
 project.</li>
<li>Add both the SWIG interface file (the .i file), any supporting C
 files, and the name of the wrapper file that will be created by SWIG
 (ie. <tt>example_wrap.c</tt>). Note: If using C++, choose a different
 suffix for the wrapper file such as <tt>example_wrap.cxx</tt>. Don't
 worry if the wrapper file doesn't exist yet--Developer studio will keep
 a reference to it around.</li>
<li>Select the SWIG interface file and go to the settings menu. Under
 settings, select the &quot;Custom Build&quot; option.</li>
<li>Enter &quot;SWIG&quot; in the description field.</li>
<li>Enter &quot;<tt>swig -perl5 -o $(ProjDir)\$(InputName)_wrap.cxx
 $(InputPath)</tt>&quot; in the &quot;Build command(s) field&quot;</li>
<li>Enter &quot;<tt>$(ProjDir)\$(InputName)_wrap.c</tt>xx&quot; in the &quot;Output
 files(s) field&quot;.</li>
<li>Next, select the settings for the entire project and go to
 &quot;C++:Preprocessor&quot;. Add the include directories for your Perl 5
 installation under &quot;Additional include directories&quot;.</li>
<li>Define the symbols WIN32 and MSWIN32 under preprocessor options. If
 using the ActiveWare port, also define the symbol PERL_OBJECT. Note
 that all extensions to the ActiveWare port must be compiled with the
 C++ compiler since Perl has been encapsulated in a C++ class.</li>
<li>Finally, select the settings for the entire project and go to &quot;Link
 Options&quot;. Add the Perl library file to your link libraries. For example
 &quot;perl.lib&quot;. Also, set the name of the output file to match the name of
 your Perl module (ie. example.dll).</li>
<li>Build your project.</li>
</ul>
<p> Now, assuming you made it this far, SWIG will be automatically
 invoked when you build your project. Any changes made to the interface
 file will result in SWIG being automatically invoked to produce a new
 version of the wrapper file. To run your new Perl extension, simply run
 Perl and use the use command as normal. For example:</p>
<div class="targetlang">
<pre>
DOS &gt; perl
use example;
$a = example::fact(4);
print &quot;$a\n&quot;;

</pre>
</div>
<h3><a name="Perl5_nn13">30.3.2 Using other compilers</a></h3>
<p> SWIG is known to work with Cygwin and may work with other compilers
 on Windows. For general hints and suggestions refer to the <a href="#Windows">
Windows</a> chapter.</p>
<h2><a name="Perl5_nn14">30.4 The low-level interface</a></h2>
<p> At its core, the Perl module uses a simple low-level interface to C
 function, variables, constants, and classes. This low-level interface
 can be used to control your application. However, it is also used to
 construct more user-friendly proxy classes as described in the next
 section.</p>
<h3><a name="Perl5_nn15">30.4.1 Functions</a></h3>
<p> C functions are converted into new Perl built-in commands (or
 subroutines). For example:</p>
<div class="targetlang">
<pre>
%module example
int fact(int a);
...
</pre>
</div>
<p> Now, in Perl:</p>
<div class="targetlang">
<pre>
use example;
$a = &amp;example::fact(2);
</pre>
</div>
<h3><a name="Perl5_nn16">30.4.2 Global variables</a></h3>
<p> Global variables are handled using Perl's magic variable mechanism.
 SWIG generates a pair of functions that intercept read/write operations
 and attaches them to a Perl variable with the same name as the C global
 variable. Thus, an interface like this</p>
<div class="targetlang">
<pre>
%module example;
...
double Spam;
...
</pre>
</div>
<p> is accessed as follows:</p>
<div class="targetlang">
<pre>
use example;
print $example::Spam, &quot;\n&quot;;
$example::Spam = $example::Spam + 4
# ... etc ...

</pre>
</div>
<p> If a variable is declared as <tt>const</tt>, it is wrapped as a
 read-only variable. Attempts to modify its value will result in an
 error.</p>
<p> To make ordinary variables read-only, you can also use the <tt>
%immutable</tt> directive. For example:</p>
<div class="code">
<pre>
%{
extern char *path;
%}
%immutable;
extern char *path;
%mutable;
</pre>
</div>
<p> The <tt>%immutable</tt> directive stays in effect until it is
 explicitly disabled or cleared using <tt>%mutable</tt>. See the <a href="#SWIG_readonly_variables">
Creating read-only variables</a> section for further details.</p>
<p> It is also possible to tag a specific variable as read-only like
 this:</p>
<div class="code">
<pre>
%{
extern char *path;
%}
%immutable path; 
...
...
extern char *path;       // Declared later in the input
</pre>
</div>
<h3><a name="Perl5_nn17">30.4.3 Constants</a></h3>
<p> By default, constants are wrapped as read-only Perl variables. For
 example:</p>
<div class="code">
<pre>
%module example

#define FOO 42
</pre>
</div>
<p> In Perl:</p>
<div class="targetlang">
<pre>
use example;
print $example::FOO, &quot;\n&quot;;   # OK
$example::FOO = 2;           # Error
</pre>
</div>
<p> Alternatively, if you use swig's <tt>-const</tt> option, constants
 are wrapped such that the leading $ isn't required (by using a constant
 subroutine), which usually gives a more natural Perl interface, for
 example:</p>
<div class="targetlang">
<pre>
use example;
print example::FOO, &quot;\n&quot;;
</pre>
</div>
<h3><a name="Perl5_nn18">30.4.4 Pointers</a></h3>
<p> SWIG represents pointers as blessed references. A blessed reference
 is the same as a Perl reference except that it has additional
 information attached to it indicating what kind of reference it is.
 That is, if you have a C declaration like this:</p>
<div class="code">
<pre>
Matrix *new_Matrix(int n, int m);
</pre>
</div>
<p> The module returns a value generated as follows:</p>
<div class="targetlang">
<pre>
$ptr = new_Matrix(int n, int m);     # Save pointer return result
bless $ptr, &quot;p_Matrix&quot;;              # Bless it as a pointer to Matrix
</pre>
</div>
<p> SWIG uses the &quot;blessing&quot; to check the datatype of various pointers.
 In the event of a mismatch, an error or warning message is generated.</p>
<p> To check to see if a value is the NULL pointer, use the <tt>
defined()</tt> command:</p>
<div class="targetlang">
<pre>
if (defined($ptr)) {
  print &quot;Not a NULL pointer.&quot;;
} else {
  print &quot;Is a NULL pointer.&quot;;
}

</pre>
</div>
<p> To create a NULL pointer, you should pass the <tt>undef</tt> value
 to a function.</p>
<p> The &quot;value&quot; of a Perl reference is not the same as the underlying C
 pointer that SWIG wrapper functions return. Suppose that <tt>$a</tt>
 and <tt>$b</tt> are two references that point to the same C object. In
 general, <tt>$a</tt> and <tt>$b</tt> will be different--since they are
 different references. Thus, it is a mistake to check the equality of <tt>
$a</tt> and <tt>$b</tt> to check the equality of two C pointers. The
 correct method to check equality of C pointers is to dereference them
 as follows:</p>
<div class="targetlang">
<pre>
if ($$a == $$b) {
  print &quot;a and b point to the same thing in C&quot;;
} else {
  print &quot;a and b point to different objects.&quot;;
}

</pre>
</div>
<p> As much as you might be inclined to modify a pointer value directly
 from Perl, don't. Manipulating pointer values is architecture dependent
 and could cause your program to crash. Similarly, don't try to manually
 cast a pointer to a new type by reblessing a pointer. This may not work
 like you expect and it is particularly dangerous when casting C++
 objects. If you need to cast a pointer or change its value, consider
 writing some helper functions instead. For example:</p>
<div class="code">
<pre>
%inline %{
/* C-style cast */
Bar *FooToBar(Foo *f) {
  return (Bar *) f;
}

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

Foo *IncrFoo(Foo *f, int i) {
  return f+i;
}
%}
</pre>
</div>
<p> Also, if working with C++, you should always try to use the new C++
 style casts. For example, in the above code, the C-style cast may
 return a bogus result whereas as the C++-style cast will return <tt>
NULL</tt> if the conversion can't be performed.</p>
<p><b> Compatibility Note:</b> In earlier versions, SWIG tried to
 preserve the same pointer naming conventions as XS and <tt>xsubpp</tt>.
 Given the advancement of the SWIG typesystem and the growing
 differences between SWIG and XS, this is no longer supported.</p>
<h3><a name="Perl5_nn19">30.4.5 Structures</a></h3>
<p> Access to the contents of a structure are provided through a set of
 low-level accessor functions as described in the &quot;SWIG Basics&quot; chapter.
 For example,</p>
<div class="code">
<pre>
struct Vector {
  double x, y, z;
};
</pre>
</div>
<p> gets mapped into the following collection of accessor functions:</p>
<div class="code">
<pre>
struct Vector *new_Vector();
void           delete_Vector(Vector *v);
double         Vector_x_get(Vector *obj)
void           Vector_x_set(Vector *obj, double x)
double         Vector_y_get(Vector *obj)
void           Vector_y_set(Vector *obj, double y)
double         Vector_z_get(Vector *obj)
void           Vector_z_set(Vector *obj, double z)

</pre>
</div>
<p> These functions are then used to access structure data from Perl as
 follows:</p>
<div class="targetlang">
<pre>
$v = example::new_Vector();
print example::Vector_x_get($v), &quot;\n&quot;;   # Get x component
example::Vector_x_set($v, 7.8);          # Change x component
</pre>
</div>
<p> Similar access is provided for unions and the data members of C++
 classes.</p>
<p> <tt>const</tt> members of a structure are read-only. Data members
 can also be forced to be read-only using the <tt>%immutable</tt>
 directive. For example:</p>
<div class="code">
<pre>
struct Foo {
  ...
  %immutable;
  int x;        /* Read-only members */
  char *name;
  %mutable;
  ...
};
</pre>
</div>
<p> When <tt>char *</tt> members of a structure are wrapped, the
 contents are assumed to be dynamically allocated using <tt>malloc</tt>
 or <tt>new</tt> (depending on whether or not SWIG is run with the -c++
 option). When the structure member is set, the old contents will be
 released and a new value created. If this is not the behavior you want,
 you will have to use a typemap (described later).</p>
<p> Array members are normally wrapped as read-only. For example,</p>
<div class="code">
<pre>
struct Foo {
  int x[50];
};
</pre>
</div>
<p> produces a single accessor function like this:</p>
<div class="code">
<pre>
int *Foo_x_get(Foo *self) {
  return self-&gt;x;
};
</pre>
</div>
<p> If you want to set an array member, you will need to supply a
 &quot;memberin&quot; typemap described later in this chapter. As a special case,
 SWIG does generate code to set array members of type <tt>char</tt>
 (allowing you to store a Python string in the structure).</p>
<p> When structure members are wrapped, they are handled as pointers.
 For example,</p>
<div class="code">
<pre>
struct Foo {
  ...
};

struct Bar {
  Foo f;
};
</pre>
</div>
<p> generates accessor functions such as this:</p>
<div class="code">
<pre>
Foo *Bar_f_get(Bar *b) {
  return &amp;b-&gt;f;
}

void Bar_f_set(Bar *b, Foo *val) {
  b-&gt;f = *val;
}
</pre>
</div>
<h3><a name="Perl5_nn20">30.4.6 C++ classes</a></h3>
<p> C++ classes are wrapped by building a set of low level accessor
 functions. Consider the following class:</p>
<div class="code">
<pre>
class List {
public:
  List();
  ~List();
  int  search(char *item);
  void insert(char *item);
  void remove(char *item);
  char *get(int n);
  int  length;
static void print(List *l);
};
</pre>
</div>
<p> When wrapped by SWIG, the following functions are created:</p>
<div class="code">
<pre>
List    *new_List();
void     delete_List(List *l);
int      List_search(List *l, char *item);
void     List_insert(List *l, char *item);
void     List_remove(List *l, char *item);
char    *List_get(List *l, int n);
int      List_length_get(List *l);
void     List_length_set(List *l, int n);
void     List_print(List *l);

</pre>
</div>
<p> In Perl, these functions are used in a straightforward manner:</p>
<div class="targetlang">
<pre>
use example;
$l = example::new_List();
example::List_insert($l, &quot;Ale&quot;);
example::List_insert($l, &quot;Stout&quot;);
example::List_insert($l, &quot;Lager&quot;)
example::List_print($l)
Lager
Stout
Ale
print example::List_length_get($l), &quot;\n&quot;;
3
</pre>
</div>
<p> At this low level, C++ objects are really just typed pointers.
 Member functions are accessed by calling a C-like wrapper with an
 instance pointer as the first argument. Although this interface is
 fairly primitive, it provides direct access to C++ objects. A higher
 level interface using Perl proxy classes can be built using these
 low-level accessors. This is described shortly.</p>
<h3><a name="Perl5_nn21">30.4.7 C++ classes and type-checking</a></h3>
<p> The SWIG type-checker is fully aware of C++ inheritance. Therefore,
 if you have classes like this</p>
<div class="code">
<pre>
class Foo {
...
};

class Bar : public Foo {
...
};
</pre>
</div>
<p> and a function</p>
<div class="code">
<pre>
void spam(Foo *f);
</pre>
</div>
<p> then the function <tt>spam()</tt> accepts <tt>Foo *</tt> or a
 pointer to any class derived from <tt>Foo</tt>. If necessary, the
 type-checker also adjusts the value of the pointer (as is necessary
 when multiple inheritance is used).</p>
<h3><a name="Perl5_nn22">30.4.8 C++ overloaded functions</a></h3>
<p> If you have a C++ program with overloaded functions or methods, you
 will need to disambiguate those methods using <tt>%rename</tt>. For
 example:</p>
<div class="code">
<pre>
/* Forward renaming declarations */
%rename(foo_i) foo(int); 
%rename(foo_d) foo(double);
...
void foo(int);           // Becomes 'foo_i'
void foo(char *c);       // Stays 'foo' (not renamed)

class Spam {
public:
  void foo(int);      // Becomes 'foo_i'
  void foo(double);   // Becomes 'foo_d'
  ...
};
</pre>
</div>
<p> Now, in Perl, the methods are accessed as follows:</p>
<div class="targetlang">
<pre>
use example;
example::foo_i(3);
$s = example::new_Spam();
example::Spam_foo_i($s, 3);
example::Spam_foo_d($s, 3.14);
</pre>
</div>
<p> Please refer to the &quot;SWIG Basics&quot; chapter for more information.</p>
<h3><a name="Perl5_nn23">30.4.9 Operators</a></h3>
<p> As of version 1.3.27 SWIG automatically renames the most common C++
 operators, and maps them into the perl module with the proper 'use
 overload ...' so you don't need to do any work.</p>
<p> The following C++ operators are currently supported by the Perl
 module:</p>
<ul>
<li>operator++</li>
<li>operator--</li>
<li>operator+</li>
<li>operator-</li>
<li>operator*</li>
<li>operator/</li>
<li>operator==</li>
<li>operator!=</li>
<li>operator%</li>
<li>operator&gt;</li>
<li>operator&lt;</li>
<li>operator and</li>
<li>operator or</li>
</ul>
<h3><a name="Perl5_nn24">30.4.10 Modules and packages</a></h3>
<p> When you create a SWIG extension, everything gets placed into a
 single Perl module. The name of the module is determined by the <tt>
%module</tt> directive. To use the module, do the following:</p>
<div class="targetlang">
<pre>
$ perl5
use example;                      # load the example module
print example::fact(4), &quot;\n&quot;      # Call a function in it
24
</pre>
</div>
<p> Usually, a module consists of a collection of code that is contained
 within a single file. A package, on the other hand, is the Perl
 equivalent of a namespace. A package is a lot like a module, except
 that it is independent of files. Any number of files may be part of the
 same package--or a package may be broken up into a collection of
 modules if you prefer to think about it in this way.</p>
<p> SWIG installs its functions into a package with the same name as the
 module.</p>
<p><b> Incompatible Change:</b> previous versions of SWIG enabled you to
 change the name of the package by using the -package option, this
 feature has been removed in order to properly support modules that used
 nested namespaces, e.g. Foo::Bar::Baz. To give your module a nested
 namespace simply provide the fully qualified name in your %module
 directive:</p>
<div class="code">
<pre>
%module &quot;Foo::Bar::Baz&quot;
</pre>
</div>
<p><b> NOTE:</b> the double quotes are necessary.</p>
<p> Using the <tt>package</tt> option of the <tt>%module</tt> directive
 allows you to specify what Perl namespace that the module will be
 living in when installed. This is useful in the situation where a
 module maintainer wants to split a large module into smaller pieces to
 make maintenance easier, but doesn't want to have that affect the
 module name used by applications. So for example, if I wanted to split <tt>
XML::Xerces</tt> into <tt>XML::Xerces::SAX</tt>, etc. , but I wanted all
 the applications to be able to access the classes using the <tt>
XML::Xerces</tt> namespace I could use:</p>
<div class="code">
<pre>
%module(package=&quot;XML::Xerces&quot;) &quot;XML::Xerces::SAX
</pre>
</div>
<p> And now all the applications could use the class <tt>
XML::Xerces::SAXParser</tt>. Without the <tt>package</tt> directive
 splitting the module would force applications to use the class <tt>
XML::Xerces::SAX::SAXParser</tt>. This could break compatibility for
 existing applications that are already using the class under the name <tt>
XML::Xerces::SAXParser</tt>.</p>

<!--
&lt;p&gt;
This can be changed by giving SWIG the -package
option:
&lt;/p&gt;

&lt;div class=&quot;code&quot;&gt;&lt;pre&gt;
$ swig -perl -package Foo example.i
&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;
In this case, you still create a module called `&lt;tt&gt;example&lt;/tt&gt;' exactly as before, but
all of the functions in that module will be installed into the package
`&lt;tt&gt;Foo&lt;/tt&gt;.' For example:
&lt;/p&gt;

&lt;div class=&quot;targetlang&quot;&gt;&lt;pre&gt;
use example;   # Load the module like before
print Foo::fact(4), &quot;\n&quot;;        # Call a function in package FooBar
&lt;/pre&gt;&lt;/div&gt;
-->
<h2><a name="Perl5_nn25">30.5 Input and output parameters</a></h2>
<p> A common problem in some C programs is handling parameters passed as
 simple pointers. For example:</p>
<div class="code">
<pre>
void add(int x, int y, int *result) {
  *result = x + y;
}
</pre>
</div>
<p> or perhaps</p>
<div class="code">
<pre>
int sub(int *x, int *y) {
  return *x+*y;
}
</pre>
</div>
<p> The easiest way to handle these situations is to use the <tt>
typemaps.i</tt> file. For example:</p>
<div class="code">
<pre>
%module example
%include &quot;typemaps.i&quot;

void add(int, int, int *OUTPUT);
int  sub(int *INPUT, int *INPUT);
</pre>
</div>
<p> In Perl, this allows you to pass simple values. For example:</p>
<div class="targetlang">
<pre>
$a = example::add(3, 4);
print &quot;$a\n&quot;;
7
$b = example::sub(7, 4);
print &quot;$b\n&quot;;
3
</pre>
</div>
<p> Notice how the <tt>INPUT</tt> parameters allow integer values to be
 passed instead of pointers and how the <tt>OUTPUT</tt> parameter
 creates a return result.</p>
<p> If you don't want to use the names <tt>INPUT</tt> or <tt>OUTPUT</tt>
, use the <tt>%apply</tt> directive. For example:</p>
<div class="code">
<pre>
%module example
%include &quot;typemaps.i&quot;

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

void add(int x, int y, int *result);
int  sub(int *x, int *y);
</pre>
</div>
<p> If a function mutates one of its parameters like this,</p>
<div class="code">
<pre>
void negate(int *x) {
  *x = -(*x);
}
</pre>
</div>
<p> you can use <tt>INOUT</tt> like this:</p>
<div class="code">
<pre>
%include &quot;typemaps.i&quot;
...
void negate(int *INOUT);
</pre>
</div>
<p> In Perl, a mutated parameter shows up as a return value. For
 example:</p>
<div class="targetlang">
<pre>
$a = example::negate(3);
print &quot;$a\n&quot;;
-3
</pre>
</div>
<p> The most common use of these special typemap rules is to handle
 functions that return more than one value. For example, sometimes a
 function returns a result as well as a special error code:</p>
<div class="code">
<pre>
/* send message, return number of bytes sent, along with success code */
int send_message(char *text, int len, int *success);
</pre>
</div>
<p> To wrap such a function, simply use the <tt>OUTPUT</tt> rule above.
 For example:</p>
<div class="code">
<pre>
%module example
%include &quot;typemaps.i&quot;
%apply int *OUTPUT { int *success };
...
int send_message(char *text, int *success);
</pre>
</div>
<p> When used in Perl, the function will return multiple values.</p>
<div class="targetlang">
<pre>
($bytes, $success) = example::send_message(&quot;Hello World&quot;);
</pre>
</div>
<p> Another common use of multiple return values are in query functions.
 For example:</p>
<div class="code">
<pre>
void get_dimensions(Matrix *m, int *rows, int *columns);
</pre>
</div>
<p> To wrap this, you might use the following:</p>
<div class="code">
<pre>
%module example
%include &quot;typemaps.i&quot;
%apply int *OUTPUT { int *rows, int *columns };
...
void get_dimensions(Matrix *m, int *rows, *columns);
</pre>
</div>
<p> Now, in Perl:</p>
<div class="targetlang">
<pre>
($r, $c) = example::get_dimensions($m);
</pre>
</div>
<p> In certain cases, it is possible to treat Perl references as C
 pointers. To do this, use the <tt>REFERENCE</tt> typemap. For example:</p>
<div class="code">
<pre>
%module example
%include &quot;typemaps.i&quot;

void add(int x, int y, int *REFERENCE);
</pre>
</div>
<p> In Perl:</p>
<div class="targetlang">
<pre>
use example;
$c = 0.0;
example::add(3, 4, \$c);
print &quot;$c\n&quot;;
7
</pre>
</div>
<p><b> Note:</b> The <tt>REFERENCE</tt> feature is only currently
 supported for numeric types (integers and floating point).</p>
<h2><a name="Perl5_nn26">30.6 Exception handling</a></h2>
<p> The SWIG <tt>%exception</tt> directive can be used to create a
 user-definable exception handler for converting exceptions in your
 C/C++ program into Perl exceptions. The chapter on customization
 features contains more details, but suppose you have a C++ class like
 the following:</p>
<div class="code">
<pre>
class RangeError {};   // Used for an exception

class DoubleArray {
  private:
    int n;
    double *ptr;
  public:
    // Create a new array of fixed size
    DoubleArray(int size) {
      ptr = new double[size];
      n = size;
    }
    // Destroy an array
    ~DoubleArray() {
      delete ptr;
    }
    // Return the length of the array
    int   length() {
      return n;
    }

    // Get an item from the array and perform bounds checking.
    double getitem(int i) {
      if ((i &gt;= 0) &amp;&amp; (i &lt; n))
        return ptr[i];
      else
        throw RangeError();
    }

    // Set an item in the array and perform bounds checking.
    void setitem(int i, double val) {
      if ((i &gt;= 0) &amp;&amp; (i &lt; n))
        ptr[i] = val;
      else
        throw RangeError();
    }
  };
</pre>
</div>
<p> Since several methods in this class can throw an exception for an
 out-of-bounds access, you might want to catch this in the Perl
 extension by writing the following in an interface file:</p>
<div class="code">
<pre>
%exception {
  try {
    $action
  }
  catch (RangeError) {
    croak(&quot;Array index out-of-bounds&quot;);
  }
}

class DoubleArray {
...
};
</pre>
</div>
<p> The exception handling code is inserted directly into generated
 wrapper functions. The <tt>$action</tt> variable is replaced with the
 C/C++ code being executed by the wrapper. When an exception handler is
 defined, errors can be caught and used to gracefully generate a Perl
 error instead of forcing the entire program to terminate with an
 uncaught error.</p>
<p> As shown, the exception handling code will be added to every wrapper
 function. Since this is somewhat inefficient. You might consider
 refining the exception handler to only apply to specific methods like
 this:</p>
<div class="code">
<pre>
%exception getitem {
  try {
    $action
  }
  catch (RangeError) {
    croak(&quot;Array index out-of-bounds&quot;);
  }
}

%exception setitem {
  try {
    $action
  }
  catch (RangeError) {
    croak(&quot;Array index out-of-bounds&quot;);
  }
}
</pre>
</div>
<p> In this case, the exception handler is only attached to methods and
 functions named <tt>getitem</tt> and <tt>setitem</tt>.</p>
<p> If you had a lot of different methods, you can avoid extra typing by
 using a macro. For example:</p>
<div class="code">
<pre>
%define RANGE_ERROR
{
  try {
    $action
  }
  catch (RangeError) {
    croak(&quot;Array index out-of-bounds&quot;);
  }
}
%enddef

%exception getitem RANGE_ERROR;
%exception setitem RANGE_ERROR;
</pre>
</div>
<p> Since SWIG's exception handling is user-definable, you are not
 limited to C++ exception handling. See the chapter on &quot;<a href="#Customization">
Customization features</a>&quot; for more examples.</p>
<p><b> Compatibility note:</b> In SWIG1.1, exceptions were defined using
 the older <tt>%except</tt> directive:</p>
<div class="code">
<pre>
%except(python) {
  try {
    $function
  }
  catch (RangeError) {
    croak(&quot;Array index out-of-bounds&quot;);
  }
}
</pre>
</div>
<p> This is still supported, but it is deprecated. The newer <tt>
%exception</tt> directive provides the same functionality, but it has
 additional capabilities that make it more powerful.</p>
<h2><a name="Perl5_nn27">30.7 Remapping datatypes with typemaps</a></h2>
<p> This section describes how you can modify SWIG's default wrapping
 behavior for various C/C++ datatypes using the <tt>%typemap</tt>
 directive. This is an advanced topic that assumes familiarity with the
 Perl C API as well as the material in the &quot;<a href="#Typemaps">Typemaps</a>
&quot; chapter.</p>
<p> Before proceeding, it should be stressed that typemaps are<em> not</em>
 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 primitive C-Perl interface.</p>
<h3><a name="Perl5_nn28">30.7.1 A simple typemap example</a></h3>
<p> A typemap is nothing more than a code generation rule that is
 attached to a specific C datatype. For example, to convert integers
 from Perl to C, you might define a typemap like this:</p>
<div class="code">
<pre>
%module example

%typemap(in) int {
  $1 = (int) SvIV($input);
  printf(&quot;Received an integer : %d\n&quot;, $1);
}
...
%inline %{
extern int fact(int n);
%}

</pre>
</div>
<p> Typemaps are always associated with some specific aspect of code
 generation. In this case, the &quot;in&quot; 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 variable prefaced by a
 <tt>$</tt> are used. The <tt>$1</tt> variable is placeholder for a
 local variable of type <tt>int</tt>. The <tt>$input</tt> variable is
 the input object (usually a <tt>SV *</tt>).</p>
<p> When this example is used in Perl5, it will operate as follows:</p>
<div class="targetlang">
<pre>
use example;
$n = example::fact(6);
print &quot;$n\n&quot;;
...

Output:
Received an integer : 6
720
</pre>
</div>
<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 type-system. When you define a typemap for <tt>
int</tt>, that typemap applies to <tt>int</tt> and qualified variations
 such as <tt>const int</tt>. In addition, the typemap system follows <tt>
typedef</tt> declarations. For example:</p>
<div class="targetlang">
<pre>
%typemap(in) int n {
  $1 = (int) SvIV($input);
  printf(&quot;n = %d\n&quot;, $1);
}
%inline %{
typedef int Integer;
extern int fact(Integer n);    // Above typemap is applied
%}
</pre>
</div>
<p> It should be noted that the matching of <tt>typedef</tt> only occurs
 in one direction. If you defined a typemap for <tt>Integer</tt>, it is
 not applied to arguments of type <tt>int</tt>.</p>
<p> Typemaps can also be defined for groups of consecutive arguments.
 For example:</p>
<div class="targetlang">
<pre>
%typemap(in) (char *str, unsigned len) {
    $1 = SvPV($input, $2);
};

int count(char c, char *str, unsigned len);
</pre>
</div>
<p> When a multi-argument typemap is defined, the arguments are always
 handled as a single Perl object. This allows the function to be used
 like this (notice how the length parameter is omitted):</p>
<div class="targetlang">
<pre>
example::count(&quot;e&quot;, &quot;Hello World&quot;);
1
&gt;&gt;&gt;
</pre>
</div>
<h3><a name="Perl5_nn29">30.7.2 Perl5 typemaps</a></h3>
<p> The previous section illustrated an &quot;in&quot; typemap for converting Perl
 objects to C. A variety of different typemap methods are defined by the
 Perl module. For example, to convert a C integer back into a Perl
 object, you might define an &quot;out&quot; typemap like this:</p>
<div class="targetlang">
<pre>
%typemap(out) int {
  $result = sv_newmortal();
  sv_setiv($result, (IV) $1);
  argvi++;
}
</pre>
</div>
<p> The following typemap methods are available:</p>
<p> <tt>%typemap(in)</tt></p>
<div class="indent"> Converts Perl5 object to input function arguments.</div>
<p> <tt>%typemap(out)</tt></p>
<div class="indent"> Converts function return value to a Perl5 value.</div>
<p> <tt>%typemap(varin)</tt></p>
<div class="indent"> Converts a Perl5 object to a global variable.</div>
<p> <tt>%typemap(varout)</tt></p>
<div class="indent"> Converts a global variable to a Perl5 object.</div>
<p> <tt>%typemap(freearg)</tt></p>
<div class="indent"> Cleans up a function argument after a function call</div>
<p> <tt>%typemap(argout)</tt></p>
<div class="indent"> Output argument handling</div>
<p> <tt>%typemap(ret)</tt></p>
<div class="indent"> Clean up return value from a function.</div>
<p> <tt>%typemap(memberin)</tt></p>
<div class="indent"> Setting of C++ member data (all languages).</div>
<p> <tt>%typemap(memberout)</tt></p>
<div class="indent"> Return of C++ member data (all languages).</div>
<p> <tt>%typemap(check)</tt></p>
<div class="indent"> Check value of input parameter.</div>
<h3><a name="Perl5_nn30">30.7.3 Typemap variables</a></h3>
<p> Within typemap code, a number of special variables prefaced with a <tt>
$</tt> may appear. A full list of variables can be found in the &quot;<a href="#Typemaps">
Typemaps</a>&quot; chapter. This is a list of the most common variables:</p>
<p> <tt>$1</tt></p>
<div class="indent"> A C local variable corresponding to the actual type
 specified in the <tt>%typemap</tt> directive. For input values, this is
 a C local variable that's supposed to hold an argument value. For
 output values, this is the raw result that's supposed to be returned to
 Perl.</div>
<p> <tt>$input</tt></p>
<div class="indent"> A Perl object holding the value of an argument of
 variable value.</div>
<p> <tt>$result</tt></p>
<div class="indent"> A Perl object that holds the result to be returned
 to Perl.</div>
<p> <tt>$1_name</tt></p>
<div class="indent"> The parameter name that was matched.</div>
<p> <tt>$1_type</tt></p>
<div class="indent"> The actual C datatype matched by the typemap.</div>
<p> <tt>$1_ltype</tt></p>
<div class="indent"> An assignable version of the datatype matched by
 the typemap (a type that can appear on the left-hand-side of a C
 assignment operation). This type is stripped of qualifiers and may be
 an altered version of <tt>$1_type</tt>. All arguments and local
 variables in wrapper functions are declared using this type so that
 their values can be properly assigned.</div>
<p> <tt>$symname</tt></p>
<div class="indent"> The Perl name of the wrapper function being
 created.</div>
<h3><a name="Perl5_nn31">30.7.4 Useful functions</a></h3>
<p> When writing typemaps, it is necessary to work directly with Perl5
 objects. This, unfortunately, can be a daunting task. Consult the
 &quot;perlguts&quot; man-page for all of the really ugly details. A short summary
 of commonly used functions is provided here for reference. It should be
 stressed that SWIG can be used quite effectively without knowing any of
 these details--especially now that there are typemap libraries that can
 already been written.</p>
<p><b> Perl Integer Functions</b></p>
<div class="code">
<pre>
int   SvIV(SV *);
void  sv_setiv(SV *sv, IV value);
SV   *newSViv(IV value);
int   SvIOK(SV *);
</pre>
</div>
<p><b> Perl Floating Point Functions</b></p>
<div class="code">
<pre>
double SvNV(SV *);
void   sv_setnv(SV *, double value);
SV    *newSVnv(double value);
int    SvNOK(SV *);
</pre>
</div>
<p><b> Perl String Functions</b></p>
<div class="code">
<pre>
char     *SvPV(SV *, STRLEN len);
void      sv_setpv(SV *, char *val);
void      sv_setpvn(SV *, char *val, STRLEN len);
SV       *newSVpv(char *value, STRLEN len);
int       SvPOK(SV *);
void      sv_catpv(SV *, char *);
void      sv_catpvn(SV *, char *, STRLEN);
</pre>
</div>
<p><b> Perl References</b></p>
<div class="code">
<pre>
void      sv_setref_pv(SV *, char *, void *ptr);
int       sv_isobject(SV *);
SV       *SvRV(SV *);
int       sv_isa(SV *, char *0;
</pre>
</div>
<h2><a name="Perl5_nn32">30.8 Typemap Examples</a></h2>
<p> This section includes a few examples of typemaps. For more examples,
 you might look at the files &quot;<tt>perl5.swg</tt>&quot; and &quot;<tt>typemaps.i</tt>
&quot; in the SWIG library.</p>
<h3><a name="Perl5_nn33">30.8.1 Converting a Perl5 array to a char **</a>
</h3>
<p> A common problem in many C programs is the processing of command
 line arguments, which are usually passed in an array of NULL terminated
 strings. The following SWIG interface file allows a Perl5 array
 reference to be used as a char ** datatype.</p>
<div class="code">
<pre>
%module argv

// This tells SWIG to treat char ** as a special case
%typemap(in) char ** {
  AV *tempav;
  I32 len;
  int i;
  SV  **tv;
  if (!SvROK($input))
    croak(&quot;Argument $argnum is not a reference.&quot;);
  if (SvTYPE(SvRV($input)) != SVt_PVAV)
    croak(&quot;Argument $argnum is not an array.&quot;);
  tempav = (AV*)SvRV($input);
  len = av_len(tempav);
  $1 = (char **) malloc((len+2)*sizeof(char *));
  for (i = 0; i &lt;= len; i++) {
    tv = av_fetch(tempav, i, 0);
    $1[i] = (char *) SvPV(*tv, PL_na);
  }
  $1[i] = NULL;
};

// This cleans up the char ** array after the function call
%typemap(freearg) char ** {
  free($1);
}

// Creates a new Perl array and places a NULL-terminated char ** into it
%typemap(out) char ** {
  AV *myav;
  SV **svs;
  int i = 0, len = 0;
  /* Figure out how many elements we have */
  while ($1[len])
    len++;
  svs = (SV **) malloc(len*sizeof(SV *));
  for (i = 0; i &lt; len ; i++) {
    svs[i] = sv_newmortal();
    sv_setpv((SV*)svs[i], $1[i]);
  };
  myav = av_make(len, svs);
  free(svs);
  $result = newRV_noinc((SV*)myav);
  sv_2mortal($result);
  argvi++;
}

// Now a few test functions
%inline %{
  int print_args(char **argv) {
    int i = 0;
    while (argv[i]) {
      printf(&quot;argv[%d] = %s\n&quot;, i, argv[i]);
      i++;
    }
    return i;
  }

  // Returns a char ** list
  char **get_args() {
    static char *values[] = { &quot;Dave&quot;, &quot;Mike&quot;, &quot;Susan&quot;, &quot;John&quot;, &quot;Michelle&quot;, 0};
    return &amp;values[0];
  }
%}

</pre>
</div>
<p> When this module is compiled, the wrapped C functions can be used in
 a Perl script as follows:</p>
<div class="targetlang">
<pre>
use argv;
@a = (&quot;Dave&quot;, &quot;Mike&quot;, &quot;John&quot;, &quot;Mary&quot;);           # Create an array of strings
argv::print_args(\@a);                           # Pass it to our C function
$b = argv::get_args();                           # Get array of strings from C
print @$b, &quot;\n&quot;;                                 # Print it out
</pre>
</div>
<h3><a name="Perl5_nn34">30.8.2 Return values</a></h3>
<p> Return values are placed on the argument stack of each wrapper
 function. The current value of the argument stack pointer is contained
 in a variable <tt>argvi</tt>. Whenever a new output value is added, it
 is critical that this value be incremented. For multiple output values,
 the final value of <tt>argvi</tt> should be the total number of output
 values.</p>
<p> The total number of return values should not exceed the number of
 input values unless you explicitly extend the argument stack. This can
 be done using the <tt>EXTEND()</tt> macro as in:</p>
<div class="code">
<pre>
%typemap(argout) int *OUTPUT {
  if (argvi &gt;= items) {
    EXTEND(sp, 1);              /* Extend the stack by 1 object */
  }
  $result = sv_newmortal();
  sv_setiv($target, (IV) *($1));
  argvi++;
}
</pre>
</div>
<h3><a name="Perl5_nn35">30.8.3 Returning values from arguments</a></h3>
<p> Sometimes it is desirable for a function to return a value in one of
 its arguments. This example describes the implementation of the <tt>
OUTPUT</tt> typemap.</p>
<div class="code">
<pre>
%module return

// This tells SWIG to treat an double * argument with name 'OutDouble' as
// an output value.  

%typemap(argout) double *OUTPUT {
  $result = sv_newmortal();
  sv_setnv($result, *$input);
  argvi++;                     /* Increment return count -- important! */
}

// We don't care what the input value is. Ignore, but set to a temporary variable

%typemap(in, numinputs=0) double *OUTPUT(double junk) {
  $1 = &amp;junk;
}

// Now a function to test it
%{
/* Returns the first two input arguments */
int multout(double a, double b, double *out1, double *out2) {
  *out1 = a;
  *out2 = b;
  return 0;
};
%}

// If we name both parameters OutDouble both will be output

int multout(double a, double b, double *OUTPUT, double *OUTPUT);
...
</pre>
</div>
<p> When this function is called, the output arguments are appended to
 the stack used to return results. This shows up an array in Perl. For
 example:</p>
<div class="targetlang">
<pre>
@r = multout(7, 13);
print &quot;multout(7, 13) = @r\n&quot;;
($x, $y) = multout(7, 13);
</pre>
</div>
<h3><a name="Perl5_nn36">30.8.4 Accessing array structure members</a></h3>
<p> Consider the following data structure:</p>
<div class="code">
<pre>
#define SIZE  8
typedef struct {
  int   values[SIZE];
  ...
} Foo;

</pre>
</div>
<p> By default, SWIG doesn't know how to the handle the values structure
 member it's an array, not a pointer. In this case, SWIG makes the array
 member read-only. Reading will simply return a pointer to the first
 item in the array. To make the member writable, a &quot;memberin&quot; typemap
 can be used.</p>
<div class="code">
<pre>
%typemap(memberin) int [SIZE] {
  int i;
  for (i = 0; i &lt; SIZE; i++) {
    $1[i] = $input[i];
  }
}

</pre>
</div>
<p> Whenever a <tt>int [SIZE]</tt> member is encountered in a structure
 or class, this typemap provides a safe mechanism for setting its value.</p>
<p> As in the previous example, the typemap can be generalized for any
 dimension. For example:</p>
<div class="code">
<pre>
%typemap(memberin) int [ANY] {
  int i;
  for (i = 0; i &lt; $1_dim0; i++) {
    $1[i] = $input[i];
  }
}
</pre>
</div>
<p> When setting structure members, the input object is always assumed
 to be a C array of values that have already been converted from the
 target language. Because of this, the <tt>memberin</tt> typemap is
 almost always combined with the use of an &quot;in&quot; typemap. For example,
 the &quot;in&quot; typemap in the previous section would be used to convert an <tt>
int[]</tt> array to C whereas the &quot;memberin&quot; typemap would be used to
 copy the converted array into a C data structure.</p>
<h3><a name="Perl5_nn37">30.8.5 Turning Perl references into C pointers</a>
</h3>
<p> A frequent confusion on the SWIG mailing list is errors caused by
 the mixing of Perl references and C pointers. For example, suppose you
 have a C function that modifies its arguments like this:</p>
<div class="code">
<pre>
void add(double a, double b, double *c) {
  *c = a + b;
}
</pre>
</div>
<p> A common misinterpretation of this function is the following Perl
 script:</p>
<div class="targetlang">
<pre>
# Perl script
$a = 3.5;
$b = 7.5;
$c = 0.0;          # Output value
add($a, $b, \$c);    # Place result in c (Except that it doesn't work)
</pre>
</div>
<p> To make this work with a reference, you can use a typemap such as
 this:</p>
<div class="code">
<pre>
%typemap(in) double * (double dvalue) {
  SV* tempsv;
  if (!SvROK($input)) {
    croak(&quot;expected a reference\n&quot;);
  }
  tempsv = SvRV($input);
  if ((!SvNOK(tempsv)) &amp;&amp; (!SvIOK(tempsv))) {
    croak(&quot;expected a double reference\n&quot;);
  }
  dvalue = SvNV(tempsv);
  $1 = &amp;dvalue;
}

%typemap(argout) double * {
  SV *tempsv;
  tempsv = SvRV($input);
  sv_setnv(tempsv, *$1);
}
</pre>
</div>
<p> Now, if you place this before the add function, you can do this:</p>
<div class="targetlang">
<pre>
$a = 3.5;
$b = 7.5;
$c = 0.0;
add($a, $b, \$c);            # Now it works!
print &quot;$c\n&quot;;

</pre>
</div>
<h3><a name="Perl5_nn38">30.8.6 Pointer handling</a></h3>
<p> Occasionally, it might be necessary to convert pointer values that
 have been stored using the SWIG typed-pointer representation. To
 convert a pointer from Perl to C, the following function is used:</p>
<p> <tt>int SWIG_ConvertPtr(SV *obj, void **ptr, swig_type_info *ty, int
 flags)</tt></p>
<div class="indent"> Converts a Perl object <tt>obj</tt> to a C pointer.
 The result of the conversion is placed into the pointer located at <tt>
ptr</tt>. <tt>ty</tt> is a SWIG type descriptor structure. <tt>flags</tt>
 is used to handle error checking and other aspects of conversion. <tt>
flags</tt> is currently undefined and reserved for future expansion.
 Returns 0 on success and -1 on error.</div>
<p> <tt>void *SWIG_MakePtr(SV *obj, void *ptr, swig_type_info *ty, int
 flags)</tt></p>
<div class="indent"> Creates a new Perl pointer object. <tt>obj</tt> is
 a Perl SV that has been initialized to hold the result, <tt>ptr</tt> is
 the pointer to convert, <tt>ty</tt> is the SWIG type descriptor
 structure that describes the type, and <tt>flags</tt> is a flag that
 controls properties of the conversion. <tt>flags</tt> is currently
 undefined and reserved.</div>
<p> Both of these functions require the use of a special SWIG
 type-descriptor structure. This structure contains information about
 the mangled name of the datatype, type-equivalence information, as well
 as information about converting pointer values under C++ inheritance.
 For a type of <tt>Foo *</tt>, the type descriptor structure is usually
 accessed as follows:</p>
<div class="code">
<pre>
Foo *f;
if (!SWIG_IsOK(SWIG_ConvertPtr($input, (void **) &amp;f, SWIGTYPE_p_Foo, 0))) {
  SWIG_exception_fail(SWIG_TypeError, &quot;in method '$symname', expecting type Foo&quot;);
}

SV *sv = sv_newmortal();
SWIG_MakePtr(sv, f, SWIGTYPE_p_Foo, 0);
</pre>
</div>
<p> In a typemap, the type descriptor should always be accessed using
 the special typemap variable <tt>$1_descriptor</tt>. For example:</p>
<div class="code">
<pre>
%typemap(in) Foo * {
  if (!SWIG_IsOK(SWIG_ConvertPtr($input, (void **) &amp;$1, $1_descriptor, 0))) {
    SWIG_exception_fail(SWIG_TypeError, &quot;in method '$symname', expecting type Foo&quot;);
  }
}
</pre>
</div>
<p> If necessary, the descriptor for any type can be obtained using the <tt>
$descriptor()</tt> macro in a typemap. For example:</p>
<div class="code">
<pre>
%typemap(in) Foo * {
  if (!SWIG_IsOK(SWIG_ConvertPtr($input, (void **) &amp;$1, $descriptor(Foo *), 0))) {
    SWIG_exception_fail(SWIG_TypeError, &quot;in method '$symname', expecting type Foo&quot;);
  }
}
</pre>
</div>
<h2><a name="Perl5_nn39">30.9 Proxy classes</a></h2>
<p><b> Out of date. Needs update.</b></p>
<p> Using the low-level procedural interface, SWIG can also construct a
 high-level object oriented interface to C structures and C++ classes.
 This is done by constructing a Perl proxy class (also known as a shadow
 class) that provides an OO wrapper to the underlying code. This section
 describes the implementation details of the proxy interface.</p>
<h3><a name="Perl5_nn40">30.9.1 Preliminaries</a></h3>
<p> Proxy classes, are generated by default. If you want to turn them
 off, use the <tt>-noproxy</tt> command line option. For example:</p>
<div class="code">
<pre>
$ swig -c++ -perl -noproxy example.i
</pre>
</div>
<p> When proxy classes are used, SWIG moves all of the low-level
 procedural wrappers to another package name. By default, this package
 is named 'modulec' where 'module' is the name of the module you
 provided with the <tt>%module</tt> directive. Then, in place of the
 original module, SWIG creates a collection of high-level Perl wrappers.
 In your scripts, you will use these high level wrappers. The wrappers,
 in turn, interact with the low-level procedural module.</p>
<h3><a name="Perl5_nn41">30.9.2 Structure and class wrappers</a></h3>
<p> Suppose you have the following SWIG interface file:</p>
<div class="code">
<pre>
%module example
struct Vector {
  Vector(double x, double y, double z);
  ~Vector();
  double x, y, z;
};

</pre>
</div>
<p> When wrapped, SWIG creates the following set of low-level accessor
 functions as described in previous sections.</p>
<div class="code">
<pre>
Vector *new_Vector(double x, double y, double z);
void    delete_Vector(Vector *v);
double  Vector_x_get(Vector *v);
double  Vector_x_set(Vector *v, double value);
double  Vector_y_get(Vector *v);
double  Vector_y_set(Vector *v, double value);
double  Vector_z_get(Vector *v);
double  Vector_z_set(Vector *v, double value);

</pre>
</div>
<p> However, when proxy classes are enabled, these accessor functions
 are wrapped inside a Perl class like this:</p>
<div class="targetlang">
<pre>
package example::Vector;
@ISA = qw( example );
%OWNER = ();
%BLESSEDMEMBERS = ();

sub new () {
  my $self = shift;
  my @args = @_;
  $self = vectorc::new_Vector(@args);
  return undef if (!defined($self));
  bless $self, &quot;example::Vector&quot;;
  $OWNER{$self} = 1;
  my %retval;
  tie %retval, &quot;example::Vector&quot;, $self;
  return bless \%retval, &quot;Vector&quot;;
}

sub DESTROY {
  return unless $_[0]-&gt;isa('HASH');
  my $self = tied(%{$_[0]});
  delete $ITERATORS{$self};
  if (exists $OWNER{$self}) {
    examplec::delete_Vector($self));
    delete $OWNER{$self};
  }
}

sub FETCH {
  my ($self, $field) = @_;
  my $member_func = &quot;vectorc::Vector_${field}_get&quot;;
  my $val = &amp;$member_func($self);
  if (exists $BLESSEDMEMBERS{$field}) {
    return undef if (!defined($val));
    my %retval;
    tie %retval, $BLESSEDMEMBERS{$field}, $val;
    return bless \%retval, $BLESSEDMEMBERS{$field};
  }
  return $val;
}

sub STORE {
  my ($self, $field, $newval) = @_;
  my $member_func = &quot;vectorc::Vector_${field}_set&quot;;
  if (exists $BLESSEDMEMBERS{$field}) {
    &amp;$member_func($self, tied(%{$newval}));
  } else {
    &amp;$member_func($self, $newval);
  }
}
</pre>
</div>
<p> Each structure or class is mapped into a Perl package of the same
 name. The C++ constructors and destructors are mapped into constructors
 and destructors for the package and are always named &quot;new&quot; and
 &quot;DESTROY&quot;. The constructor always returns a tied hash table. This hash
 table is used to access the member variables of a structure in addition
 to being able to invoke member functions. The <tt>%OWNER</tt> and <tt>
%BLESSEDMEMBERS</tt> hash tables are used internally and described
 shortly.</p>
<p> To use our new proxy class we can simply do the following:</p>
<div class="targetlang">
<pre>
# Perl code using Vector class
$v = new Vector(2, 3, 4);
$w = Vector-&gt;new(-1, -2, -3);

# Assignment of a single member
$v-&gt;{x} = 7.5;

# Assignment of all members
%$v = ( x=&gt;3,
        y=&gt;9,
        z=&gt;-2);

# Reading members
$x = $v-&gt;{x};

# Destruction
$v-&gt;DESTROY();

</pre>
</div>
<h3><a name="Perl5_nn42">30.9.3 Object Ownership</a></h3>
<p> In order for proxy classes to work properly, it is necessary for
 Perl to manage some mechanism of object ownership. Here's the crux of
 the problem---suppose you had a function like this:</p>
<div class="code">
<pre>
Vector *Vector_get(Vector *v, int index) {
  return &amp;v[i];
}
</pre>
</div>
<p> This function takes a Vector pointer and returns a pointer to
 another Vector. Such a function might be used to manage arrays or lists
 of vectors (in C). Now contrast this function with the constructor for
 a Vector object:</p>
<div class="code">
<pre>
Vector *new_Vector(double x, double y, double z) {
  Vector *v;
  v = new Vector(x, y, z);        // Call C++ constructor
  return v;
}
</pre>
</div>
<p> Both functions return a Vector, but the constructor is returning a
 brand-new Vector while the other function is returning a Vector that
 was already created (hopefully). In Perl, both vectors will be
 indistinguishable---clearly a problem considering that we would
 probably like the newly created Vector to be destroyed when we are done
 with it.</p>
<p> To manage these problems, each class contains two methods that
 access an internal hash table called <tt>%OWNER</tt>. This hash keeps a
 list of all of the objects that Perl knows that it has created. This
 happens in two cases: (1) when the constructor has been called, and (2)
 when a function implicitly creates a new object (as is done when SWIG
 needs to return a complex datatype by value). When the destructor is
 invoked, the Perl proxy class module checks the <tt>%OWNER</tt> hash to
 see if Perl created the object. If so, the C/C++ destructor is invoked.
 If not, we simply destroy the Perl object and leave the underlying C
 object alone (under the assumption that someone else must have created
 it).</p>
<p> This scheme works remarkably well in practice but it isn't
 foolproof. In fact, it will fail if you create a new C object in Perl,
 pass it on to a C function that remembers the object, and then destroy
 the corresponding Perl object (this situation turns out to come up
 frequently when constructing objects like linked lists and trees). When
 C takes possession of an object, you can change Perl's ownership by
 simply deleting the object from the <tt>%OWNER</tt> hash. This is done
 using the <tt>DISOWN</tt> method.</p>
<div class="targetlang">
<pre>
# Perl code to change ownership of an object
$v = new Vector(x, y, z);
$v-&gt;DISOWN();     
</pre>
</div>
<p> To acquire ownership of an object, the <tt>ACQUIRE</tt> method can
 be used.</p>
<div class="targetlang">
<pre>
# Given Perl ownership of a file
$u = Vector_get($v);
$u-&gt;ACQUIRE();

</pre>
</div>
<p> As always, a little care is in order. SWIG does not provide
 reference counting, garbage collection, or advanced features one might
 find in sophisticated languages.</p>
<h3><a name="Perl5_nn43">30.9.4 Nested Objects</a></h3>
<p> Suppose that we have a new object that looks like this:</p>
<div class="code">
<pre>
struct Particle {
  Vector r;
  Vector v;
  Vector f;
  int type;
}

</pre>
</div>
<p> In this case, the members of the structure are complex objects that
 have already been encapsulated in a Perl proxy class. To handle these
 correctly, we use the <tt>%BLESSEDMEMBERS</tt> hash which would look
 like this (along with some supporting code):</p>
<div class="targetlang">
<pre>
package Particle;
...
%BLESSEDMEMBERS = (
        r =&gt; `Vector',
        v =&gt; `Vector',
        f =&gt; `Vector',
);

</pre>
</div>
<p> When fetching members from the structure, <tt>%BLESSEDMEMBERS</tt>
 is checked. If the requested field is present, we create a tied-hash
 table and return it. If not, we just return the corresponding member
 unmodified.</p>
<p> This implementation allows us to operate on nested structures as
 follows:</p>
<div class="targetlang">
<pre>
# Perl access of nested structure
$p = new Particle();
$p-&gt;{f}-&gt;{x} = 0.0;
%${$p-&gt;{v}} = ( x=&gt;0, y=&gt;0, z=&gt;0);         
</pre>
</div>
<h3><a name="Perl5_nn44">30.9.5 Proxy Functions</a></h3>
<p> When functions take arguments involving a complex object, it is
 sometimes necessary to write a proxy function. For example:</p>
<div class="code">
<pre>
double dot_product(Vector *v1, Vector *v2);
</pre>
</div>
<p> Since Vector is an object already wrapped into a proxy class, we
 need to modify this function to accept arguments that are given in the
 form of tied hash tables. This is done by creating a Perl function like
 this:</p>
<div class="targetlang">
<pre>
sub dot_product {
  my @args = @_;
  $args[0] = tied(%{$args[0]});         # Get the real pointer values
  $args[1] = tied(%{$args[1]});
  my $result = vectorc::dot_product(@args);
  return $result;
}
</pre>
</div>
<p> This function replaces the original function, but operates in an
 identical manner.</p>
<h3><a name="Perl5_nn45">30.9.6 Inheritance</a></h3>
<p> Simple C++ inheritance is handled using the Perl <tt>@ISA</tt> array
 in each class package. For example, if you have the following interface
 file:</p>
<div class="code">
<pre>
// shapes.i
// SWIG interface file for shapes class
%module shapes
%{
#include &quot;shapes.h&quot;
%}

class Shape {
public:
  virtual double area() = 0;
  virtual double perimeter() = 0;
  void    set_location(double x, double y);
};
class Circle : public Shape {
public:
  Circle(double radius);
  ~Circle();
  double area();
  double perimeter();
};
class Square : public Shape {
public:
  Square(double size);
  ~Square();
  double area();
  double perimeter();
}

</pre>
</div>
<p> The resulting, Perl wrapper class will create the following code:</p>
<div class="targetlang">
<pre>
Package Shape;
@ISA = (shapes);
...
Package Circle;
@ISA = (shapes Shape);
...
Package Square;
@ISA = (shapes Shape);

</pre>
</div>
<p> The <tt>@ISA</tt> array determines where to look for methods of a
 particular class. In this case, both the <tt>Circle</tt> and <tt>Square</tt>
 classes inherit functions from <tt>Shape</tt> so we'll want to look in
 the <tt>Shape</tt> base class for them. All classes also inherit from
 the top-level module <tt>shapes</tt>. This is because certain common
 operations needed to implement proxy classes are implemented only once
 and reused in the wrapper code for various classes and structures.</p>
<p> Since SWIG proxy classes are implemented in Perl, it is easy to
 subclass from any SWIG generated class. To do this, simply put the name
 of a SWIG class in the <tt>@ISA</tt> array for your new class. However,
 be forewarned that this is not a trivial problem. In particular,
 inheritance of data members is extremely tricky (and I'm not even sure
 if it really works).</p>
<h3><a name="Perl5_nn46">30.9.7 Modifying the proxy methods</a></h3>
<p> It is possible to override the SWIG generated proxy/shadow methods,
 using <tt>%feature(&quot;shadow&quot;)</tt>. It works like all the other <a href="#Customization_features">
%feature directives</a>. Here is a simple example showing how to add
 some Perl debug code to the constructor:</p>
<div class="targetlang">
<pre>
/* Let's make the constructor of the class Square more verbose */
%feature(&quot;shadow&quot;) Square(double w)
%{
  sub new {
    my $pkg = shift;
    my $self = examplec::new_Square(@_);
    print STDERR &quot;Constructed an @{[ref($self)]}\n&quot;;
    bless $self, $pkg if defined($self);
  }
%}

class Square {
public:
  Square(double w);
  ...
};
</pre>
</div>
<h2><a name="Perl5_nn47">30.10 Adding additional Perl code</a></h2>
<p> If writing support code in C isn't enough, it is also possible to
 write code in Perl. This code gets inserted in to the <tt>.pm</tt> file
 created by SWIG. One use of Perl code might be to supply a high-level
 interface to certain functions. For example:</p>
<div class="code">
<pre>
void set_transform(Image *im, double x[4][4]);

...
/* Rewrite the high level interface to set_transform */
%perlcode %{
sub set_transform
{
  my ($im, $x) = @_;
  my $a = new_mat44();
  for (my $i = 0; $i &lt; 4, $i++)
  {
    for (my $j = 0; $j &lt; 4, $j++)
    {
      mat44_set($a, $i, $j, $x-&gt;[i][j])
    }
  }
  example.set_transform($im, $a);
  free_mat44($a);
}
%}
</pre>
</div>
<p> In this example, <tt>set_transform()</tt> provides a high-level Perl
 interface built on top of low-level helper functions. For example, this
 code now seems to work:</p>
<div class="targetlang">
<pre>
my $a =
  [[1, 0, 0, 0],
  [0, 1, 0, 0],
  [0, 0, 1, 0],
  [0, 0, 0, 1]];
set_transform($im, $a);
</pre>
</div>
<h2><a name="Perl5_directors">30.11 Cross language polymorphism</a></h2>
<p> Proxy classes provide a more natural, object-oriented way to access
 extension classes. As described above, each proxy instance has an
 associated C++ instance, and method calls to the proxy are passed to
 the C++ instance transparently via C wrapper functions.</p>
<p> This arrangement is asymmetric in the sense that no corresponding
 mechanism exists to pass method calls down the inheritance chain from
 C++ to Perl. In particular, if a C++ class has been extended in Perl
 (by extending the proxy class), these extensions will not be visible
 from C++ code. Virtual method calls from C++ are thus not able access
 the lowest implementation in the inheritance chain.</p>
<p> Changes have been made to SWIG to 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 Perl implementations lower in the
 inheritance chain. The upshot is that C++ classes can be extended in
 Perl and from C++ these extensions look exactly like native C++
 classes. Neither C++ code nor Perl code needs to know where a
 particular method is implemented: the combination of proxy classes,
 director classes, and C wrapper functions takes care of all the
 cross-language method routing transparently.</p>
<h3><a name="Perl5_nn48">30.11.1 Enabling directors</a></h3>
<p> The director feature is disabled by default. To use directors you
 must make two changes to the interface file. First, add the &quot;directors&quot;
 option to the %module directive, like this:</p>
<div class="code">
<pre>
%module(directors=&quot;1&quot;) modulename
</pre>
</div>
<p> Without this option no director code will be generated. Second, you
 must use the %feature(&quot;director&quot;) directive to tell SWIG which classes
 and methods should get directors. The %feature directive can be applied
 globally, to specific classes, and to specific methods, like this:</p>
<div class="code">
<pre>
// generate directors for all classes that have virtual methods
%feature(&quot;director&quot;);         

// generate directors for the virtual methods in class Foo
%feature(&quot;director&quot;) Foo;      
</pre>
</div>
<p> You can use the %feature(&quot;nodirector&quot;) directive to turn off
 directors for specific classes or methods. So for example,</p>
<div class="code">
<pre>
%feature(&quot;director&quot;) Foo;
%feature(&quot;nodirector&quot;) Foo::bar;
</pre>
</div>
<p> will generate directors for the virtual methods of class Foo except
 bar().</p>
<p> Directors can also be generated implicitly through inheritance. In
 the following, class Bar will get a director class that handles the
 methods one() and two() (but not three()):</p>
<div class="code">
<pre>
%feature(&quot;director&quot;) Foo;
class Foo {
public:
  Foo(int foo);
  virtual void one();
  virtual void two();
};

class Bar: public Foo {
public:
  virtual void three();
};
</pre>
</div>
<p> then at the Perl side you can define</p>
<div class="targetlang">
<pre>
use mymodule;

package MyFoo;
use base 'mymodule::Foo';

sub one {
  print &quot;one from Perl\n&quot;;
}
</pre>
</div>
<h3><a name="Perl5_nn49">30.11.2 Director classes</a></h3>
<p> For each class that has directors enabled, SWIG generates a new
 class that derives from both the class in question and a special <tt>
Swig::Director</tt> class. These new classes, referred to as director
 classes, can be loosely thought of as the C++ equivalent of the Perl
 proxy classes. The director classes store a pointer to their underlying
 Perl object and handle various issues related to object ownership.</p>
<p> For simplicity let's ignore the <tt>Swig::Director</tt> class and
 refer to the original C++ class as the director's base class. By
 default, a director class extends all virtual methods in the
 inheritance chain of its base class (see the preceding section for how
 to modify this behavior). Virtual methods that have a final specifier
 are unsurprisingly excluded. Thus the virtual method calls, whether
 they originate in C++ or in Perl 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 &quot;appropriate place&quot; we mean the method that would
 have been called if the C++ base class and its extensions in Perl were
 seamlessly integrated. That seamless integration is exactly what the
 director classes provide, transparently skipping over all the messy
 extension API glue that binds the two languages together.</p>
<p> In reality, the &quot;appropriate place&quot; is one of only two
 possibilities: C++ or Perl. 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 Perl, the Perl API is
 used to call the method of the underlying Perl object (after which the
 usual virtual method resolution in Perl automatically finds the right
 implementation).</p>
<p> Now how does the director decide which language should handle the
 method call? The basic rule is to handle the method in Perl, unless
 there's a good reason not to. The reason for this is simple: Perl has
 the most &quot;extended&quot; implementation of the method. This assertion is
 guaranteed, since at a minimum the Perl proxy class implements the
 method. If the method in question has been extended by a class derived
 from the proxy class, that extended implementation will execute exactly
 as it should. If not, the proxy class will route the method call into a
 C wrapper function, expecting that the method will be resolved in C++.
 The wrapper will call the virtual method of the C++ instance, and since
 the director extends this the call will end up right back in the
 director method. Now comes the &quot;good reason not to&quot; part. If the
 director method were to blindly call the Perl method again, it would
 get stuck in an infinite loop. We avoid this situation by adding
 special code to the C wrapper function that tells the director method
 to not do this. The C wrapper function compares the pointer to the Perl
 object that called the wrapper function to the pointer stored by the
 director. If these are the same, then the C wrapper function tells the
 director to resolve the method by calling up the C++ inheritance chain,
 preventing an infinite loop.</p>
<p> One more point needs to be made about the relationship between
 director classes and proxy classes. When a proxy class instance is
 created in Perl, SWIG creates an instance of the original C++ class.
 This is exactly what happens without directors and is true even if
 directors are enabled for the particular class in question. When a
 class<i> derived</i> from a proxy class is created, however, SWIG then
 creates an instance of the corresponding C++ director class. The reason
 for this difference is that user-defined subclasses may override or
 extend methods of the original class, so the director class is needed
 to route calls to these methods correctly. For unmodified proxy
 classes, all methods are ultimately implemented in C++ so there is no
 need for the extra overhead involved with routing the calls through
 Perl.</p>
<h3><a name="Perl5_nn50">30.11.3 Ownership and object destruction</a></h3>
<p> Memory management issues are slightly more complicated with
 directors than for proxy classes alone. Perl instances hold a pointer
 to the associated C++ director object, and the director in turn holds a
 pointer back to a Perl object. By default, proxy classes own their C++
 director object and take care of deleting it when they are garbage
 collected.</p>
<p> This relationship can be reversed by calling the special <tt>
DISOWN()</tt> method of the proxy class. After calling this method the
 director class increments the reference count of the Perl object. When
 the director class is deleted it decrements the reference count.
 Assuming no outstanding references to the Perl object remain, the Perl
 object will be destroyed at the same time. This is a good thing, since
 directors and proxies refer to each other and so must be created and
 destroyed together. Destroying one without destroying the other will
 likely cause your program to segfault.</p>
<p> Also note that due to the proxy implementation, the <tt>DESTROY()</tt>
 method on directors can be called for several reasons, many of which
 have little to do with the teardown of an object instance. To help
 disambiguate this, a second argument is added to the <tt>DESTROY()</tt>
 call when a C++ director object is being released. So, to avoid running
 your clean-up code when an object is not really going away, or after it
 has already been reclaimed, it is suggested that custom destructors in
 Perl subclasses looks something like:</p>
<div class="targetlang">
<pre>
sub DESTROY {
  my($self, $final) = @_;
  if($final) {
    # real teardown code
  }
  shift-&gt;SUPER::DESTROY(@_);
}
</pre>
</div>
<h3><a name="Perl5_nn51">30.11.4 Exception unrolling</a></h3>
<p> With directors routing method calls to Perl, and proxies routing
 them to C++, the handling of exceptions is an important concern. By
 default, the directors ignore exceptions that occur during method calls
 that are resolved in Perl. To handle such exceptions correctly, it is
 necessary to temporarily translate them into C++ exceptions. This can
 be done with the %feature(&quot;director:except&quot;) directive. The following
 code should suffice in most cases:</p>
<div class="code">
<pre>
%feature(&quot;director:except&quot;) {
  if ($error != NULL) {
    throw Swig::DirectorMethodException();
  }
}
</pre>
</div>
<p> This code will check the Perl error state after each method call
 from a director into Perl, and throw a C++ exception if an error
 occurred. This exception can be caught in C++ to implement an error
 handler.</p>
<p> It may be the case that a method call originates in Perl, travels up
 to C++ through a proxy class, and then back into Perl via a director
 method. If an exception occurs in Perl at this point, it would be nice
 for that exception to find its way back to the original caller. This
 can be done by combining a normal %exception directive with the <tt>
director:except</tt> handler shown above. Here is an example of a
 suitable exception handler:</p>
<div class="code">
<pre>
%exception {
  try { $action }
  catch (Swig::DirectorException &amp;e) { SWIG_fail; }
}
</pre>
</div>
<p> The class Swig::DirectorException used in this example is actually a
 base class of Swig::DirectorMethodException, so it will trap this
 exception. Because the Perl error state is still set when
 Swig::DirectorMethodException is thrown, Perl will register the
 exception as soon as the C wrapper function returns.</p>
<h3><a name="Perl5_nn52">30.11.5 Overhead and code bloat</a></h3>
<p> Enabling directors for a class will generate a new director method
 for every virtual method in the class' inheritance chain. This alone
 can generate a lot of code bloat for large hierarchies. Method
 arguments that require complex conversions to and from target language
 types can result in large director methods. For this reason it is
 recommended that you selectively enable directors only for specific
 classes that are likely to be extended in Perl and used in C++.</p>
<p> Compared to classes that do not use directors, the call routing in
 the director methods does add some overhead. In particular, at least
 one dynamic cast and one extra function call occurs per method call
 from Perl. Relative to the speed of Perl execution this is probably
 completely negligible. For worst case routing, a method call that
 ultimately resolves in C++ may take one extra detour through Perl in
 order to ensure that the method does not have an extended Perl
 implementation. This could result in a noticeable overhead in some
 cases.</p>
<p> Although directors make it natural to mix native C++ objects with
 Perl objects (as director objects) via a common base class pointer, one
 should be aware of the obvious fact that method calls to Perl objects
 will be much slower than calls to C++ objects. 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
 Perl.</p>
<h3><a name="Perl5_nn53">30.11.6 Typemaps</a></h3>
<p> Typemaps for input and output of most of the basic types from
 director classes have been written. These are roughly the reverse of
 the usual input and output typemaps used by the wrapper code. The
 typemap operation names are 'directorin', 'directorout', and
 'directorargout'. The director code does not currently use any of the
 other kinds of typemaps. It is not clear at this point which kinds are
 appropriate and need to be supported.</p>
<HR NOSHADE>
<h1><a name="Php">31 SWIG and PHP</a></h1>

<!-- INDEX -->
<div class="sectiontoc">
<ul>
<li><a href="#Php_nn1">Generating PHP Extensions</a>
<ul>
<li><a href="#Php_nn1_1">Building a loadable extension</a></li>
<li><a href="#Php_nn1_3">Using PHP Extensions</a></li>
</ul>
</li>
<li><a href="#Php_nn2">Basic PHP interface</a>
<ul>
<li><a href="#Php_nn2_1">Constants</a></li>
<li><a href="#Php_nn2_2">Global Variables</a></li>
<li><a href="#Php_nn2_3">Functions</a></li>
<li><a href="#Php_nn2_4">Overloading</a></li>
<li><a href="#Php_nn2_5">Pointers and References</a></li>
<li><a href="#Php_nn2_6">Structures and C++ classes</a>
<ul>
<li><a href="#Php_nn2_6_1">Using -noproxy</a></li>
<li><a href="#Php_nn2_6_2">Constructors and Destructors</a></li>
<li><a href="#Php_nn2_6_3">Static Member Variables</a></li>
<li><a href="#Php_nn2_6_4">Static Member Functions</a></li>
<li><a href="#Php_nn2_6_5">Specifying Implemented Interfaces</a></li>
</ul>
</li>
<li><a href="#Php_nn2_7">PHP Pragmas, Startup and Shutdown code</a></li>
</ul>
</li>
<li><a href="#Php_nn3">Cross language polymorphism</a>
<ul>
<li><a href="#Php_nn3_1">Enabling directors</a></li>
<li><a href="#Php_nn3_2">Director classes</a></li>
<li><a href="#Php_nn3_3">Ownership and object destruction</a></li>
<li><a href="#Php_nn3_4">Exception unrolling</a></li>
<li><a href="#Php_nn3_5">Overhead and code bloat</a></li>
<li><a href="#Php_nn3_6">Typemaps</a></li>
<li><a href="#Php_nn3_7">Miscellaneous</a></li>
</ul>
</li>
</ul>
</div>
<!-- INDEX -->
<p> In this chapter, we discuss SWIG's support of PHP. SWIG currently
 supports generating wrappers for PHP7. Support for PHP5 was removed in
 SWIG 4.0.0 and support for PHP4 was removed in SWIG 1.3.37.</p>
<p> Currently any PHP7 release should work.</p>
<p> In order to use this module, you will need to have a copy of the PHP
 include files to compile the SWIG generated files. If you installed PHP
 from a binary package, you may need to install a &quot;php-dev&quot; or
 &quot;php-devel&quot; package for these to be installed. You can find out where
 these files are by running <tt>php-config --includes</tt>. To use the
 built PHP module you will need either the php binary or the Apache php
 module. If you want to build your extension into php directly, you will
 need the complete PHP source tree available.</p>
<h2><a name="Php_nn1">31.1 Generating PHP Extensions</a></h2>
<p> To build a PHP extension, run swig using the <tt>-php7</tt> option
 as follows (<tt>-php</tt> is also supported and currently is an alias
 for <tt>-php7</tt> but prior to SWIG 4.0.0 it was an alias for <tt>
-php5</tt>):</p>
<div class="code">
<pre>
swig -php7 example.i
</pre>
</div>
<p> This will produce 3 files example_wrap.c, php_example.h and
 example.php. The first file, <tt>example_wrap.c</tt> contains all of
 the C code needed to build a PHP extension. The second file, <tt>
php_example.h</tt> contains the header information needed if you wish to
 statically link the extension into the php interpreter. The third file,
 <tt>example.php</tt> can be included by PHP scripts. It attempts to
 dynamically load the extension and contains extra php code specified in
 the interface file. If wrapping C++ code with PHP classes, it will also
 contain PHP class wrappers.</p>
<p> SWIG can generate PHP extensions from C++ libraries as well when
 given the <tt>-c++</tt> option. The support for C++ is discussed in
 more detail in <a href="#Php_nn2_6">section 27.2.6</a>. The generated
 C++ wrapper will be called example_wrap.cxx. You can specify a
 different extension for the C++ wrapper using <tt>-cppext</tt> - e.g.
 if you want example_wrap.cc use <tt>-cppext cc</tt>.</p>
<p> The usual (and recommended) way is to build the extension as a
 separate dynamically loaded module (which is supported by all modern
 operating systems).</p>
<p> It is also possible to rebuild PHP from source so that your module
 is statically linked into the php executable/library. This is a lot
 more work, and also requires a full rebuild of PHP to update your
 module, and it doesn't play nicely with package system. We don't
 recommend this approach, or provide explicit support for it.</p>
<h3><a name="Php_nn1_1">31.1.1 Building a loadable extension</a></h3>
<p> To build your module as a dynamically loadable extension, use
 compilation commands like these (if you aren't using GCC, the commands
 will be different, and there may be some variation between platforms -
 these commands should at least work for Linux though):</p>
<div class="code">
<pre>
        gcc `php-config --includes` -fpic -c example_wrap.c example.c
        gcc -shared example_wrap.o example.o -o example.so
</pre>
</div>
<h3><a name="Php_nn1_3">31.1.2 Using PHP Extensions</a></h3>
<p> To test the extension from a PHP script, you first need to tell PHP
 to load it. To do this, add a line like this to the <tt>[PHP]</tt>
 section of <tt>php.ini</tt>:</p>
<div class="code">
<pre>
        extension=/path/to/modulename.so
</pre>
</div>
<p> If the module is in PHP's default extension directory, you can omit
 the path.</p>
<p> For some SAPIs (for example, the CLI SAPI) you can instead use the <a
href="https://www.php.net/manual/en/function.dl.php">dl() function</a>
 to load an extension at run time, by adding a line like this to the
 start of each PHP script which uses your extension:</p>
<div class="code">
<pre>
        dl(&quot;/path/to/modulename.so&quot;); // Load the module
</pre>
</div>
<p> But note that <tt>dl()</tt> isn't supported when running PHP through
 a webserver - you'll need to use <tt>extension</tt> in <tt>php.ini</tt>
 as described above.</p>
<p> The PHP module which SWIG generates will also attempt to do the <tt>
dl()</tt> call for you if the extension isn't already loaded:</p>
<div class="code">
<pre>
        include(&quot;example.php&quot;);
</pre>
</div>
<p> This PHP module also defines the PHP classes for the wrapped API, so
 you'll almost certainly want to include it anyway.</p>
<h2><a name="Php_nn2">31.2 Basic PHP interface</a></h2>
<p> It is important to understand that PHP uses a single global
 namespace into which all symbols from extension modules are loaded. It
 is quite possible for names of symbols in one extension module to clash
 with other symbols unless care is taken to <tt>%rename</tt> them. At
 present SWIG doesn't have support for generating wrappers which make
 use of PHP's namespace feature.</p>
<h3><a name="Php_nn2_1">31.2.1 Constants</a></h3>
<p> These work in much the same way as in C/C++. Constants can be
 defined by using either the normal C pre-processor declarations, or the
 <tt>%constant</tt> SWIG directive. These will then be available from
 your PHP script as a PHP constant, (i.e. no dollar sign is needed to
 access them.) For example, with a swig interface file like this,</p>
<div class="code">
<pre>
%module example

#define PI 3.14159

%constant int E  = 2.71828
</pre>
</div>
<p> you can access the constants in your PHP script like this,</p>
<div class="code">
<pre>
include(&quot;example.php&quot;);

echo &quot;PI = &quot; . PI . &quot;\n&quot;;

echo &quot;E = &quot; . E . &quot;\n&quot;;

</pre>
</div>
<p> There's one peculiarity of how constants work in PHP which it is
 useful to note (this is not specific to SWIG though) - if you try to
 use an undeclared constant, PHP will emit a warning (or a notice in PHP
 7.1 and earlier) and then expand the constant to a string version of
 the constant's name. Unfortunately it is easy to miss the warning
 message if you're using PHP in a webserver as it will probably end up
 in error.log or similar. Apparently this will throw an Error in a
 future version of PHP, but until then it's something to be aware of.</p>
<p> For example,</p>
<div class="code">
<pre>
%module example

#define EASY_TO_MISPELL 0
</pre>
</div>
<p> accessed incorrectly in PHP,</p>
<div class="code">
<pre>
include(&quot;example.php&quot;);

if(EASY_TO_MISPEL) {
  ...
} else {
  ...
}

</pre>
</div>
<p> The mis-spelled constant will become the string 'EASY_TO_MISPEL',
 which is treated as true by the if test, when the value of the intended
 constant would be treated as false!</p>
<h3><a name="Php_nn2_2">31.2.2 Global Variables</a></h3>
<p> Because PHP does not provide a mechanism to intercept access and
 assignment of global variables, global variables are supported through
 the use of automatically generated accessor functions.</p>
<div class="code">
<pre>
%module example;

%inline %{
  double seki = 2;
  void print_seki() {
    zend_printf(&quot;seki is now %f\n&quot;, seki);
  }
%}
</pre>
</div>
<p> is accessed as follows:</p>
<div class="code">
<pre>
include(&quot;example.php&quot;);
print seki_get();
seki_set( seki_get() * 2); # The C variable is now 4.
print seki_get();
</pre>
</div>
<p> SWIG supports global variables of all C datatypes including pointers
 and complex objects. Additional types can be supported by using the <tt>
varinit</tt> typemap.</p>
<p> SWIG honors the <tt>%immutable</tt> modifier by not generating code
 for the <tt>_set</tt> method. This provides read-only access to the
 variable from the php script. Attempting to access the <tt>_set</tt>
 method will result in a php fatal error because the function is
 undefined.</p>
<p> At this time SWIG does not support custom accessor methods.</p>
<h3><a name="Php_nn2_3">31.2.3 Functions</a></h3>
<p> C functions are converted into PHP functions. Default/optional
 arguments are also allowed. An interface file like this :</p>
<div class="code">
<pre>
%module example
int foo(int a);
double bar(double, double b = 3.0);
...
</pre>
</div>
<p> Will be accessed in PHP like this :</p>
<div class="code">
<pre>
include(&quot;example.php&quot;);
$a = foo(2);
$b = bar(3.5, -1.5);
$c = bar(3.5);  # Use default argument for 2nd parameter

</pre>
</div>
<!-- This isn't correct for 1.3.30 and needs rewriting to reflect reality
&lt;p&gt;
Because PHP is a dynamically typed language, the default typemaps
used for simple types will attempt to coerce the arguments into the appropriate type.  That is the following invocations are equivalent:
&lt;/p&gt;

&lt;div class=&quot;code&quot;&gt;&lt;pre&gt;
$a = foo(2);
$a = foo(&quot;2&quot;);
$a = foo(2.0);
&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;
Functions are invoked using pass by value semantics like all of PHP.
This means the conversion which automatically takes place when
invoking a swig wrapped method does not change the native type of the
argument variable.
&lt;/p&gt;
&lt;div class=&quot;code&quot;&gt;&lt;pre&gt;
$s = &quot;2 A string representing two&quot;;
$a = foo($s);  # invokes 'foo(2)';
print $s;      # The value of $s was not changed.
&lt;/pre&gt;&lt;/div&gt;
-->
<h3><a name="Php_nn2_4">31.2.4 Overloading</a></h3>
<p> Although PHP does not support overloading functions natively, swig
 will generate dispatch functions which will use <tt>%typecheck</tt>
 typemaps to allow overloading. This dispatch function's operation and
 precedence is described in <a href="#SWIGPlus_overloaded_methods">
Overloaded functions and methods</a>.</p>

<!-- This isn't correct for 1.3.30 and needs rewriting to reflect reality
&lt;p&gt;
Because PHP is a dynamically typed language, simple values can be
silently converted from one type to another.  For example, integers,
doubles and strings silently convert to each other depending on
context.  This situation make overloading slightly problematic because
given the following function:
&lt;/p&gt;

&lt;div class=&quot;code&quot;&gt;&lt;pre&gt;
void doit( int i );
void doit( double i );
&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;
it is questionable which to invoke when &lt;tt&gt;doit(&quot;2&quot;);&lt;/tt&gt; is used in
PHP.  The string &lt;tt&gt;&quot;2&quot;&lt;/tt&gt; simultaneously represents the integer
&lt;tt&gt;2&lt;/tt&gt; and the double &lt;tt&gt;2.0&lt;/tt&gt;.
&lt;/p&gt;

&lt;p&gt;
In order to provide the most natural experience to PHP programmers,
the default &lt;tt&gt;%typecheck&lt;/tt&gt; implemented in &lt;tt&gt;php.swg&lt;/tt&gt;
allows any simple type (integer, double, string) in PHP to be used for
any simple C type (int, double, char *).  The function selected then
depends only on the argument type precedence defined by SWIG.
&lt;/p&gt;

&lt;p&gt;
It should be noted that &lt;tt&gt;SWIGTYPE&lt;/tt&gt; references and pointers will
not be silently converted.  So these two functions:
&lt;/p&gt;

&lt;div class=&quot;code&quot;&gt;&lt;pre&gt;
void doit( const Vector &amp; );
void doit( int i );
&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;
Cause less confusion and &lt;tt&gt;doit(&quot;2&quot;);&lt;/tt&gt; will invoke the function
taking the integer argument.
&lt;/p&gt;
-->
<h3><a name="Php_nn2_5">31.2.5 Pointers and References</a></h3>
<p> Pointers to C/C++ objects are represented as PHP resources, rather
 like MySQL connection handles.</p>
<p> There are multiple ways to wrap pointers to simple types. Given the
 following C method:</p>
<div class="code">
<pre>
  void add( int *in1, int *in2, int *result);
</pre>
</div>
<p> One can include<b> cpointer.i</b> to generate PHP wrappers to <tt>
int *</tt>.</p>
<div class="code">
<pre>
%module example
%include &quot;cpointer.i&quot;
%pointer_functions(int, intp)

void add( int *in1, int *in2, int *result);
</pre>
</div>
<p> This will result in the following usage in PHP:</p>
<div class="code">
<pre>
&lt;?php

include(&quot;example.php&quot;);

$in1=copy_intp(3);
$in2=copy_intp(5);
$result=new_intp();

add( $in1, $in2, $result );

echo &quot;The sum &quot; . intp_value($in1) . &quot; + &quot; . intp_value($in2) . &quot; = &quot; . intp_value( $result) . &quot;\n&quot;;
?&gt;
</pre>
</div>
<p> An alternative would be to use the include<b> typemaps.i</b> which
 defines named typemaps for INPUT, OUTPUT and INOUT variables. One needs
 to either <tt>%apply</tt> the appropriate typemap or adjust the
 parameter names as appropriate.</p>
<div class="code">
<pre>
%module example
%include &quot;typemaps.i&quot;

void add( int *INPUT, int *INPUT, int *OUTPUT);

</pre>
</div>
<p> This will result in the following usage in PHP:</p>
<div class="code">
<pre>
&lt;?php

include(&quot;example.php&quot;);

$in1 = 3;
$in2 = 5;
$result= add($in1, $in2);  # Note using variables for the input is unnecessary.

echo &quot;The sum $in1 + $in2 = $result\n&quot;;
?&gt;
</pre>
</div>
<p> Because PHP has a native concept of reference, it may seem more
 natural to the PHP developer to use references to pass pointers. To
 enable this, one needs to include<b> phppointers.i</b> which defines
 the named typemap REF.</p>
<p> In case you write your own typemaps, SWIG supports an attribute
 called <tt>byref</tt>: if you set that, then SWIG will make sure that
 the generated wrapper function will want the input parameter as a
 reference.</p>
<div class="code">
<pre>
%module example
%include &quot;phppointers.i&quot;

void add( int *REF, int *REF, int *REF);

</pre>
</div>
<p> This will result in the following usage in PHP:</p>
<div class="code">
<pre>
&lt;?php

include(&quot;example.php&quot;);

$in1 = 3;
$in2 = 5;
$result = 0;
add($in1, $in2, $result);

echo &quot;The sum $in1 + $in2 = $result\n&quot;;
?&gt;
</pre>
</div>
<p> It is important to note that a php variable which is NULL when
 passed by reference would end up passing a NULL pointer into the
 function. In PHP, an unassigned variable (i.e. where the first
 reference to the variable is not an assignment) is NULL. In the above
 example, if any of the three variables had not been assigned, a NULL
 pointer would have been passed into <tt>add</tt>. Depending on the
 implementation of the function, this may or may not be a good thing.</p>
<p> We chose to allow passing NULL pointers into functions because that
 is sometimes required in C libraries. A NULL pointer can be created in
 PHP in a number of ways: by using <tt>unset</tt> on an existing
 variable, or assigning <tt>NULL</tt> to a variable.</p>
<h3><a name="Php_nn2_6">31.2.6 Structures and C++ classes</a></h3>
<p> SWIG defaults to wrapping C++ structs and classes with PHP classes -
 this is done by generating a PHP wrapper script which defines proxy
 classes which calls a set of flat functions which actually wrap the C++
 class. You can disable this wrapper layer by passing the command-line
 option &quot;-noproxy&quot; in which case you'll just get the flat functions.</p>
<p> This interface file</p>
<div class="code">
<pre>
%module vector

class Vector {
public:
  double x, y, z;
  Vector();
  ~Vector();
  double magnitude();
};

struct Complex {
 double re, im;
};
</pre>
</div>
<p> Would be used in the following way from PHP:</p>
<div class="code">
<pre>
&lt;?php
  require &quot;vector.php&quot;;

  $v = new Vector();
  $v-&gt;x = 3;
  $v-&gt;y = 4;
  $v-&gt;z = 5;

  echo &quot;Magnitude of ($v-&gt;x, $v-&gt;y, $v-&gt;z) = &quot; . $v-&gt;magnitude() . &quot;\n&quot;;

  $v = NULL;   # destructor called.

  $c = new Complex();

  $c-&gt;re = 0;
  $c-&gt;im = 0;

  # $c destructor called when $c goes out of scope.
?&gt;
</pre>
</div>
<p> Member variables and methods are accessed using the <tt>-&gt;</tt>
 operator.</p>
<h4><a name="Php_nn2_6_1">31.2.6.1 Using -noproxy</a></h4>
<p> The <tt>-noproxy</tt> option flattens the object structure and
 generates collections of named functions (these are the functions which
 the PHP class wrappers call). The above example results in the
 following PHP functions:</p>
<div class="code">
<pre>
new_Vector();
Vector_x_set($obj, $d);
Vector_x_get($obj);
Vector_y_set($obj, $d);
Vector_y_get($obj);
Vector_z_set($obj, $d);
Vector_z_get($obj);
Vector_magnitude($obj);
new_Complex();
Complex_re_set($obj, $d);
Complex_re_get($obj);
Complex_im_set($obj, $d);
Complex_im_get($obj);
</pre>
</div>
<h4><a name="Php_nn2_6_2">31.2.6.2 Constructors and Destructors</a></h4>
<p> The constructor is called when <tt>new Object()</tt> (or <tt>
new_Object()</tt> if using <tt>-noproxy</tt>) is used to create an
 instance of the object. If multiple constructors are defined for an
 object, function overloading will be used to determine which
 constructor to execute.</p>
<p> Because PHP uses reference counting to manage resources, simple
 assignment of one variable to another such as:</p>
<div class="code">
<pre>
$ref = $v;
</pre>
</div>
<p> causes the symbol <tt>$ref</tt> to refer to the same underlying
 object as <tt>$v</tt>. This does not result in a call to the C++ copy
 constructor or copy assignment operator.</p>
<p> One can force execution of the copy constructor by using:</p>
<div class="code">
<pre>
$o_copy = new Object($o);
</pre>
</div>
<p> Destructors are automatically called when all variables referencing
 the instance are reassigned or go out of scope. The destructor is not
 available to be called manually. To force a destructor to be called the
 programmer can either reassign the variable or call <tt>unset($v)</tt></p>
<h4><a name="Php_nn2_6_3">31.2.6.3 Static Member Variables</a></h4>
<p> Static member variables in C++ are not wrapped as such in PHP as it
 does not appear to be possible to intercept accesses to such variables.
 Therefore, static member variables are wrapped using a class function
 with the same name, which returns the current value of the class
 variable. For example</p>
<div class="code">
<pre>
%module example

class Ko {
  static int threats;
};

</pre>
</div>
<p> would be accessed in PHP as,</p>
<div class="code">
<pre>
include(&quot;example.php&quot;);

echo &quot;There have now been &quot; . Ko::threats() . &quot; threats\n&quot;;

</pre>
</div>
<p> To set the static member variable, pass the value as the argument to
 the class function, e.g.</p>
<div class="code">
<pre>

Ko::threats(10);

echo &quot;There have now been &quot; . Ko::threats() . &quot; threats\n&quot;;

</pre>
</div>
<h4><a name="Php_nn2_6_4">31.2.6.4 Static Member Functions</a></h4>
<p> Static member functions are supported in PHP using the <tt>
class::function()</tt> syntax. For example</p>
<div class="code">
<pre>
%module example
class Ko {
  static void threats();
};
</pre>
</div> would be executed in PHP as,<div class="code">
<pre>
include(&quot;example.php&quot;);
Ko::threats();
</pre>
</div>
<h4><a name="Php_nn2_6_5">31.2.6.5 Specifying Implemented Interfaces</a></h4>
<p> PHP supports the concept of abstract interfaces which a class can
 implement. Since SWIG 3.0.3, you can tell SWIG that a wrapped class
 (for example <code>MyIterator</code>) implements the <code>Iterator</code>
 interface like so:</p>
<div class="code">
<pre>
%typemap(&quot;phpinterfaces&quot;) MyIterator &quot;Iterator&quot;;
</pre>
</div>
<p> If there are multiple interfaces, just list them separated by
 commas.</p>
<h3><a name="Php_nn2_7">31.2.7 PHP Pragmas, Startup and Shutdown code</a>
</h3>
<p> To place PHP code in the generated &quot;example.php&quot; file one can use
 the<b> code</b> pragma. The code is inserted after loading the shared
 object.</p>
<div class="code">
<pre>
%module example
%pragma(php) code=&quot;
# This code is inserted into example.php
echo \&quot;example.php execution\\n\&quot;;
&quot;
</pre>
</div>
<p> Results in the following in &quot;example.php&quot;</p>
<div class="code">
<pre>
# This code is inserted into example.php
echo &quot;example.php execution\n&quot;;
</pre>
</div>
<p> The<b> version</b> pragma can be used to add version to generated
 PHP extension module. The version is inserted in the zend_module_entry
 block.</p>
<div class="code">
<pre>
%module example
%pragma(php) version=&quot;1.5&quot;
</pre>
</div>
<p> The<b> include</b> pragma is a short cut to add include statements
 to the example.php file.</p>
<div class="code">
<pre>
%module example
%pragma(php) code=&quot;
include \&quot;include.php\&quot;;
&quot;
%pragma(php) include=&quot;include.php&quot;   // equivalent.
</pre>
</div>
<p> The<b> phpinfo</b> pragma inserts code in the <tt>PHP_MINFO_FUNCTION</tt>
 which is called from PHP's phpinfo() function.</p>
<div class="code">
<pre>
%module example;
%pragma(php) phpinfo=&quot;
  zend_printf(&quot;An example of PHP support through SWIG\n&quot;);
  php_info_print_table_start();
  php_info_print_table_header(2, \&quot;Directive\&quot;, \&quot;Value\&quot;);
  php_info_print_table_row(2, \&quot;Example support\&quot;, \&quot;enabled\&quot;);
  php_info_print_table_end();
&quot;
</pre>
</div>
<p> To insert code into the <tt>PHP_MINIT_FUNCTION</tt>, one can use
 either <tt>%init</tt> or <tt>%minit</tt>.</p>
<div class="code">
<pre>
%module example;
%init {
  zend_printf(&quot;Inserted into PHP_MINIT_FUNCTION\n&quot;);
}
%minit {
  zend_printf(&quot;Inserted into PHP_MINIT_FUNCTION\n&quot;);
}
</pre>
</div>
<p> To insert code into the <tt>PHP_MSHUTDOWN_FUNCTION</tt>, one can use
 either <tt>%shutdown</tt> or <tt>%mshutdown</tt>.</p>
<div class="code">
<pre>
%module example;
%mshutdown {
  zend_printf(&quot;Inserted into PHP_MSHUTDOWN_FUNCTION\n&quot;);
}
</pre>
</div>
<p> The <tt>%rinit</tt> and <tt>%rshutdown</tt> statements are very
 similar but insert code into the request init (PHP_RINIT_FUNCTION) and
 request shutdown (PHP_RSHUTDOWN_FUNCTION) code respectively.</p>
<h2><a name="Php_nn3">31.3 Cross language polymorphism</a></h2>
<p> Proxy classes provide a more natural, object-oriented way to access
 extension classes. As described above, each proxy instance has an
 associated C++ instance, and method calls to the proxy are passed to
 the C++ instance transparently via C wrapper functions.</p>
<p> This arrangement is asymmetric in the sense that no corresponding
 mechanism exists to pass method calls down the inheritance chain from
 C++ to PHP. In particular, if a C++ class has been extended in PHP (by
 extending the proxy class), these extensions will not be visible from
 C++ code. Virtual method calls from C++ are thus not able access the
 lowest implementation in the inheritance chain.</p>
<p> Changes have been made to SWIG 1.3.18 to 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. Support for
 generating PHP classes has been added in SWIG 1.3.40. The job of the
 directors is to route method calls correctly, either to C++
 implementations higher in the inheritance chain or to PHP
 implementations lower in the inheritance chain. The upshot is that C++
 classes can be extended in PHP and from C++ these extensions look
 exactly like native C++ classes. Neither C++ code nor PHP code needs to
 know where a particular method is implemented: the combination of proxy
 classes, director classes, and C wrapper functions takes care of all
 the cross-language method routing transparently.</p>
<h3><a name="Php_nn3_1">31.3.1 Enabling directors</a></h3>
<p> The director feature is disabled by default. To use directors you
 must make two changes to the interface file. First, add the &quot;directors&quot;
 option to the %module directive, like this:</p>
<div class="code">
<pre>
%module(directors=&quot;1&quot;) modulename
</pre>
</div>
<p> Without this option no director code will be generated. Second, you
 must use the %feature(&quot;director&quot;) directive to tell SWIG which classes
 and methods should get directors. The %feature directive can be applied
 globally, to specific classes, and to specific methods, like this:</p>
<div class="code">
<pre>
// generate directors for all classes that have virtual methods
%feature(&quot;director&quot;);         

// generate directors for the virtual methods in class Foo
%feature(&quot;director&quot;) Foo;      
</pre>
</div>
<p> You can use the %feature(&quot;nodirector&quot;) directive to turn off
 directors for specific classes or methods. So for example,</p>
<div class="code">
<pre>
%feature(&quot;director&quot;) Foo;
%feature(&quot;nodirector&quot;) Foo::bar;
</pre>
</div>
<p> will generate directors for the virtual methods of class Foo except
 bar().</p>
<p> Directors can also be generated implicitly through inheritance. In
 the following, class Bar will get a director class that handles the
 methods one() and two() (but not three()):</p>
<div class="code">
<pre>
%feature(&quot;director&quot;) Foo;
class Foo {
public:
  Foo(int foo);
  virtual void one();
  virtual void two();
};

class Bar: public Foo {
public:
  virtual void three();
};
</pre>
</div>
<p> then at the PHP side you can define</p>
<div class="targetlang">
<pre>
require(&quot;mymodule.php&quot;);

class MyFoo extends Foo {
  function one() {
    print &quot;one from php\n&quot;;
  }
}
</pre>
</div>
<h3><a name="Php_nn3_2">31.3.2 Director classes</a></h3>
<p> For each class that has directors enabled, SWIG generates a new
 class that derives from both the class in question and a special <tt>
Swig::Director</tt> class. These new classes, referred to as director
 classes, can be loosely thought of as the C++ equivalent of the PHP
 proxy classes. The director classes store a pointer to their underlying
 PHP object. Indeed, this is quite similar to the &quot;_cPtr&quot; and &quot;thisown&quot;
 members of the PHP proxy classes.</p>
<p> For simplicity let's ignore the <tt>Swig::Director</tt> class and
 refer to the original C++ class as the director's base class. By
 default, a director class extends all virtual methods in the
 inheritance chain of its base class (see the preceding section for how
 to modify this behavior). Virtual methods that have a final specifier
 are unsurprisingly excluded. Thus the virtual method calls, whether
 they originate in C++ or in PHP 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 &quot;appropriate place&quot; we mean the method that would
 have been called if the C++ base class and its extensions in PHP were
 seamlessly integrated. That seamless integration is exactly what the
 director classes provide, transparently skipping over all the messy
 extension API glue that binds the two languages together.</p>
<p> In reality, the &quot;appropriate place&quot; is one of only two
 possibilities: C++ or PHP. 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 PHP, the Zend API is
 used to call the method of the underlying PHP object (after which the
 usual virtual method resolution in PHP automatically finds the right
 implementation).</p>
<p> Now how does the director decide which language should handle the
 method call? The basic rule is to handle the method in PHP, unless
 there's a good reason not to. The reason for this is simple: PHP has
 the most &quot;extended&quot; implementation of the method. This assertion is
 guaranteed, since at a minimum the PHP proxy class implements the
 method. If the method in question has been extended by a class derived
 from the proxy class, that extended implementation will execute exactly
 as it should. If not, the proxy class will route the method call into a
 C wrapper function, expecting that the method will be resolved in C++.
 The wrapper will call the virtual method of the C++ instance, and since
 the director extends this the call will end up right back in the
 director method. Now comes the &quot;good reason not to&quot; part. If the
 director method were to blindly call the PHP method again, it would get
 stuck in an infinite loop. We avoid this situation by adding special
 code to the C wrapper function that tells the director method to not do
 this. The C wrapper function compares the called and the declaring
 class name of the given method. If these are not the same, then the C
 wrapper function tells the director to resolve the method by calling up
 the C++ inheritance chain, preventing an infinite loop.</p>
<p> One more point needs to be made about the relationship between
 director classes and proxy classes. When a proxy class instance is
 created in PHP, SWIG creates an instance of the original C++ class and
 assigns it to <tt>-&gt;_cPtr</tt>. This is exactly what happens without
 directors and is true even if directors are enabled for the particular
 class in question. When a class<i> derived</i> from a proxy class is
 created, however, SWIG then creates an instance of the corresponding
 C++ director class. The reason for this difference is that user-defined
 subclasses may override or extend methods of the original class, so the
 director class is needed to route calls to these methods correctly. For
 unmodified proxy classes, all methods are ultimately implemented in C++
 so there is no need for the extra overhead involved with routing the
 calls through PHP.</p>
<h3><a name="Php_nn3_3">31.3.3 Ownership and object destruction</a></h3>
<p> Memory management issues are slightly more complicated with
 directors than for proxy classes alone. PHP instances hold a pointer to
 the associated C++ director object, and the director in turn holds a
 pointer back to the PHP object. By default, proxy classes own their C++
 director object and take care of deleting it when they are garbage
 collected.</p>
<p> This relationship can be reversed by calling the special <tt>
-&gt;thisown</tt> property of the proxy class. After setting this property
 to <tt>0</tt>, the director class no longer destroys the PHP object.
 Assuming no outstanding references to the PHP object remain, the PHP
 object will be destroyed at the same time. This is a good thing, since
 directors and proxies refer to each other and so must be created and
 destroyed together. Destroying one without destroying the other will
 likely cause your program to segfault.</p>
<p> Here is an example:</p>
<div class="code">
<pre>
class Foo {
public:
  ...
};
class FooContainer {
public:
  void addFoo(Foo *);
  ...
};
</pre>
</div>
<br><div class="targetlang">
<pre>
$c = new FooContainer();
$a = new Foo();
$a-&gt;thisown = 0;
$c-&gt;addFoo($a);
</pre>
</div>
<p> In this example, we are assuming that FooContainer will take care of
 deleting all the Foo pointers it contains at some point.</p>
<h3><a name="Php_nn3_4">31.3.4 Exception unrolling</a></h3>
<p> With directors routing method calls to PHP, and proxies routing them
 to C++, the handling of exceptions is an important concern. By default,
 an exception thrown in PHP code called from C++ causes the PHP
 interpreter to flag that an exception is thrown, then return passes to
 C++ as if the PHP function had returned <code>Null</code>. Assuming the
 directorout typemaps handle this (those SWIG defines by default should)
 then once control returns to PHP code again, the PHP exception will
 actually propagate.</p>
<p> Sometimes this control flow is problematic, and you want to skip any
 handling in the C++ code. To achieve this, it is necessary to
 temporarily translate the PHP exception into a C++ exception. This can
 be achieved using the %feature(&quot;director:except&quot;) directive. The
 following code should suffice in most cases:</p>
<div class="code">
<pre>
%feature(&quot;director:except&quot;) {
  if ($error == FAILURE) {
    throw Swig::DirectorMethodException();
  }
}
</pre>
</div>
<p> This code will check the PHP error state after each method call from
 a director into PHP, and throw a C++ exception if an error occurred.
 This exception can be caught in C++ to implement an error handler.
 Currently no information about the PHP error is stored in the
 Swig::DirectorMethodException object, but this will likely change in
 the future.</p>
<p> It may be the case that a method call originates in PHP, travels up
 to C++ through a proxy class, and then back into PHP via a director
 method. If an exception occurs in PHP at this point, it would be nice
 for that exception to find its way back to the original caller. This
 can be done by combining a normal %exception directive with the <tt>
director:except</tt> handler shown above. Here is an example of a
 suitable exception handler:</p>
<div class="code">
<pre>
%exception {
  try { $action }
  catch (Swig::DirectorException &amp;e) { SWIG_fail; }
}
</pre>
</div>
<p> The class Swig::DirectorException used in this example is actually a
 base class of Swig::DirectorMethodException, so it will trap this
 exception. Because the PHP error state is still set when
 Swig::DirectorMethodException is thrown, PHP will register the
 exception as soon as the C wrapper function returns.</p>
<h3><a name="Php_nn3_5">31.3.5 Overhead and code bloat</a></h3>
<p> Enabling directors for a class will generate a new director method
 for every virtual method in the class' inheritance chain. This alone
 can generate a lot of code bloat for large hierarchies. Method
 arguments that require complex conversions to and from target language
 types can result in large director methods. For this reason it is
 recommended that you selectively enable directors only for specific
 classes that are likely to be extended in PHP and used in C++.</p>
<p> Compared to classes that do not use directors, the call routing in
 the director methods does add some overhead. In particular, at least
 one dynamic cast and one extra function call occurs per method call
 from PHP. Relative to the speed of PHP execution this is probably
 completely negligible. For worst case routing, a method call that
 ultimately resolves in C++ may take one extra detour through PHP in
 order to ensure that the method does not have an extended PHP
 implementation. This could result in a noticeable overhead in some
 cases.</p>
<p> Although directors make it natural to mix native C++ objects with
 PHP objects (as director objects) via a common base class pointer, one
 should be aware of the obvious fact that method calls to PHP objects
 will be much slower than calls to C++ objects. 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
 PHP.</p>
<h3><a name="Php_nn3_6">31.3.6 Typemaps</a></h3>
<p> Typemaps for input and output of most of the basic types from
 director classes have been written. These are roughly the reverse of
 the usual input and output typemaps used by the wrapper code. The
 typemap operation names are 'directorin', 'directorout', and
 'directorargout'. The director code does not currently use any of the
 other kinds of typemaps. It is not clear at this point which kinds are
 appropriate and need to be supported.</p>
<h3><a name="Php_nn3_7">31.3.7 Miscellaneous</a></h3>
<p> Director typemaps for STL classes are mostly in place, and hence you
 should be able to use std::string, etc., as you would any other type.</p>
<HR NOSHADE>
<h1><a name="Python">32 SWIG and Python</a></h1>

<!-- INDEX -->
<div class="sectiontoc">
<ul>
<li><a href="#Python_nn2">Overview</a></li>
<li><a href="#Python_nn3">Preliminaries</a>
<ul>
<li><a href="#Python_nn4">Running SWIG</a></li>
<li><a href="#Python_nn6">Using distutils</a></li>
<li><a href="#Python_nn7">Hand compiling a dynamic module</a></li>
<li><a href="#Python_nn8">Static linking</a></li>
<li><a href="#Python_nn9">Using your module</a></li>
<li><a href="#Python_nn10">Compilation of C++ extensions</a></li>
<li><a href="#Python_nn11">Compiling for 64-bit platforms</a></li>
<li><a href="#Python_nn12">Building Python extensions under Windows</a></li>
<li><a href="#Python_commandline">Additional Python commandline options</a>
</li>
</ul>
</li>
<li><a href="#Python_nn13">A tour of basic C/C++ wrapping</a>
<ul>
<li><a href="#Python_nn14">Modules</a></li>
<li><a href="#Python_nn15">Functions</a></li>
<li><a href="#Python_nn16">Global variables</a></li>
<li><a href="#Python_nn17">Constants and enums</a></li>
<li><a href="#Python_nn18">Pointers</a></li>
<li><a href="#Python_nn19">Structures</a></li>
<li><a href="#Python_nn20">C++ classes</a></li>
<li><a href="#Python_nn21">C++ inheritance</a></li>
<li><a href="#Python_nn22">Pointers, references, values, and arrays</a></li>
<li><a href="#Python_nn23">C++ overloaded functions</a></li>
<li><a href="#Python_nn24">C++ operators</a></li>
<li><a href="#Python_nn25">C++ namespaces</a></li>
<li><a href="#Python_nn26">C++ templates</a></li>
<li><a href="#Python_nn27">C++ Smart Pointers</a>
<ul>
<li><a href="#Python_smart_pointers_shared_ptr">The shared_ptr Smart
 Pointer</a></li>
<li><a href="#Python_smart_pointers_generic">Generic Smart Pointers</a></li>
</ul>
</li>
<li><a href="#Python_nn27a">C++ reference counted objects</a></li>
</ul>
</li>
<li><a href="#Python_nn28">Further details on the Python class interface</a>
<ul>
<li><a href="#Python_nn29">Proxy classes</a></li>
<li><a href="#Python_builtin_types">Built-in Types</a>
<ul>
<li><a href="#Python_builtin_limitations">Limitations</a></li>
<li><a href="#Python_builtin_overloads">Operator overloads and slots --
 use them!</a></li>
</ul>
</li>
<li><a href="#Python_nn30">Memory management</a></li>
</ul>
</li>
<li><a href="#Python_directors">Cross language polymorphism</a>
<ul>
<li><a href="#Python_nn33">Enabling directors</a></li>
<li><a href="#Python_nn34">Director classes</a></li>
<li><a href="#Python_nn35">Ownership and object destruction</a></li>
<li><a href="#Python_nn36">Exception unrolling</a></li>
<li><a href="#Python_nn37">Overhead and code bloat</a></li>
<li><a href="#Python_nn38">Typemaps</a></li>
<li><a href="#Python_nn39">Miscellaneous</a></li>
</ul>
</li>
<li><a href="#Python_nn40">Common customization features</a>
<ul>
<li><a href="#Python_nn41">C/C++ helper functions</a></li>
<li><a href="#Python_nn42">Adding additional Python code</a></li>
<li><a href="#Python_nn43">Class extension with %extend</a></li>
<li><a href="#Python_nn44">Exception handling with %exception</a></li>
<li><a href="#Python_optimization">Optimization options</a>
<ul>
<li><a href="#Python_fastproxy">-fastproxy</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#Python_nn45">Tips and techniques</a>
<ul>
<li><a href="#Python_nn46">Input and output parameters</a></li>
<li><a href="#Python_nn47">Simple pointers</a></li>
<li><a href="#Python_nn48">Unbounded C Arrays</a></li>
<li><a href="#Python_nn49">String handling</a></li>
<li><a href="#Python_default_args">Default arguments</a></li>
</ul>
</li>
<li><a href="#Python_nn53">Typemaps</a>
<ul>
<li><a href="#Python_nn54">What is a typemap?</a></li>
<li><a href="#Python_nn55">Python typemaps</a></li>
<li><a href="#Python_nn56">Typemap variables</a></li>
<li><a href="#Python_nn57">Useful Python Functions</a></li>
</ul>
</li>
<li><a href="#Python_nn58">Typemap Examples</a>
<ul>
<li><a href="#Python_nn59">Converting Python list to a char **</a></li>
<li><a href="#Python_nn60">Expanding a Python object into multiple
 arguments</a></li>
<li><a href="#Python_nn61">Using typemaps to return arguments</a></li>
<li><a href="#Python_nn62">Mapping Python tuples into small arrays</a></li>
<li><a href="#Python_nn63">Mapping sequences to C arrays</a></li>
<li><a href="#Python_nn64">Pointer handling</a></li>
<li><a href="#Python_memory_management_member_variables">Memory
 management when returning references to member variables</a></li>
</ul>
</li>
<li><a href="#Python_nn65">Docstring Features</a>
<ul>
<li><a href="#Python_nn66">Module docstring</a></li>
<li><a href="#Python_nn67">%feature(&quot;autodoc&quot;)</a>
<ul>
<li><a href="#Python_nn68">%feature(&quot;autodoc&quot;, &quot;0&quot;)</a></li>
<li><a href="#Python_nn69">%feature(&quot;autodoc&quot;, &quot;1&quot;)</a></li>
<li><a href="#Python_autodoc2">%feature(&quot;autodoc&quot;, &quot;2&quot;)</a></li>
<li><a href="#Python_autodoc3">%feature(&quot;autodoc&quot;, &quot;3&quot;)</a></li>
<li><a href="#Python_nn70">%feature(&quot;autodoc&quot;, &quot;docstring&quot;)</a></li>
</ul>
</li>
<li><a href="#Python_nn71">%feature(&quot;docstring&quot;)</a></li>
</ul>
</li>
<li><a href="#Python_nn72">Python Packages</a>
<ul>
<li><a href="#Python_modulepackage">Setting the Python package</a></li>
<li><a href="#Python_absrelimports">Absolute and relative imports</a></li>
<li><a href="#Python_absimport">Enforcing absolute import semantics</a></li>
<li><a href="#Python_importfrominit">Importing from __init__.py</a></li>
<li><a href="#Python_implicit_namespace_packages">Implicit namespace
 packages</a></li>
<li><a href="#Python_package_search">Location of modules</a>
<ul>
<li><a href="#Python_package_search_both_package_modules">Both modules
 in the same package</a></li>
<li><a href="#Python_package_search_both_global_modules">Both modules
 are global</a></li>
<li><a href="#Python_package_search_wrapper_split">Split modules custom
 configuration</a></li>
<li><a href="#Python_custom_module_import">More on customizing the
 module import code</a></li>
<li><a href="#Python_package_search_static">Statically linked C modules</a>
</li>
</ul>
</li>
</ul>
</li>
<li><a href="#Python_python3support">Python 3 Support</a>
<ul>
<li><a href="#Python_nn74">Function annotation</a></li>
<li><a href="#Python_nn75">Buffer interface</a></li>
<li><a href="#Python_nn76">Abstract base classes</a></li>
<li><a href="#Python_nn77">Byte string output conversion</a></li>
<li><a href="#Python_2_unicode">Python 2 Unicode</a></li>
</ul>
</li>
<li><a href="#Python_multithreaded">Support for Multithreaded
 Applications</a>
<ul>
<li><a href="#Python_thread_UI">UI for Enabling Multithreading Support</a>
</li>
<li><a href="#Python_thread_performance">Multithread Performance</a></li>
</ul>
</li>
</ul>
</div>
<!-- INDEX -->
<p><b> Caution: This chapter is under repair!</b></p>
<p> This chapter describes SWIG's support of Python. SWIG is compatible
 with all recent Python versions (Python 2.7 and Python &gt;= 3.2). If you
 still need to generate bindings which work with older versions of
 Python, you'll have to use SWIG 3.0.x.</p>
<p> This chapter covers most SWIG features, but certain low-level
 details are covered in less depth than in earlier chapters. At the very
 least, make sure you read the &quot;<a href="#SWIG">SWIG Basics</a>&quot;
 chapter.</p>
<h2><a name="Python_nn2">32.1 Overview</a></h2>
<p> To build Python extension modules, SWIG uses a layered approach in
 which parts of the extension module are defined in C and other parts
 are defined in Python. The C layer contains low-level wrappers whereas
 Python code is used to define high-level features.</p>
<p> This layered approach recognizes the fact that certain aspects of
 extension building are better accomplished in each language (instead of
 trying to do everything in C or C++). Furthermore, by generating code
 in both languages, you get a lot more flexibility since you can enhance
 the extension module with support code in either language.</p>
<p> In describing the Python interface, this chapter starts by covering
 the basics of configuration, compiling, and installing Python modules.
 Next, the Python interface to common C and C++ programming features is
 described. Advanced customization features such as typemaps are then
 described followed by a discussion of low-level implementation details.</p>
<h2><a name="Python_nn3">32.2 Preliminaries</a></h2>
<h3><a name="Python_nn4">32.2.1 Running SWIG</a></h3>
<p> Suppose that you defined a SWIG module such as the following:</p>
<div class="code">
<pre>
/* File: example.i */
%module example

%{
#define SWIG_FILE_WITH_INIT
#include &quot;example.h&quot;
%}

int fact(int n);
</pre>
</div>
<p> The <tt>#define SWIG_FILE_WITH_INIT</tt> line inserts a macro that
 specifies that the resulting C file should be built as a Python
 extension, inserting the module <tt>init</tt> code. This <tt>.i</tt>
 file wraps the following simple C file:</p>
<div class="code">
<pre>
/* File: example.c */

#include &quot;example.h&quot;

int fact(int n) {
  if (n &lt; 0) { /* This should probably return an error, but this is simpler */
    return 0;
  }
  if (n == 0) {
    return 1;
  } else {
    /* testing for overflow would be a good idea here */
    return n * fact(n-1);
  }
}

</pre>
</div>
<p> With the header file:</p>
<div class="code">
<pre>
/* File: example.h */

int fact(int n);
</pre>
</div>
<p> To build a Python module, run SWIG using the <tt>-python</tt>
 option:</p>
<div class="shell">
<pre>
$ swig -python example.i
</pre>
</div>
<p> If building a C++ extension, add the <tt>-c++</tt> option:</p>
<div class="shell">
<pre>
$ swig -c++ -python example.i
</pre>
</div>
<p> This creates two different files; a C/C++ source file <tt>
example_wrap.c</tt> or <tt>example_wrap.cxx</tt> and a Python source
 file <tt>example.py</tt>. The generated C source file contains the
 low-level wrappers that need to be compiled and linked with the rest of
 your C/C++ application to create an extension module. The Python source
 file contains high-level support code. This is the file that you will
 import to use the module.</p>
<p> The name of the wrapper file is derived from the name of the input
 file. For example, if the input file is <tt>example.i</tt>, the name of
 the wrapper file is <tt>example_wrap.c</tt>. To change this, you can
 use the <tt>-o</tt> option. The name of the Python file is derived from
 the module name specified with <tt>%module</tt>. If the module name is <tt>
example</tt>, then a file <tt>example.py</tt> is created.</p>
<p> The following sections have further practical examples and details
 on how you might go about compiling and using the generated files.</p>
<h3><a name="Python_nn6">32.2.2 Using distutils</a></h3>
<p> The preferred approach to building an extension module for Python is
 to compile it with distutils, which comes with all recent versions of
 Python (<a href="https://docs.python.org/3/library/distutils.html">
Distutils Docs</a>).</p>
<p> Distutils takes care of making sure that your extension is built
 with all the correct flags, headers, etc. for the version of Python it
 is run with. Distutils will compile your extension into a shared object
 file or DLL (<tt>.so</tt> on Linux, <tt>.pyd</tt> on Windows, etc). In
 addition, distutils can handle installing your package into
 site-packages, if that is desired. A configuration file (conventionally
 called: <tt>setup.py</tt>) describes the extension (and related Python
 modules). The distutils will then generate all the right compiler
 directives to build it for you.</p>
<p> Here is a sample <tt>setup.py</tt> file for the above example:</p>
<div class="code">
<pre>
#!/usr/bin/env python

&quot;&quot;&quot;
setup.py file for SWIG example
&quot;&quot;&quot;

from distutils.core import setup, Extension


example_module = Extension('_example',
                           sources=['example_wrap.c', 'example.c'],
                           )

setup (name = 'example',
       version = '0.1',
       author      = &quot;SWIG Docs&quot;,
       description = &quot;&quot;&quot;Simple swig example from docs&quot;&quot;&quot;,
       ext_modules = [example_module],
       py_modules = [&quot;example&quot;],
       )
</pre>
</div>
<p> In this example, the line: <tt>example_module = Extension(....)</tt>
 creates an Extension module object, defining the name as <tt>_example</tt>
, and using the source code files: <tt>example_wrap.c</tt>, generated by
 swig, and <tt>example.c</tt>, your original c source. The swig (and
 other Python extension modules) tradition is for the compiled extension
 to have the name of the Python portion, prefixed by an underscore. If
 the name of your Python module is &quot;<tt>example.py</tt>&quot;, then the name
 of the corresponding object file will be&quot;<tt>_example.so</tt>&quot;</p>
<p> The <tt>setup</tt> call then sets up distutils to build your
 package, defining some meta data, and passing in your extension module
 object. Once this is saved as <tt>setup.py</tt>, you can build your
 extension with these commands:</p>
<div class="shell">
<pre>
$ swig -python example.i
$ python setup.py build_ext --inplace
</pre>
</div>
<p> And a .so, or .pyd or... will be created for you. It will build a
 version that matches the Python that you run the command with. Taking
 apart the command line:</p>
<ul>
<li> <tt>python</tt> -- the version of Python you want to build for</li>
<li> <tt>setup.py</tt> -- the name of your setup script (it can be
 called anything, but setup.py is the tradition)</li>
<li> <tt>build_ext</tt> -- telling distutils to build extensions</li>
<li> <tt>--inplace</tt> -- this tells distutils to put the extension lib
 in the current dir. Otherwise, it will put it inside a build hierarchy,
 and you'd have to move it to use it.</li>
</ul>
<p> The distutils have many other features, consult the Python distutils
 docs for details.</p>
<p> This same approach works on all platforms if the appropriate
 compiler is installed. (it can even build extensions to the standard
 Windows Python using MingGW)</p>
<h3><a name="Python_nn7">32.2.3 Hand compiling a dynamic module</a></h3>
<p> While the preferred approach to building an extension module is to
 use the distutils, some people like to integrate building extensions
 with a larger build system, and thus may wish to compile their modules
 without the distutils. To do this, you need to compile your program
 using commands like this (shown for Linux):</p>
<div class="shell">
<pre>
$ swig -python example.i
$ gcc -O2 -fPIC -c example.c
$ gcc -O2 -fPIC -c example_wrap.c -I/usr/local/include/python2.5
$ gcc -shared example.o example_wrap.o -o _example.so
</pre>
</div>
<p> The exact commands for doing this vary from platform to platform.
 However, SWIG tries to guess the right options when it is installed.
 Therefore, you may want to start with one of the examples in the <tt>
SWIG/Examples/python</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="https://github.com/swig/swig/wiki">
SWIG Wiki</a> for additional information.</p>
<p> When linking the module,<b> the name of the output file has to match
 the name of the module prefixed by an underscore</b>. If the name of
 your module is &quot;<tt>example</tt>&quot;, then the name of the corresponding
 object file should be &quot;<tt>_example.so</tt>&quot; or &quot;<tt>_examplemodule.so</tt>
&quot;. The name of the module is specified using the <tt>%module</tt>
 directive or the <tt>-module</tt> command line option.</p>
<p><b> Compatibility Note:</b> In SWIG-1.3.13 and earlier releases,
 module names did not include the leading underscore. This is because
 modules were normally created as C-only extensions without the extra
 Python support file (instead, creating Python code was supported as an
 optional feature). This has been changed in SWIG-1.3.14 and is
 consistent with other Python extension modules. For example, the <tt>
socket</tt> module actually consists of two files; <tt>socket.py</tt>
 and <tt>_socket.so</tt>. Many other built-in Python modules follow a
 similar convention.</p>
<h3><a name="Python_nn8">32.2.4 Static linking</a></h3>
<p> An alternative approach to dynamic linking is to rebuild the Python
 interpreter with your extension module added to it. In the past, this
 approach was sometimes necessary due to limitations in dynamic loading
 support on certain machines. However, the situation has improved
 greatly over the last few years and you should not consider this
 approach unless there is really no other option.</p>
<p> The usual procedure for adding a new module to Python involves
 finding the Python source, adding an entry to the <tt>Modules/Setup</tt>
 file, and rebuilding the interpreter using the Python Makefile.
 However, newer Python versions have changed the build process. You may
 need to edit the 'setup.py' file in the Python distribution instead.</p>
<p> In earlier versions of SWIG, the <tt>embed.i</tt> library file could
 be used to rebuild the interpreter. For example:</p>
<div class="code">
<pre>
%module example

%inline %{
extern int fact(int);
extern int mod(int, int);
extern double My_variable;
%}

%include &quot;embed.i&quot;       // Include code for a static version of Python

</pre>
</div>
<p> The <tt>embed.i</tt> library file includes supporting code that
 contains everything needed to rebuild Python. To rebuild the
 interpreter, you simply do something like this:</p>
<div class="shell">
<pre>
$ swig -python -lembed.i example.i
$ gcc example.c example_wrap.c \
        -Xlinker -export-dynamic \
        -DHAVE_CONFIG_H -I/usr/include/python2.7 \
        -I/usr/lib/python2.7/config-x86_64-linux-gnu \
        -I/usr/lib/python2.7/config \
        -L/usr/lib/python2.7/config -lpython2.7 -lm -ldl \
        -o mypython
</pre>
</div>
<p> You will need to supply the same libraries that were used to build
 Python the first time. This may include system libraries such as <tt>
-lsocket</tt>, <tt>-lnsl</tt>, and <tt>-lpthread</tt>. Assuming this
 actually works, the new version of Python should be identical to the
 default version except that your extension module will be a built-in
 part of the interpreter.</p>
<p><b> Comment:</b> In practice, you should probably try to avoid static
 linking if possible. Some programmers may be inclined to use static
 linking in the interest of getting better performance. However, the
 performance gained by static linking tends to be rather minimal in most
 situations (and quite frankly not worth the extra hassle in the opinion
 of this author).</p>
<p><b> Compatibility note:</b> The <tt>embed.i</tt> library file is
 deprecated and has not been actively maintained for many years. Even
 though it appears to &quot;work&quot; with Python 2.7, no future support is
 guaranteed. If using static linking, you might want to rely on a
 different approach (perhaps using distutils).</p>
<h3><a name="Python_nn9">32.2.5 Using your module</a></h3>
<p> To use your module, simply use the Python <tt>import</tt> statement.
 If all goes well, you will be able to run this:</p>
<div class="targetlang">
<pre>
$ python
&gt;&gt;&gt; import example
&gt;&gt;&gt; example.fact(4)
24
&gt;&gt;&gt;
</pre>
</div>
<p> A common error received by first-time users is the following:</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; import example
Traceback (most recent call last):
  File &quot;&lt;stdin&gt;&quot;, line 1, in ?
  File &quot;example.py&quot;, line 2, in ?
    import _example
ImportError: No module named _example
</pre>
</div>
<p> If you get this message, it means that you either forgot to compile
 the wrapper code into an extension module or you didn't give the
 extension module the right name. Make sure that you compiled the
 wrappers into a module called <tt>_example.so</tt>. And don't forget
 the leading underscore (_).</p>
<p> Another possible error is the following:</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; import example
Traceback (most recent call last):
  File &quot;&lt;stdin&gt;&quot;, line 1, in ?
ImportError: dynamic module does not define init function (init_example)
&gt;&gt;&gt;
</pre>
</div>
<p> This error is almost always caused when a bad name is given to the
 shared object file. For example, if you created a file <tt>example.so</tt>
 instead of <tt>_example.so</tt> you would get this error.
 Alternatively, this error could arise if the name of the module is
 inconsistent with the module name supplied with the <tt>%module</tt>
 directive. Double-check the interface to make sure the module name and
 the shared object filename match. Another possible cause of this error
 is forgetting to link the SWIG-generated wrapper code with the rest of
 your application when creating the extension module.</p>
<p> Another common error is something similar to the following:</p>
<div class="targetlang">
<pre>
Traceback (most recent call last):
  File &quot;example.py&quot;, line 3, in ?
    import example
ImportError: ./_example.so: undefined symbol: fact
</pre>
</div>
<p> This error usually indicates that you forgot to include some object
 files or libraries in the linking of the shared library file. Make sure
 you compile both the SWIG wrapper file and your original program into a
 shared library file. Make sure you pass all of the required libraries
 to the linker.</p>
<p> Sometimes unresolved symbols occur because a wrapper has been
 created for a function that doesn't actually exist in a library. This
 usually occurs when a header file includes a declaration for a function
 that was never actually implemented or it was removed from a library
 without updating the header file. To fix this, you can either edit the
 SWIG input file to remove the offending declaration or you can use the <tt>
%ignore</tt> directive to ignore the declaration.</p>
<p> Finally, suppose that your extension module is linked with another
 library like this:</p>
<div class="shell">
<pre>
$ gcc -shared example.o example_wrap.o -L/home/beazley/projects/lib <b>-lfoo</b> \
      -o _example.so
</pre>
</div>
<p> If the <tt>foo</tt> library is compiled as a shared library, you
 might encounter the following problem when you try to use your module:</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; import example
Traceback (most recent call last):
  File &quot;&lt;stdin&gt;&quot;, line 1, in ?
ImportError: libfoo.so: cannot open shared object file: No such file or directory
&gt;&gt;&gt;
</pre>
</div>
<p> This error is generated because the dynamic linker can't locate the <tt>
libfoo.so</tt> library. When shared libraries are loaded, the system
 normally only checks a few standard locations such as <tt>/usr/lib</tt>
 and <tt>/usr/local/lib</tt>. To fix this problem, there are several
 things you can do. First, you can recompile your extension module with
 extra path information. For example, on Linux you can do this:</p>
<div class="shell">
<pre>
$ gcc -shared example.o example_wrap.o -L/home/beazley/projects/lib -lfoo \
      <b>-Xlinker -rpath /home/beazley/projects/lib </b> \
      -o _example.so
</pre>
</div>
<p> Alternatively, you can set the <tt>LD_LIBRARY_PATH</tt> environment
 variable to include the directory with your shared libraries. If
 setting <tt>LD_LIBRARY_PATH</tt>, be aware that setting this variable
 can introduce a noticeable performance impact on all other applications
 that you run. To set it only for Python, you might want to do this
 instead:</p>
<div class="shell">
<pre>
$ env LD_LIBRARY_PATH=/home/beazley/projects/lib python
</pre>
</div>
<p> Finally, you can 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>
<h3><a name="Python_nn10">32.2.6 Compilation of C++ extensions</a></h3>
<p> Compilation of C++ extensions has traditionally been a tricky
 problem. Since the Python interpreter is written in C, you need to take
 steps to make sure C++ is properly initialized and that modules are
 compiled correctly. This should be a non-issue if you're using
 distutils, as it takes care of all that for you. The following is
 included for historical reasons, and in case you need to compile on
 your own.</p>
<p> On most machines, C++ extension modules should be linked using the
 C++ compiler. For example:</p>
<div class="shell">
<pre>
$ swig -c++ -python example.i
$ g++ -O2 -fPIC -c example.cxx
$ g++ -O2 -fPIC -c example_wrap.cxx -I/usr/local/include/python2.5
$ g++ -shared example.o example_wrap.o -o _example.so
</pre>
</div>
<p> The -fPIC option tells GCC to generate position-independent code
 (PIC) which is required for most architectures (it's not vital on x86,
 but still a good idea as it allows code pages from the library to be
 shared between processes). Other compilers may need a different option
 specified instead of -fPIC.</p>
<p> In addition to this, you may need to include additional library
 files to make it work. For example, if you are using the Sun C++
 compiler on Solaris, you often need to add an extra library <tt>-lCrun</tt>
 like this:</p>
<div class="shell">
<pre>
$ swig -c++ -python example.i
$ CC -c example.cxx
$ CC -c example_wrap.cxx -I/usr/local/include/python2.5
$ CC -G example.o example_wrap.o -L/opt/SUNWspro/lib -o _example.so -lCrun
</pre>
</div>
<p> Of course, the extra libraries to use are completely
 non-portable---you will probably need to do some experimentation.</p>
<p> Sometimes people have suggested that it is necessary to relink the
 Python interpreter using the C++ compiler to make C++ extension modules
 work. In the experience of this author, this has never actually
 appeared to be necessary. Relinking the interpreter with C++ really
 only includes the special run-time libraries described above---as long
 as you link your extension modules with these libraries, it should not
 be necessary to rebuild Python.</p>
<p> If you aren't entirely sure about the linking of a C++ extension,
 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
 extension module. For example:</p>
<div class="shell">
<pre>
$ ldd swig
        libstdc++-libc6.1-1.so.2 =&gt; /usr/lib/libstdc++-libc6.1-1.so.2 (0x40019000)
        libm.so.6 =&gt; /lib/libm.so.6 (0x4005b000)
        libc.so.6 =&gt; /lib/libc.so.6 (0x40077000)
        /lib/ld-linux.so.2 =&gt; /lib/ld-linux.so.2 (0x40000000)
</pre>
</div>
<p> As a final complication, a major weakness of C++ is that it does not
 define any sort of standard for binary linking of libraries. This means
 that C++ code compiled by different compilers will not link together
 properly as libraries nor is the memory layout of classes and data
 structures implemented in any kind of portable manner. In a monolithic
 C++ program, this problem may be unnoticed. However, in Python, it is
 possible for different extension modules to be compiled with different
 C++ compilers. As long as these modules are self-contained, this
 probably won't matter. However, if these modules start sharing data,
 you will need to take steps to avoid segmentation faults and other
 erratic program behavior. If working with lots of software components,
 you might want to investigate using a more formal standard such as COM.</p>
<h3><a name="Python_nn11">32.2.7 Compiling for 64-bit platforms</a></h3>
<p> On platforms that support 64-bit applications (Solaris, Irix, etc.),
 special care is required when building extension modules. On these
 machines, 64-bit applications are compiled and linked using a different
 set of compiler/linker options. In addition, it is not generally
 possible to mix 32-bit and 64-bit code together in the same
 application.</p>
<p> To utilize 64-bits, the Python executable will need to be recompiled
 as a 64-bit application. In addition, all libraries, wrapper code, and
 every other part of your application will need to be compiled for
 64-bits. If you plan to use other third-party extension modules, they
 will also have to be recompiled as 64-bit extensions.</p>
<p> If you are wrapping commercial software for which you have no source
 code, you will be forced to use the same linking standard as used by
 that software. This may prevent the use of 64-bit extensions. It may
 also introduce problems on platforms that support more than one linking
 standard (e.g., -o32 and -n32 on Irix).</p>
<p> On the Linux x86_64 platform (Opteron or EM64T), besides of the
 required compiler option -fPIC discussed above, you will need to be
 careful about the libraries you link with or the library path you use.
 In general, a Linux distribution will have two set of libraries, one
 for native x86_64 programs (under /usr/lib64), and another for 32 bits
 compatibility (under /usr/lib). Also, the compiler options -m32 and
 -m64 allow you to choose the desired binary format for your Python
 extension.</p>
<h3><a name="Python_nn12">32.2.8 Building Python extensions under
 Windows</a></h3>
<p> Building a SWIG extension to Python under Windows is roughly similar
 to the process used with Unix. Using the distutils, it is essentially
 identical. If you have the same version of the MS compiler that Python
 was built with (the python2.4 and python2.5 distributed by python.org
 are built with Visual Studio 2003), the standard <tt>python setup.py
 build</tt> should just work.</p>
<p> As of python2.5, the distutils support building extensions with
 MingGW out of the box. Following the instruction here: <a href="http://boodebr.org/main/python/build-windows-extensions">
Building Python extensions for Windows with only free tools</a> should
 get you started.</p>
<p> If you need to build it on your own, the following notes are
 provided:</p>
<p> You will need to create a DLL that can be loaded into the
 interpreter. This section briefly describes the use of SWIG with
 Microsoft Visual C++. As a starting point, many of SWIG's examples
 include project files (.dsp files) for Visual C++ 6. These can be
 opened by more recent versions of Visual Studio. You might want to take
 a quick look at these examples in addition to reading this section.</p>
<p> In Developer Studio, SWIG should be invoked as a custom build
 option. This is usually done as follows:</p>
<ul>
<li>Open up a new workspace and use the AppWizard to select a DLL
 project.</li>
<li>Add both the SWIG interface file (the .i file), any supporting C
 files, and the name of the wrapper file that will be created by SWIG
 (ie. <tt>example_wrap.c</tt>). Note : If using C++, choose a different
 suffix for the wrapper file such as <tt>example_wrap.cxx</tt>. Don't
 worry if the wrapper file doesn't exist yet--Developer Studio keeps a
 reference to it.</li>
<li>Select the SWIG interface file and go to the settings menu. Under
 settings, select the &quot;Custom Build&quot; option.</li>
<li>Enter &quot;SWIG&quot; in the description field.</li>
<li>Enter &quot;<tt>swig -python -o $(ProjDir)\$(InputName)_wrap.c
 $(InputPath)</tt>&quot; in the &quot;Build command(s) field&quot;</li>
<li>Enter &quot;<tt>$(ProjDir)\$(InputName)_wrap.c</tt>&quot; in the &quot;Output
 files(s) field&quot;.</li>
<li>Next, select the settings for the entire project and go to
 &quot;C++:Preprocessor&quot;. Add the include directories for your Python
 installation under &quot;Additional include directories&quot;.</li>
<li>Define the symbol __WIN32__ under preprocessor options.</li>
<li>Finally, select the settings for the entire project and go to &quot;Link
 Options&quot;. Add the Python library file to your link libraries. For
 example &quot;python27.lib&quot;. Also, set the name of the output file to match
 the name of your Python module, i.e. <tt>_example.pyd</tt></li>
<li>Build your project.</li>
</ul>
<p> If all went well, SWIG will be automatically invoked whenever you
 build your project. Any changes made to the interface file will result
 in SWIG being automatically executed to produce a new version of the
 wrapper file.</p>
<p> To run your new Python extension, simply run Python and use the <tt>
import</tt> command as normal. For example :</p>
<div class="targetlang">
<pre>
$ python
&gt;&gt;&gt; import example
&gt;&gt;&gt; print example.fact(4)
24
&gt;&gt;&gt;
</pre>
</div>
<p> If you get an <tt>ImportError</tt> exception when importing the
 module, you may have forgotten to include additional library files when
 you built your module. If you get an access violation or some kind of
 general protection fault immediately upon import, you have a more
 serious problem. This is often caused by linking your extension module
 against the wrong set of Win32 debug or thread libraries. You will have
 to fiddle around with the build options of project to try and track
 this down.</p>
<p> A 'Debug' build of the wrappers requires a debug build of the Python
 interpreter. This normally requires building the Python interpreter
 from source, which is not a job for the feint-hearted. Alternatively
 you can use the 'Release' build of the Python interpreter with a
 'Debug' build of your wrappers by defining the <tt>
SWIG_PYTHON_INTERPRETER_NO_DEBUG</tt> symbol under the preprocessor
 options. Or you can ensure this macro is defined at the beginning of
 the wrapper code using the following in your interface file, where <tt>
_MSC_VER</tt> ensures it is only used by the Visual Studio compiler:</p>
<div class="code">
<pre>
%begin %{
#ifdef _MSC_VER
#define SWIG_PYTHON_INTERPRETER_NO_DEBUG
#endif
%}
</pre>
</div>
<p> Some users have reported success in building extension modules using
 Cygwin and other compilers. However, the problem of building usable
 DLLs with these compilers tends to be rather problematic. For the
 latest information, you may want to consult the <a href="https://github.com/swig/swig/wiki">
 SWIG Wiki</a>.</p>
<h3><a name="Python_commandline">32.2.9 Additional Python commandline
 options</a></h3>
<p> The following table lists the additional commandline options
 available for the Python module. They can also be seen by using:</p>
<div class="code">
<pre>
swig -python -help
</pre>
</div>
<table summary="Python specific options">
<tr><th>Python specific options</th></tr>
<tr><td>-builtin</td><td>Create Python built-in types rather than proxy
 classes, for better performance</td></tr>
<tr><td>-castmode</td><td>Enable the casting mode, which allows implicit
 cast between types in Python</td></tr>
<tr><td>-debug-doxygen-parser</td><td>Display doxygen parser module
 debugging information</td></tr>
<tr><td>-debug-doxygen-translator</td><td>Display doxygen translator
 module debugging information</td></tr>
<tr><td>-dirvtable</td><td>Generate a pseudo virtual table for directors
 for faster dispatch</td></tr>
<tr><td>-doxygen</td><td>Convert C++ doxygen comments to pydoc comments
 in proxy classes</td></tr>
<tr><td>-extranative</td><td>Return extra native wrappers for C++ std
 containers wherever possible</td></tr>
<tr><td>-fastproxy</td><td>Use fast proxy mechanism for member methods</td>
</tr>
<tr><td>-globals &lt;name&gt;</td><td>Set &lt;name&gt; used to access C global
 variable (default: 'cvar')</td></tr>
<tr><td>-interface &lt;mod&gt;</td><td>Set low-level C/C++ module name to
 &lt;mod&gt; (default: module name prefixed by '_')</td></tr>
<tr><td>-keyword</td><td>Use keyword arguments</td></tr>
<tr><td>-nofastunpack</td><td>Use traditional UnpackTuple method to
 parse the argument functions</td></tr>
<tr><td>-noh</td><td>Don't generate the output header file</td></tr>
<tr><td>-noproxy</td><td>Don't generate proxy classes</td></tr>
<tr><td>-nortti</td><td>Disable the use of the native C++ RTTI with
 directors</td></tr>
<tr><td>-nothreads</td><td>Disable thread support for the entire
 interface</td></tr>
<tr><td>-olddefs</td><td>Keep the old method definitions when using
 -fastproxy</td></tr>
<tr><td>-py3</td><td>Generate code with Python 3 specific features and
 syntax</td></tr>
<tr><td>-relativeimport</td><td>Use relative Python imports</td></tr>
<tr><td>-threads</td><td>Add thread support for all the interface</td></tr>
<tr><td>-O</td><td>Enable the following optimization options:
 -fastdispatch -fastproxy -fvirtual</td></tr>
</table>
<p> Many of these options are covered later on and their use should
 become clearer by the time you have finished reading this section on
 SWIG and Python.</p>
<h2><a name="Python_nn13">32.3 A tour of basic C/C++ wrapping</a></h2>
<p> By default, SWIG tries to build a very natural Python interface to
 your C/C++ code. Functions are wrapped as functions, classes are
 wrapped as classes, and so forth. This section briefly covers the
 essential aspects of this wrapping.</p>
<h3><a name="Python_nn14">32.3.1 Modules</a></h3>
<p> The SWIG <tt>%module</tt> directive specifies the name of the Python
 module. If you specify `<tt>%module example</tt>', then everything is
 wrapped into a Python '<tt>example</tt>' module. Underneath the covers,
 this module consists of a Python source file <tt>example.py</tt> and a
 low-level extension module <tt>_example.so</tt>. When choosing a module
 name, make sure you don't use the same name as a built-in Python
 command or standard module name.</p>
<h3><a name="Python_nn15">32.3.2 Functions</a></h3>
<p> Global functions are wrapped as new Python built-in functions. For
 example,</p>
<div class="code">
<pre>
%module example
int fact(int n);
</pre>
</div>
<p> creates a built-in function <tt>example.fact(n)</tt> that works
 exactly like you think it does:</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; import example
&gt;&gt;&gt; print example.fact(4)
24
&gt;&gt;&gt;
</pre>
</div>
<h3><a name="Python_nn16">32.3.3 Global variables</a></h3>
<p> C/C++ global variables are fully supported by SWIG. However, the
 underlying mechanism is somewhat different than you might expect due to
 the way that Python assignment works. When you type the following in
 Python</p>
<div class="targetlang">
<pre>
a = 3.4
</pre>
</div>
<p> &quot;a&quot; becomes a name for an object containing the value 3.4. If you
 later type</p>
<div class="targetlang">
<pre>
b = a
</pre>
</div>
<p> then &quot;a&quot; and &quot;b&quot; are both names for the object containing the value
 3.4. Thus, there is only one object containing 3.4 and &quot;a&quot; and &quot;b&quot; are
 both names that refer to it. This is quite different than C where a
 variable name refers to a memory location in which a value is stored
 (and assignment copies data into that location). Because of this, there
 is no direct way to map variable assignment in C to variable assignment
 in Python.</p>
<p> To provide access to C global variables, SWIG creates a special
 object called `<tt>cvar</tt>' that is added to each SWIG generated
 module. Global variables are then accessed as attributes of this
 object. For example, consider this interface</p>
<div class="code">
<pre>
// SWIG interface file with global variables
%module example
...
%inline %{
extern int My_variable;
extern double density;
%}
...
</pre>
</div>
<p> Now look at the Python interface:</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; import example
&gt;&gt;&gt; # Print out value of a C global variable
&gt;&gt;&gt; print example.cvar.My_variable
4
&gt;&gt;&gt; # Set the value of a C global variable
&gt;&gt;&gt; example.cvar.density = 0.8442
&gt;&gt;&gt; # Use in a math operation
&gt;&gt;&gt; example.cvar.density = example.cvar.density*1.10
</pre>
</div>
<p> If you make an error in variable assignment, you will receive an
 error message. For example:</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; example.cvar.density = &quot;Hello&quot;
Traceback (most recent call last):
  File &quot;&lt;stdin&gt;&quot;, line 1, in ?
TypeError: C variable 'density (double )'
&gt;&gt;&gt;
</pre>
</div>
<p> If a variable is declared as <tt>const</tt>, it is wrapped as a
 read-only variable. Attempts to modify its value will result in an
 error.</p>
<p> To make ordinary variables read-only, you can use the <tt>%immutable</tt>
 directive. For example:</p>
<div class="code">
<pre>
%{
extern char *path;
%}
%immutable;
extern char *path;
%mutable;
</pre>
</div>
<p> The <tt>%immutable</tt> directive stays in effect until it is
 explicitly disabled or cleared using <tt>%mutable</tt>. See the <a href="#SWIG_readonly_variables">
Creating read-only variables</a> section for further details.</p>
<p> If you just want to make a specific variable immutable, supply a
 declaration name. For example:</p>
<div class="code">
<pre>
%{
extern char *path;
%}
%immutable path;
...
extern char *path;      // Read-only (due to %immutable)
</pre>
</div>
<p> If you would like to access variables using a name other than &quot;<tt>
cvar</tt>&quot;, it can be changed using the <tt>-globals</tt> option :</p>
<div class="shell">
<pre>
$ swig -python -globals myvar example.i
</pre>
</div>
<p> Some care is in order when importing multiple SWIG modules. If you
 use the &quot;<tt>from &lt;file&gt; import *</tt>&quot; style of importing, you will
 get a name clash on the variable `<tt>cvar</tt>' and you will only be
 able to access global variables from the last module loaded. To prevent
 this, you might consider renaming <tt>cvar</tt> or making it private to
 the module by giving it a name that starts with a leading underscore.
 SWIG does not create <tt>cvar</tt> if there are no global variables in
 a module.</p>
<h3><a name="Python_nn17">32.3.4 Constants and enums</a></h3>
<p> C/C++ constants are installed as Python objects containing the
 appropriate value. To create a constant, use <tt>#define</tt>, <tt>enum</tt>
, or the <tt>%constant</tt> directive. For example:</p>
<div class="code">
<pre>
#define PI 3.14159
#define VERSION &quot;1.0&quot;

enum Beverage { ALE, LAGER, STOUT, PILSNER };

%constant int FOO = 42;
%constant const char *path = &quot;/usr/local&quot;;
</pre>
</div>
<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
 stick an enum in a SWIG interface without also telling the C compiler
 about it, the wrapper code won't compile.</p>
<p> Note: declarations declared as <tt>const</tt> are wrapped as
 read-only variables and will be accessed using the <tt>cvar</tt> object
 described in the previous section. They are not wrapped as constants.
 For further discussion about this, see the <a href="#SWIG">SWIG Basics</a>
 chapter.</p>
<p> Constants are not guaranteed to remain constant in Python---the name
 of the constant could be accidentally reassigned to refer to some other
 object. Unfortunately, there is no easy way for SWIG to generate code
 that prevents this. You will just have to be careful.</p>
<h3><a name="Python_nn18">32.3.5 Pointers</a></h3>
<p> C/C++ pointers are fully supported by SWIG. Furthermore, SWIG has no
 problem working with incomplete type information. Here is a rather
 simple interface:</p>
<div class="code">
<pre>
%module example

FILE *fopen(const char *filename, const char *mode);
int fputs(const char *, FILE *);
int fclose(FILE *);
</pre>
</div>
<p> When wrapped, you will be able to use the functions in a natural way
 from Python. For example:</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; import example
&gt;&gt;&gt; f = example.fopen(&quot;junk&quot;, &quot;w&quot;)
&gt;&gt;&gt; example.fputs(&quot;Hello World\n&quot;, f)
&gt;&gt;&gt; example.fclose(f)
</pre>
</div>
<p> If this makes you uneasy, rest assured that there is no deep magic
 involved. Underneath the covers, pointers to C/C++ objects are simply
 represented as opaque values using an especial Python container object:</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; print f
&lt;Swig Object of type 'FILE *' at 0xb7d6f470&gt;
</pre>
</div>
<p> This pointer value can be freely passed around to different C
 functions that expect to receive an object of type <tt>FILE *</tt>. The
 only thing you can't do is dereference the pointer from Python. Of
 course, that isn't much of a concern in this example.</p>
<p> In older versions of SWIG (1.3.22 or older), pointers were
 represented using a plain string object. If you have an old package
 that still requires that representation, or you just feel nostalgic,
 you can always retrieve it by casting the pointer object to a string:</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; print str(f)
_c0671108_p_FILE
</pre>
</div>
<p> Also, if you need to pass the raw pointer value to some external
 Python library, you can do it by casting the pointer object to an
 integer:</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; print int(f)
135833352
</pre>
</div>
<p> However, the inverse operation is not possible, i.e., you can't
 build a SWIG pointer object from a raw integer value.</p>
<p> Note also that the '0' or NULL pointer is always represented by <tt>
None</tt>, no matter what type swig is addressing. In the previous
 example, you can call:</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; example.fclose(None)
</pre>
</div>
<p> and that will be equivalent to the following, but not really useful,
 C code:</p>
<div class="code">
<pre>
FILE *f = NULL;
fclose(f);
</pre>
</div>
<p> As much as you might be inclined to modify a pointer value directly
 from Python, don't. The hexadecimal encoding is not necessarily the
 same as the logical memory address of the underlying object. Instead it
 is the raw byte encoding of the pointer value. The encoding will vary
 depending on the native byte-ordering of the platform (i.e., big-endian
 vs. little-endian). Similarly, don't try to manually cast a pointer to
 a new type by simply replacing the type-string. This may not work like
 you expect, it is particularly dangerous when casting C++ objects. If
 you need to cast a pointer or change its value, consider writing some
 helper functions instead. For example:</p>
<div class="code">
<pre>
%inline %{
/* C-style cast */
Bar *FooToBar(Foo *f) {
  return (Bar *) f;
}

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

Foo *IncrFoo(Foo *f, int i) {
  return f+i;
}
%}
</pre>
</div>
<p> Also, if working with C++, you should always try to use the new C++
 style casts. For example, in the above code, the C-style cast may
 return a bogus result whereas as the C++-style cast will return <tt>
None</tt> if the conversion can't be performed.</p>
<h3><a name="Python_nn19">32.3.6 Structures</a></h3>
<p> If you wrap a C structure, it is wrapped by a Python class. This
 provides a very natural interface. For example,</p>
<div class="code">
<pre>
struct Vector {
  double x, y, z;
};

</pre>
</div>
<p> is used as follows:</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; v = example.Vector()
&gt;&gt;&gt; v.x = 3.5
&gt;&gt;&gt; v.y = 7.2
&gt;&gt;&gt; print v.x, v.y, v.z
3.5 7.2 0.0
&gt;&gt;&gt;
</pre>
</div>
<p> Similar access is provided for unions and the data members of C++
 classes.</p>
<p> If you print out the value of <tt>v</tt> in the above example, you
 will see something like this:</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; print v
&lt;C Vector instance at _18e31408_p_Vector&gt;
</pre>
</div>
<p> This object is actually a Python instance that has been wrapped
 around a pointer to the low-level C structure. This instance doesn't
 actually do anything--it just serves as a proxy. The pointer to the C
 object can be found in the <tt>.this</tt> attribute. For example:</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; print v.this
_18e31408_p_Vector
&gt;&gt;&gt;
</pre>
</div>
<p> Further details about the Python proxy class are covered a little
 later.</p>
<p> <tt>const</tt> members of a structure are read-only. Data members
 can also be forced to be read-only using the <tt>%immutable</tt>
 directive. For example:</p>
<div class="code">
<pre>
struct Foo {
  ...
  %immutable;
  int x;        /* Read-only members */
  char *name;
  %mutable;
  ...
};
</pre>
</div>
<p> When <tt>char *</tt> members of a structure are wrapped, the
 contents are assumed to be dynamically allocated using <tt>malloc</tt>
 or <tt>new</tt> (depending on whether or not SWIG is run with the -c++
 option). When the structure member is set, the old contents will be
 released and a new value created. If this is not the behavior you want,
 you will have to use a typemap (described later).</p>
<p> If a structure contains arrays, access to those arrays is managed
 through pointers. For example, consider this:</p>
<div class="code">
<pre>
struct Bar {
  int  x[16];
};
</pre>
</div>
<p> If accessed in Python, you will see behavior like this:</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; b = example.Bar()
&gt;&gt;&gt; print b.x
_801861a4_p_int
&gt;&gt;&gt;
</pre>
</div>
<p> This pointer can be passed around to functions that expect to
 receive an <tt>int *</tt> (just like C). You can also set the value of
 an array member using another pointer. For example:</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; c = example.Bar()
&gt;&gt;&gt; c.x = b.x             # Copy contents of b.x to c.x
</pre>
</div>
<p> For array assignment, 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.</p>
<p> When a member of a structure is itself a structure, it is handled as
 a pointer. For example, suppose you have two structures like this:</p>
<div class="code">
<pre>
struct Foo {
  int a;
};

struct Bar {
  Foo f;
};
</pre>
</div>
<p> Now, suppose that you access the <tt>f</tt> attribute of <tt>Bar</tt>
 like this:</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; b = Bar()
&gt;&gt;&gt; x = b.f
</pre>
</div>
<p> In this case, <tt>x</tt> is a pointer that points to the <tt>Foo</tt>
 that is inside <tt>b</tt>. This is the same value as generated by this
 C code:</p>
<div class="code">
<pre>
Bar b;
Foo *x = &amp;b-&gt;f;       /* Points inside b */
</pre>
</div>
<p> Because the pointer points inside the structure, you can modify the
 contents and everything works just like you would expect. For example:</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; b = Bar()
&gt;&gt;&gt; b.f.a = 3               # Modify attribute of structure member
&gt;&gt;&gt; x = b.f
&gt;&gt;&gt; x.a = 3                 # Modifies the same structure
</pre>
</div>
<p> Note that there is a limitation with structs within structs that
 will cause a problem if the outer struct is not a named variable in
 Python. The following will cause a segfault:</p>
<div class="targetlang">
<pre>
Bar().f.a = 3
</pre>
</div>
<p> because the unnamed Python proxy class for <tt>Bar()</tt> has its
 reference count decremented by the Python interpreter after <tt>f</tt>
 has been obtained from it and before <tt>f</tt> is used to obtain <tt>a</tt>
. This results in the underlying <tt>Bar</tt> instance being deleted,
 which of course also deletes <tt>f</tt> inside it. Hence the pointer to
 <tt>f</tt> points to deleted memory and use of it results in a segfault
 or some sort of other undefined behaviour.</p>
<h3><a name="Python_nn20">32.3.7 C++ classes</a></h3>
<p> C++ classes are wrapped by Python classes as well. For example, if
 you have this class,</p>
<div class="code">
<pre>
class List {
public:
  List();
  ~List();
  int  search(char *item);
  void insert(char *item);
  void remove(char *item);
  char *get(int n);
  int  length;
};
</pre>
</div>
<p> you can use it in Python like this:</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; l = example.List()
&gt;&gt;&gt; l.insert(&quot;Ale&quot;)
&gt;&gt;&gt; l.insert(&quot;Stout&quot;)
&gt;&gt;&gt; l.insert(&quot;Lager&quot;)
&gt;&gt;&gt; l.get(1)
'Stout'
&gt;&gt;&gt; print l.length
3
&gt;&gt;&gt;
</pre>
</div>
<p> Class data members are accessed in the same manner as C structures.</p>
<p> Static class members present a special problem for Python. Prior to
 Python-2.2, Python classes had no support for static methods and no
 version of Python supports static member variables in a manner that
 SWIG can utilize. Therefore, SWIG generates wrappers that try to work
 around some of these issues. To illustrate, suppose you have a class
 like this:</p>
<div class="code">
<pre>
class Spam {
public:
  static void foo();
  static int bar;
};
</pre>
</div>
<p> In Python, the static member can be access in three different ways:</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; example.Spam_foo()    # Spam::foo()
&gt;&gt;&gt; s = example.Spam()
&gt;&gt;&gt; s.foo()               # Spam::foo() via an instance
&gt;&gt;&gt; example.Spam.foo()    # Spam::foo(). Python-2.2 only
</pre>
</div>
<p> The first two methods of access are supported in all versions of
 Python. The last technique is only available in Python-2.2 and later
 versions.</p>
<p> Static member variables are currently accessed as global variables.
 This means, they are accessed through <tt>cvar</tt> like this:</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; print example.cvar.Spam_bar
7
</pre>
</div>
<h3><a name="Python_nn21">32.3.8 C++ inheritance</a></h3>
<p> SWIG is fully aware of issues related to C++ inheritance. Therefore,
 if you have classes like this</p>
<div class="code">
<pre>
class Foo {
...
};

class Bar : public Foo {
...
};
</pre>
</div>
<p> those classes are wrapped into a hierarchy of Python classes that
 reflect the same inheritance structure. All of the usual Python utility
 functions work normally:</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; b = Bar()
&gt;&gt;&gt; instance(b, Foo)
1
&gt;&gt;&gt; issubclass(Bar, Foo)
1
&gt;&gt;&gt; issubclass(Foo, Bar)
0
</pre>
</div>
<p> Furthermore, if you have functions like this</p>
<div class="code">
<pre>
void spam(Foo *f);
</pre>
</div>
<p> then the function <tt>spam()</tt> accepts <tt>Foo *</tt> or a
 pointer to any class derived from <tt>Foo</tt>.</p>
<p> It is safe to use multiple inheritance with SWIG.</p>
<h3><a name="Python_nn22">32.3.9 Pointers, references, values, and
 arrays</a></h3>
<p> In C++, there are many different ways a function might receive and
 manipulate objects. For example:</p>
<div class="code">
<pre>
void spam1(Foo *x);      // Pass by pointer
void spam2(Foo &amp;x);      // Pass by reference
void spam3(const Foo &amp;x);// Pass by const reference
void spam4(Foo x);       // Pass by value
void spam5(Foo x[]);     // Array of objects
</pre>
</div>
<p> In Python, there is no detailed distinction like this--specifically,
 there are only &quot;objects&quot;. There are no pointers, references, arrays,
 and so forth. 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:</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; f = Foo()           # Create a Foo
&gt;&gt;&gt; spam1(f)            # Ok. Pointer
&gt;&gt;&gt; spam2(f)            # Ok. Reference
&gt;&gt;&gt; spam3(f)            # Ok. Const reference
&gt;&gt;&gt; spam4(f)            # Ok. Value.
&gt;&gt;&gt; spam5(f)            # Ok. Array (1 element)
</pre>
</div>
<p> Similar behavior occurs for return values. For example, if you had
 functions like this,</p>
<div class="code">
<pre>
Foo *spam6();
Foo &amp;spam7();
Foo  spam8();
const Foo &amp;spam9();
</pre>
</div>
<p> then all three functions will return a pointer to some <tt>Foo</tt>
 object. Since the third function (spam8) returns a value, newly
 allocated memory is used to hold the result and a pointer is returned
 (Python will release this memory when the return value is garbage
 collected). The fourth case (spam9) which returns a const reference, in
 most of the cases will be treated as a returning value, and it will
 follow the same allocation/deallocation process.</p>
<h3><a name="Python_nn23">32.3.10 C++ overloaded functions</a></h3>
<p> C++ overloaded functions, methods, and constructors are mostly
 supported by SWIG. For example, if you have two functions like this:</p>
<div class="code">
<pre>
void foo(int);
void foo(char *c);
</pre>
</div>
<p> You can use them in Python in a straightforward manner:</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; foo(3)           # foo(int)
&gt;&gt;&gt; foo(&quot;Hello&quot;)     # foo(char *c)
</pre>
</div>
<p> Similarly, if you have a class like this,</p>
<div class="code">
<pre>
class Foo {
public:
  Foo();
  Foo(const Foo &amp;);
  ...
};
</pre>
</div>
<p> you can write Python code like this:</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; f = Foo()          # Create a Foo
&gt;&gt;&gt; g = Foo(f)         # Copy f
</pre>
</div>
<p> Overloading support is not quite as flexible as in C++. Sometimes
 there are methods that SWIG can't disambiguate. For example:</p>
<div class="code">
<pre>
void spam(int);
void spam(short);
</pre>
</div>
<p> or</p>
<div class="code">
<pre>
void foo(Bar *b);
void foo(Bar &amp;b);
</pre>
</div>
<p> If declarations such as these appear, you will get a warning message
 like this:</p>
<div class="shell">
<pre>
example.i:12: Warning 509: Overloaded method spam(short) effectively ignored,
example.i:11: Warning 509: as it is shadowed by spam(int).
</pre>
</div>
<p> To fix this, you either need to ignore or rename one of the methods.
 For example:</p>
<div class="code">
<pre>
%rename(spam_short) spam(short);
...
void spam(int);
void spam(short);   // Accessed as spam_short
</pre>
</div>
<p> or</p>
<div class="code">
<pre>
%ignore spam(short);
...
void spam(int);
void spam(short);   // Ignored
</pre>
</div>
<p> SWIG resolves overloaded functions and methods using a
 disambiguation scheme that ranks and sorts declarations according to a
 set of type-precedence rules. The order in which declarations appear in
 the input does not matter except in situations where ambiguity
 arises--in this case, the first declaration takes precedence.</p>
<p> Please refer to the &quot;SWIG and C++&quot; chapter for more information
 about overloading.</p>
<h3><a name="Python_nn24">32.3.11 C++ operators</a></h3>
<p> Certain C++ overloaded operators can be handled automatically by
 SWIG. For example, consider a class like this:</p>
<div class="code">
<pre>
class Complex {
private:
  double rpart, ipart;
public:
  Complex(double r = 0, double i = 0) : rpart(r), ipart(i) { }
  Complex(const Complex &amp;c) : rpart(c.rpart), ipart(c.ipart) { }
  Complex &amp;operator=(const Complex &amp;c);

  Complex operator+=(const Complex &amp;c) const;
  Complex operator+(const Complex &amp;c) const;
  Complex operator-(const Complex &amp;c) const;
  Complex operator*(const Complex &amp;c) const;
  Complex operator-() const;

  double re() const { return rpart; }
  double im() const { return ipart; }
};
</pre>
</div>
<p> When wrapped, it works like you expect:</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; c = Complex(3, 4)
&gt;&gt;&gt; d = Complex(7, 8)
&gt;&gt;&gt; e = c + d
&gt;&gt;&gt; e.re()
10.0
&gt;&gt;&gt; e.im()
12.0
&gt;&gt;&gt; c += d
&gt;&gt;&gt; c.re()
10.0
&gt;&gt;&gt; c.im()
12.0

</pre>
</div>
<p> One restriction with operator overloading support is that SWIG is
 not able to fully handle operators that aren't defined as part of the
 class. For example, if you had code like this</p>
<div class="code">
<pre>
class Complex {
...
friend Complex operator+(double, const Complex &amp;c);
...
};
</pre>
</div>
<p> then SWIG ignores it and issues a warning. You can still wrap the
 operator, but you may have to encapsulate it in a special function. For
 example:</p>
<div class="code">
<pre>
%rename(Complex_add_dc) operator+(double, const Complex &amp;);
</pre>
</div>
<p> There are ways to make this operator appear as part of the class
 using the <tt>%extend</tt> directive. Keep reading.</p>
<p> Also, be aware that certain operators don't map cleanly to Python.
 For instance, overloaded assignment operators don't map to Python
 semantics and will be ignored.</p>
<p> Operator overloading is implemented in the <tt>pyopers.swg</tt>
 library file. In particular overloaded operators are marked with the <tt>
python:maybecall</tt> feature, also known as <tt>%pythonmaybecall</tt>.
 This feature forces SWIG to generate code that return an instance of
 Python's <tt>NotImplemented</tt> instead of raising an exception when
 the comparison fails, that is, on any kind of error. This follows the
 guidelines in <a href="https://www.python.org/dev/peps/pep-0207/">PEP
 207 - Rich Comparisons</a> and <a href="https://docs.python.org/3/library/constants.html#NotImplemented">
NotImplemented Python constant</a>.</p>
<h3><a name="Python_nn25">32.3.12 C++ namespaces</a></h3>
<p> 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,</p>
<div class="code">
<pre>
%module example

namespace foo {
  int fact(int n);
  struct Vector {
    double x, y, z;
  };
};
</pre>
</div>
<p> it works in Python as follows:</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; import example
&gt;&gt;&gt; example.fact(3)
6
&gt;&gt;&gt; v = example.Vector()
&gt;&gt;&gt; v.x = 3.4
&gt;&gt;&gt; print v.y
0.0
&gt;&gt;&gt;
</pre>
</div>
<p> If your program has more than one namespace, name conflicts (if any)
 can be resolved using <tt>%rename</tt> For example:</p>
<div class="code">
<pre>
%rename(Bar_spam) Bar::spam;

namespace Foo {
  int spam();
}

namespace Bar {
  int spam();
}
</pre>
</div>
<p> If you have more than one namespace and your want to keep their
 symbols separate, consider wrapping them as separate SWIG modules. For
 example, make the module name the same as the namespace and create
 extension modules for each namespace separately. If your program
 utilizes thousands of small deeply nested namespaces each with
 identical symbol names, well, then you get what you deserve.</p>
<h3><a name="Python_nn26">32.3.13 C++ templates</a></h3>
<p> C++ templates don't present a huge problem for SWIG. However, in
 order to create wrappers, you have to tell SWIG to create wrappers for
 a particular template instantiation. To do this, you use the <tt>
%template</tt> directive. For example:</p>
<div class="code">
<pre>
%module example
%{
#include &quot;pair.h&quot;
%}

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

%template(pairii) pair&lt;int, int&gt;;
</pre>
</div>
<p> In Python:</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; import example
&gt;&gt;&gt; p = example.pairii(3, 4)
&gt;&gt;&gt; p.first
3
&gt;&gt;&gt; p.second
4
</pre>
</div>
<p> Obviously, there is more to template wrapping than shown in this
 example. More details can be found in the <a href="#SWIGPlus">SWIG and
 C++</a> chapter. Some more complicated examples will appear later.</p>
<h3><a name="Python_nn27">32.3.14 C++ Smart Pointers</a></h3>
<h4><a name="Python_smart_pointers_shared_ptr">32.3.14.1 The shared_ptr
 Smart Pointer</a></h4>
<p> The C++11 standard provides <tt>std::shared_ptr</tt> which was
 derived from the Boost implementation, <tt>boost::shared_ptr</tt>. Both
 of these are available for Python in the SWIG library and usage is
 outlined in the <a href="#Library_std_shared_ptr">shared_ptr smart
 pointer</a> library section.</p>
<h4><a name="Python_smart_pointers_generic">32.3.14.2 Generic Smart
 Pointers</a></h4>
<p> In certain C++ programs, it is common to use classes that have been
 wrapped by so-called &quot;smart pointers.&quot; Generally, this involves the use
 of a template class that implements <tt>operator-&gt;()</tt> like this:</p>
<div class="code">
<pre>
template&lt;class T&gt; class SmartPtr {
  ...
  T *operator-&gt;();
  ...
}
</pre>
</div>
<p> Then, if you have a class like this,</p>
<div class="code">
<pre>
class Foo {
public:
  int x;
  int bar();
};
</pre>
</div>
<p> A smart pointer would be used in C++ as follows:</p>
<div class="code">
<pre>
SmartPtr&lt;Foo&gt; p = CreateFoo();   // Created somehow (not shown)
...
p-&gt;x = 3;                        // Foo::x
int y = p-&gt;bar();                // Foo::bar
</pre>
</div>
<p> To wrap this in Python, simply tell SWIG about the <tt>SmartPtr</tt>
 class and the low-level <tt>Foo</tt> object. Make sure you instantiate <tt>
SmartPtr</tt> using <tt>%template</tt> if necessary. For example:</p>
<div class="code">
<pre>
%module example
...
%template(SmartPtrFoo) SmartPtr&lt;Foo&gt;;
...
</pre>
</div>
<p> Now, in Python, everything should just &quot;work&quot;:</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; p = example.CreateFoo()          # Create a smart-pointer somehow
&gt;&gt;&gt; p.x = 3                          # Foo::x
&gt;&gt;&gt; p.bar()                          # Foo::bar
</pre>
</div>
<p> If you ever need to access the underlying pointer returned by <tt>
operator-&gt;()</tt> itself, simply use the <tt>__deref__()</tt> method.
 For example:</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; f = p.__deref__()     # Returns underlying Foo *
</pre>
</div>
<h3><a name="Python_nn27a">32.3.15 C++ reference counted objects</a></h3>
<p> The <a href="#SWIGPlus_ref_unref">C++ reference counted objects</a>
 section contains Python examples of memory management using referencing
 counting.</p>
<h2><a name="Python_nn28">32.4 Further details on the Python class
 interface</a></h2>
<p> In the previous section, a high-level view of Python wrapping was
 presented. A key component of this wrapping is that structures and
 classes are wrapped by Python proxy classes. This provides a very
 natural Python interface and allows SWIG to support a number of
 advanced features such as operator overloading. However, a number of
 low-level details were omitted. This section provides a brief overview
 of how the proxy classes work.</p>
<p><b>New in SWIG version 2.0.4:</b> The use of Python proxy classes has
 performance implications that may be unacceptable for a
 high-performance library. The new <tt>-builtin</tt> option instructs
 SWIG to forego the use of proxy classes, and instead create wrapped
 types as new built-in Python types. When this option is used, the
 following section (&quot;Proxy classes&quot;) does not apply. Details on the use
 of the <tt>-builtin</tt> option are in the <a href="#Python_builtin_types">
Built-in Types</a> section.</p>
<h3><a name="Python_nn29">32.4.1 Proxy classes</a></h3>
<p> In the <a href="#SWIG">&quot;SWIG basics&quot;</a> and <a href="#SWIGPlus">
&quot;SWIG and C++&quot;</a> chapters, details of low-level structure and class
 wrapping are described. To summarize those chapters, if you have a
 class like this</p>
<div class="code">
<pre>
class Foo {
public:
  int x;
  int spam(int);
  ...
</pre>
</div>
<p> then SWIG transforms it into a set of low-level procedural wrappers.
 For example:</p>
<div class="code">
<pre>
Foo *new_Foo() {
  return new Foo();
}
void delete_Foo(Foo *f) {
  delete f;
}
int Foo_x_get(Foo *f) {
  return f-&gt;x;
}
void Foo_x_set(Foo *f, int value) {
  f-&gt;x = value;
}
int Foo_spam(Foo *f, int arg1) {
  return f-&gt;spam(arg1);
}
</pre>
</div>
<p> These wrappers can be found in the low-level extension module (e.g.,
 <tt>_example</tt>).</p>
<p> Using these wrappers, SWIG generates a high-level Python proxy class
 (also known as a shadow class) like this (shown for Python 2.2):</p>
<div class="targetlang">
<pre>
import _example

class Foo(object):
    def __init__(self):
        self.this = _example.new_Foo()
        self.thisown = 1
    def __del__(self):
        if self.thisown:
            _example.delete_Foo(self.this)
    def spam(self, arg1):
        return _example.Foo_spam(self.this, arg1)
    x = property(_example.Foo_x_get, _example.Foo_x_set)
</pre>
</div>
<p> This class merely holds a pointer to the underlying C++ object (<tt>
.this</tt>) and dispatches methods and member variable access to that
 object using the low-level accessor functions. From a user's point of
 view, it makes the class work normally:</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; f = example.Foo()
&gt;&gt;&gt; f.x = 3
&gt;&gt;&gt; y = f.spam(5)
</pre>
</div>
<p> The fact that the class has been wrapped by a real Python class
 offers certain advantages. For instance, you can attach new Python
 methods to the class and you can even inherit from it (something not
 supported by Python built-in types until Python 2.2).</p>
<h3><a name="Python_builtin_types">32.4.2 Built-in Types</a></h3>
<p> The <tt>-builtin</tt> option provides a significant performance
 improvement in the wrapped code. To understand the difference between
 proxy classes and built-in types, let's take a look at what a wrapped
 object looks like under both circumstances.</p>
<p>When proxy classes are used, each wrapped object in Python is an
 instance of a pure Python class. As a reminder, here is what the <tt>
__init__</tt> method looks like in a proxy class:</p>
<div class="targetlang">
<pre>
class Foo(object):
    def __init__(self):
        self.this = _example.new_Foo()
        self.thisown = 1
</pre>
</div>
<p>When a <tt>Foo</tt> instance is created, the call to <tt>
_example.new_Foo()</tt> creates a new C++ <tt>Foo</tt> instance; wraps
 that C++ instance inside an instance of a Python built-in type called <tt>
SwigPyObject</tt>; and stores the <tt>SwigPyObject</tt> instance in the
 'this' field of the Python Foo object. Did you get all that? So, the
 Python <tt>Foo</tt> object is composed of three parts:</p>
<ul>
<li> The Python <tt>Foo</tt> instance, which contains...</li>
<li> ... an instance of <tt>struct SwigPyObject</tt>, which contains...</li>
<li> ... a C++ <tt>Foo</tt> instance</li>
</ul>
<p>When <tt>-builtin</tt> is used, the pure Python layer is stripped
 off. Each wrapped class is turned into a new Python built-in type which
 inherits from <tt>SwigPyObject</tt>, and <tt>SwigPyObject</tt>
 instances are returned directly from the wrapped methods. For more
 information about Python built-in extensions, please refer to the
 Python documentation:</p>
<p><a href="https://docs.python.org/3/extending/newtypes.html">
https://docs.python.org/3/extending/newtypes.html</a></p>
<h4><a name="Python_builtin_limitations">32.4.2.1 Limitations</a></h4>
<p>Use of the <tt>-builtin</tt> option implies a couple of limitations:</p>
<ul>
<li>
<p>Some legacy syntax is no longer supported; in particular:</p>
<ul>
<li>The functional interface is no longer exposed. For example, you may
 no longer call <tt>Whizzo.new_CrunchyFrog()</tt>. Instead, you must use
 <tt>Whizzo.CrunchyFrog()</tt>.</li>
<li>Static member variables are no longer accessed through the 'cvar'
 field (e.g., <tt>Dances.cvar.FishSlap</tt>). They are instead accessed
 in the idiomatic way (<tt>Dances.FishSlap</tt>).</li>
</ul>
</li>
<li>
<p>Wrapped types may not be raised as Python exceptions. Here's why: the
 Python internals expect that all sub-classes of Exception will have
 this struct layout:</p>
<div class="code">
<pre>
typedef struct {
  PyObject_HEAD
  PyObject *dict;
  PyObject *args;
  PyObject *message;
} PyBaseExceptionObject;
</pre>
</div>
<p>But swig-generated wrappers expect that all swig-wrapped classes will
 have this struct layout:</p>
<div class="code">
<pre>
typedef struct {
  PyObject_HEAD
  void *ptr;
  swig_type_info *ty;
  int own;
  PyObject *next;
  PyObject *dict;
} SwigPyObject;
</pre>
</div>
<p>There are workarounds for this. For example, if you wrap this class:<div
class="code">
<pre>
class MyException {
public:
  MyException (const char *msg_);
  ~MyException ();

  const char *what () const;

private:
  char *msg;
};
</pre>
</div></p>
<p>... you can define this Python class, which may be raised as an
 exception:</p>
<div class="targetlang">
<pre>
class MyPyException(Exception):
    def __init__(self, msg, *args):
        Exception.__init__(self, *args)
        self.myexc = MyException(msg)
    def what(self):
        return self.myexc.what()
</pre>
</div></li>
<li>
<p>Reverse binary operators (e.g., <tt>__radd__</tt>) are not supported.</p>
<p>To illustrate this point, if you have a wrapped class called <tt>
MyString</tt>, and you want to use instances of <tt>MyString</tt>
 interchangeably with native Python strings, you can define an <tt>
'operator+ (const char*)'</tt> method :</p>
<div class="code">
<pre>
class MyString {
public:
  MyString (const char *init);
  MyString operator+ (const char *other) const;
  ...
};
</pre>
</div>
<p> SWIG will automatically create an operator overload in Python that
 will allow this:</p>
<div class="targetlang">
<pre>
from MyModule import MyString

mystr = MyString(&quot;No one expects&quot;)
episode = mystr + &quot; the Spanish Inquisition&quot;
</pre>
</div>
<p> This works because the first operand (<tt>mystr</tt>) defines a way
 to add a native string to itself. However, the following will<b> not</b>
 work:</p>
<div class="targetlang">
<pre>
from MyModule import MyString

mystr = MyString(&quot;Parrot&quot;)
episode = &quot;Dead &quot; + mystr
</pre>
</div>
<p> The above code fails, because the first operand -- a native Python
 string -- doesn't know how to add an instance of <tt>MyString</tt> to
 itself.</p>
</li>
<li>
<p>If you have multiple SWIG modules that share type information (<a href="#Modules_nn2">
more info</a>), the <tt>-builtin</tt> option requires a bit of extra
 discipline to ensure that base classes are initialized before derived
 classes. Specifically:</p>
<ul>
<li>
<p>There must be an unambiguous dependency graph for the modules.</p>
</li>
<li>
<p>Module dependencies must be explicitly stated with <tt>%import</tt>
 statements in the SWIG interface file.</p>
</li>
</ul>
<p>As an example, suppose module <tt>A</tt> has this interface in <tt>
A.i</tt> :</p>
<div class="code">
<pre>
%module &quot;A&quot;;

class Base {
...
};
</pre>
</div>
<p>If you want to wrap another module containing a class that inherits
 from <tt>A</tt>, this is how it would look :</p>
<div class="code">
<pre>
%module &quot;B&quot;;

%import &quot;A.i&quot;

class Derived : public Base {
...
};
</pre>
</div>
<p>The <tt>import &quot;A.i&quot;</tt> statement is required, because module <tt>B</tt>
 depends on module <tt>A</tt>.</p>
<p>As long as you obey these requirements, your Python code may import
 the modules in any order :</p>
<div class="targetlang">
<pre>
import B
import A

assert(issubclass(B.Derived, A.Base))
</pre>
</div></li>
</ul>
<h4><a name="Python_builtin_overloads">32.4.2.2 Operator overloads and
 slots -- use them!</a></h4>
<p>The entire justification for the <tt>-builtin</tt> option is improved
 performance. To that end, the best way to squeeze maximum performance
 out of your wrappers is to<b> use operator overloads.</b> Named method
 dispatch is slow in Python, even when compared to other scripting
 languages. However, Python built-in types have a large number of
 &quot;slots&quot;, analogous to C++ operator overloads, which allow you to
 short-circuit named method dispatch for certain common operations.</p>
<p>By default, SWIG will translate most C++ arithmetic operator
 overloads into Python slot entries. For example, suppose you have this
 class:<div class="code">
<pre>
class Twit {
public:
  Twit operator+ (const Twit&amp; twit) const;

  // Forward to operator+
  Twit add (const Twit&amp; twit) const {
    return *this + twit;
  }
};
</pre>
</div></p>
<p>SWIG will automatically register <tt>operator+</tt> as a Python slot
 operator for addition. You may write Python code like this:</p>
<div class="targetlang">
<pre>
from MyModule import Twit

nigel = Twit()
emily = Twit()
percival = nigel + emily
percival = nigel.add(emily)
</pre>
</div>
<p>The last two lines of the Python code are equivalent, but<b> the line
 that uses the '+' operator is much faster</b>.</p>
<p>In-place operators (e.g., <tt>operator+=</tt>) and comparison
 operators (<tt>operator==, operator&lt;</tt>, etc.) are also converted to
 Python slot operators. For a complete list of C++ operators that are
 automatically converted to Python slot operators, refer to the file <tt>
python/pyopers.swig</tt> in the SWIG library.</p>
<p> Read about all of the available Python slots here: <a href="https://docs.python.org/3/c-api/typeobj.html">
https://docs.python.org/3/c-api/typeobj.html</a></p>
<p> There are two ways to define a Python slot function: dispatch to a
 statically defined function; or dispatch to a method defined on the
 operand.</p>
<p> To dispatch to a statically defined function, use
 %feature(&quot;python:&lt;slot&gt;&quot;), where &lt;slot&gt; is the name of a field in a <tt>
PyTypeObject, PyNumberMethods, PyMappingMethods, PySequenceMethods</tt>
 or <tt>PyBufferProcs</tt>. You may override (almost) all of these
 slots.</p>
<p> Let's consider an example setting the <tt>tp_hash</tt> slot for the <tt>
MyClass</tt> type. This is akin to providing a <tt>__hash__</tt> method
 (for non-builtin types) to make a type hashable. The hashable type can
 then for example be added to a Python <tt>dict</tt>.</p>
<div class="code">
<pre>
%feature(&quot;python:tp_hash&quot;) MyClass &quot;myHashFunc&quot;;

class MyClass {
public:
  long field1;
  long field2;
  ...
};

%{
#if PY_VERSION_HEX &gt;= 0x03020000
  static Py_hash_t myHashFunc(PyObject *pyobj)
#else
  static long myHashFunc(PyObject *pyobj)
#endif
  {
    MyClass *cobj;
    // Convert pyobj to cobj
    return (cobj-&gt;field1 * (cobj-&gt;field2 &lt;&lt; 7));
  }
%}
</pre>
</div>
<p> If you examine the generated code, the supplied hash function will
 now be the function callback in the tp_hash slot for the builtin type
 for <tt>MyClass</tt>:</p>
<div class="code">
<pre>
static PyHeapTypeObject SwigPyBuiltin__MyClass_type = {
  ...
  (hashfunc) myHashFunc,       /* tp_hash */
  ...
</pre>
</div>
<p> NOTE: It is the responsibility of the programmer (that's you!) to
 ensure that a statically defined slot function has the correct
 signature, the <tt>hashfunc</tt> typedef in this case.</p>
<p> If, instead, you want to dispatch to an instance method, you can use
 %feature(&quot;python:slot&quot;). For example:</p>
<div class="code">
<pre>
%feature(&quot;python:slot&quot;, &quot;tp_hash&quot;, functype=&quot;hashfunc&quot;) MyClass::myHashFunc;

#if PY_VERSION_HEX &lt; 0x03020000
  #define Py_hash_t long
#endif

class MyClass {
  public:
    Py_hash_t myHashFunc() const;
    ...
};
</pre>
</div>
<p> NOTE: Some Python slots use a method signature which does not match
 the signature of SWIG-wrapped methods. For those slots, SWIG will
 automatically generate a &quot;closure&quot; function to re-marshal the arguments
 before dispatching to the wrapped method. Setting the &quot;functype&quot;
 attribute of the feature enables SWIG to generate the chosen closure
 function.</p>
<p> There is further information on <tt>%feature(&quot;python:slot&quot;)</tt> in
 the file <tt>python/pyopers.swig</tt> in the SWIG library.</p>
<h3><a name="Python_nn30">32.4.3 Memory management</a></h3>
<p>NOTE: Although this section refers to proxy objects, everything here
 also applies when the <tt>-builtin</tt> option is used.</p>
<p> Associated with proxy object, is an ownership flag <tt>.thisown</tt>
 The value of this flag determines who is responsible for deleting the
 underlying C++ object. If set to 1, the Python interpreter will destroy
 the C++ object when the proxy class is garbage collected. If set to 0
 (or if the attribute is missing), then the destruction of the proxy
 class has no effect on the C++ object.</p>
<p> When an object is created by a constructor or returned by value,
 Python automatically takes ownership of the result. For example:</p>
<div class="code">
<pre>
class Foo {
public:
  Foo();
  Foo bar();
};
</pre>
</div>
<p> In Python:</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; f = Foo()
&gt;&gt;&gt; f.thisown
1
&gt;&gt;&gt; g = f.bar()
&gt;&gt;&gt; g.thisown
1
</pre>
</div>
<p> On the other hand, when pointers are returned to Python, there is
 often no way to know where they came from. Therefore, the ownership is
 set to zero. For example:</p>
<div class="code">
<pre>
class Foo {
public:
  ...
  Foo *spam();
  ...
};
</pre>
</div>
<br><div class="targetlang">
<pre>
&gt;&gt;&gt; f = Foo()
&gt;&gt;&gt; s = f.spam()
&gt;&gt;&gt; print s.thisown
0
&gt;&gt;&gt;
</pre>
</div>
<p> This behavior 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
 Python to assume ownership and destroy it!</p>
<p> A good way to indicate that ownership should be set for a returned
 pointer is to use the <a href="#Library_nn11">%newobject directive</a>.</p>
<p> Related to containers, ownership issues can arise whenever an object
 is assigned to a member or global variable. For example, consider this
 interface:</p>
<div class="code">
<pre>
%module example

struct Foo {
  int  value;
  Foo  *next;
};

Foo *head = 0;
</pre>
</div>
<p> When wrapped in Python, careful observation will reveal that
 ownership changes whenever an object is assigned to a global variable.
 For example:</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; f = example.Foo()
&gt;&gt;&gt; f.thisown
1
&gt;&gt;&gt; example.cvar.head = f
&gt;&gt;&gt; f.thisown
0
&gt;&gt;&gt;
</pre>
</div>
<p> In this case, C is now holding a reference to the object---you
 probably don't want Python to destroy it. Similarly, this occurs for
 members. For example:</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; f = example.Foo()
&gt;&gt;&gt; g = example.Foo()
&gt;&gt;&gt; f.thisown
1
&gt;&gt;&gt; g.thisown
1
&gt;&gt;&gt; f.next = g
&gt;&gt;&gt; g.thisown
0
&gt;&gt;&gt;
</pre>
</div>
<p> For the most part, memory management issues remain hidden. However,
 there are occasionally situations where you might have to manually
 change the ownership of an object. For instance, consider code like
 this:</p>
<div class="code">
<pre>
class Node {
  Object *value;
public:
  void set_value(Object *v) { value = v; }
  ...
};
</pre>
</div>
<p> Now, consider the following Python code:</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; v = Object()           # Create an object
&gt;&gt;&gt; n = Node()             # Create a node
&gt;&gt;&gt; n.set_value(v)         # Set value
&gt;&gt;&gt; v.thisown
1
&gt;&gt;&gt; del v
</pre>
</div>
<p> In this case, the object <tt>n</tt> is holding a reference to <tt>v</tt>
 internally. However, SWIG has no way to know that this has occurred.
 Therefore, Python still thinks that it has ownership of the object.
 Should the proxy object be destroyed, then the C++ destructor will be
 invoked and <tt>n</tt> will be holding a stale-pointer. If you're
 lucky, you will only get a segmentation fault.</p>
<p> To work around this, it is always possible to flip the ownership
 flag. For example,</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; v.thisown = 0
</pre>
</div>
<p> It is also possible to deal with situations like this using
 typemaps--an advanced topic discussed later.</p>
<h2><a name="Python_directors">32.5 Cross language polymorphism</a></h2>
<p> Proxy classes provide a more natural, object-oriented way to access
 extension classes. As described above, each proxy instance has an
 associated C++ instance, and method calls to the proxy are passed to
 the C++ instance transparently via C wrapper functions.</p>
<p> This arrangement is asymmetric in the sense that no corresponding
 mechanism exists to pass method calls down the inheritance chain from
 C++ to Python. In particular, if a C++ class has been extended in
 Python (by extending the proxy class), these extensions will not be
 visible from C++ code. Virtual method calls from C++ are thus not able
 access the lowest implementation in the inheritance chain.</p>
<p> Changes have been made to SWIG 1.3.18 to 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 Python
 implementations lower in the inheritance chain. The upshot is that C++
 classes can be extended in Python and from C++ these extensions look
 exactly like native C++ classes. Neither C++ code nor Python code needs
 to know where a particular method is implemented: the combination of
 proxy classes, director classes, and C wrapper functions takes care of
 all the cross-language method routing transparently.</p>
<h3><a name="Python_nn33">32.5.1 Enabling directors</a></h3>
<p> The director feature is disabled by default. To use directors you
 must make two changes to the interface file. First, add the &quot;directors&quot;
 option to the %module directive, like this:</p>
<div class="code">
<pre>
%module(directors=&quot;1&quot;) modulename
</pre>
</div>
<p> Without this option no director code will be generated. Second, you
 must use the %feature(&quot;director&quot;) directive to tell SWIG which classes
 and methods should get directors. The %feature directive can be applied
 globally, to specific classes, and to specific methods, like this:</p>
<div class="code">
<pre>
// generate directors for all classes that have virtual methods
%feature(&quot;director&quot;);

// generate directors for the virtual methods in class Foo
%feature(&quot;director&quot;) Foo;
</pre>
</div>
<p> You can use the %feature(&quot;nodirector&quot;) directive to turn off
 directors for specific classes or methods. So for example,</p>
<div class="code">
<pre>
%feature(&quot;director&quot;) Foo;
%feature(&quot;nodirector&quot;) Foo::bar;
</pre>
</div>
<p> will generate directors for the virtual methods of class Foo except
 bar().</p>
<p> Directors can also be generated implicitly through inheritance. In
 the following, class Bar will get a director class that handles the
 methods one() and two() (but not three()):</p>
<div class="code">
<pre>
%feature(&quot;director&quot;) Foo;
class Foo {
public:
  Foo(int foo);
  virtual ~Foo();
  virtual void one();
  virtual void two();
};

class Bar: public Foo {
public:
  virtual void three();
};
</pre>
</div>
<p> then at the Python side you can define</p>
<div class="targetlang">
<pre>
import mymodule

class MyFoo(mymodule.Foo):
    def __init__(self, foo):
        mymodule.Foo.__init__(self, foo)
#       super().__init__(foo) # Alternative construction for Python3

    def one(self):
        print &quot;one from Python&quot;
</pre>
</div>
<h3><a name="Python_nn34">32.5.2 Director classes</a></h3>
<p> For each class that has directors enabled, SWIG generates a new
 class that derives from both the class in question and a special <tt>
Swig::Director</tt> class. These new classes, referred to as director
 classes, can be loosely thought of as the C++ equivalent of the Python
 proxy classes. The director classes store a pointer to their underlying
 Python object and handle various issues related to object ownership.
 Indeed, this is quite similar to the &quot;this&quot; and &quot;thisown&quot; members of
 the Python proxy classes.</p>
<p> For simplicity let's ignore the <tt>Swig::Director</tt> class and
 refer to the original C++ class as the director's base class. By
 default, a director class extends all virtual methods in the
 inheritance chain of its base class (see the preceding section for how
 to modify this behavior). Virtual methods that have a final specifier
 are unsurprisingly excluded. Thus the virtual method calls, whether
 they originate in C++ or in Python 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 &quot;appropriate place&quot; we mean the method that would
 have been called if the C++ base class and its extensions in Python
 were seamlessly integrated. That seamless integration is exactly what
 the director classes provide, transparently skipping over all the messy
 extension API glue that binds the two languages together.</p>
<p> In reality, the &quot;appropriate place&quot; is one of only two
 possibilities: C++ or Python. 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 Python, the Python API
 is used to call the method of the underlying Python object (after which
 the usual virtual method resolution in Python automatically finds the
 right implementation).</p>
<p> Now how does the director decide which language should handle the
 method call? The basic rule is to handle the method in Python, unless
 there's a good reason not to. The reason for this is simple: Python has
 the most &quot;extended&quot; implementation of the method. This assertion is
 guaranteed, since at a minimum the Python proxy class implements the
 method. If the method in question has been extended by a class derived
 from the proxy class, that extended implementation will execute exactly
 as it should. If not, the proxy class will route the method call into a
 C wrapper function, expecting that the method will be resolved in C++.
 The wrapper will call the virtual method of the C++ instance, and since
 the director extends this the call will end up right back in the
 director method. Now comes the &quot;good reason not to&quot; part. If the
 director method were to blindly call the Python method again, it would
 get stuck in an infinite loop. We avoid this situation by adding
 special code to the C wrapper function that tells the director method
 to not do this. The C wrapper function compares the pointer to the
 Python object that called the wrapper function to the pointer stored by
 the director. If these are the same, then the C wrapper function tells
 the director to resolve the method by calling up the C++ inheritance
 chain, preventing an infinite loop.</p>
<p> One more point needs to be made about the relationship between
 director classes and proxy classes. When a proxy class instance is
 created in Python, SWIG creates an instance of the original C++ class
 and assigns it to <tt>.this</tt>. This is exactly what happens without
 directors and is true even if directors are enabled for the particular
 class in question. When a class<i> derived</i> from a proxy class is
 created, however, SWIG then creates an instance of the corresponding
 C++ director class. The reason for this difference is that user-defined
 subclasses may override or extend methods of the original class, so the
 director class is needed to route calls to these methods correctly. For
 unmodified proxy classes, all methods are ultimately implemented in C++
 so there is no need for the extra overhead involved with routing the
 calls through Python.</p>
<h3><a name="Python_nn35">32.5.3 Ownership and object destruction</a></h3>
<p> Memory management issues are slightly more complicated with
 directors than for proxy classes alone. Python instances hold a pointer
 to the associated C++ director object, and the director in turn holds a
 pointer back to the Python object. By default, proxy classes own their
 C++ director object and take care of deleting it when they are garbage
 collected.</p>
<p> This relationship can be reversed by calling the special <tt>
__disown__()</tt> method of the proxy class. After calling this method,
 the <tt>.thisown</tt> flag is set to zero, and the director class
 increments the reference count of the Python object. When the director
 class is deleted it decrements the reference count. Assuming no
 outstanding references to the Python object remain, the Python object
 will be destroyed at the same time. This is a good thing, since
 directors and proxies refer to each other and so must be created and
 destroyed together. Destroying one without destroying the other will
 likely cause your program to segfault.</p>
<p> To help ensure that no references to the Python object remain after
 calling <tt>__disown__()</tt>, this method returns a weak reference to
 the Python object. Weak references are only available in Python
 versions 2.1 and higher, so for older versions you must explicitly
 delete all references. Here is an example:</p>
<div class="code">
<pre>
class Foo {
public:
  ...
};
class FooContainer {
public:
  void addFoo(Foo *);
  ...
};
</pre>
</div>
<br><div class="targetlang">
<pre>
&gt;&gt;&gt; c = FooContainer()
&gt;&gt;&gt; a = Foo().__disown__()
&gt;&gt;&gt; c.addFoo(a)
&gt;&gt;&gt; b = Foo()
&gt;&gt;&gt; b = b.__disown__()
&gt;&gt;&gt; c.addFoo(b)
&gt;&gt;&gt; c.addFoo(Foo().__disown__())
</pre>
</div>
<p> In this example, we are assuming that FooContainer will take care of
 deleting all the Foo pointers it contains at some point. Note that no
 hard references to the Foo objects remain in Python.</p>
<h3><a name="Python_nn36">32.5.4 Exception unrolling</a></h3>
<p> With directors routing method calls to Python, and proxies routing
 them to C++, the handling of exceptions is an important concern. By
 default, the directors ignore exceptions that occur during method calls
 that are resolved in Python. To handle such exceptions correctly, it is
 necessary to temporarily translate them into C++ exceptions. This can
 be done with the %feature(&quot;director:except&quot;) directive. The following
 code should suffice in most cases:</p>
<div class="code">
<pre>
%feature(&quot;director:except&quot;) {
  if ($error != NULL) {
    throw Swig::DirectorMethodException();
  }
}
</pre>
</div>
<p> This code will check the Python error state after each method call
 from a director into Python, and throw a C++ exception if an error
 occurred. This exception can be caught in C++ to implement an error
 handler. Currently no information about the Python error is stored in
 the Swig::DirectorMethodException object, but this will likely change
 in the future.</p>
<p> It may be the case that a method call originates in Python, travels
 up to C++ through a proxy class, and then back into Python via a
 director method. If an exception occurs in Python at this point, it
 would be nice for that exception to find its way back to the original
 caller. This can be done by combining a normal %exception directive
 with the <tt>director:except</tt> handler shown above. Here is an
 example of a suitable exception handler:</p>
<div class="code">
<pre>
%exception {
  try { $action }
  catch (Swig::DirectorException &amp;e) { SWIG_fail; }
}
</pre>
</div>
<p> The class Swig::DirectorException used in this example is actually a
 base class of Swig::DirectorMethodException, so it will trap this
 exception. Because the Python error state is still set when
 Swig::DirectorMethodException is thrown, Python will register the
 exception as soon as the C wrapper function returns.</p>
<h3><a name="Python_nn37">32.5.5 Overhead and code bloat</a></h3>
<p> Enabling directors for a class will generate a new director method
 for every virtual method in the class' inheritance chain. This alone
 can generate a lot of code bloat for large hierarchies. Method
 arguments that require complex conversions to and from target language
 types can result in large director methods. For this reason it is
 recommended that you selectively enable directors only for specific
 classes that are likely to be extended in Python and used in C++.</p>
<p> Compared to classes that do not use directors, the call routing in
 the director methods does add some overhead. In particular, at least
 one dynamic cast and one extra function call occurs per method call
 from Python. Relative to the speed of Python execution this is probably
 completely negligible. For worst case routing, a method call that
 ultimately resolves in C++ may take one extra detour through Python in
 order to ensure that the method does not have an extended Python
 implementation. This could result in a noticeable overhead in some
 cases.</p>
<p> Although directors make it natural to mix native C++ objects with
 Python objects (as director objects) via a common base class pointer,
 one should be aware of the obvious fact that method calls to Python
 objects will be much slower than calls to C++ objects. 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 Python.</p>
<h3><a name="Python_nn38">32.5.6 Typemaps</a></h3>
<p> Typemaps for input and output of most of the basic types from
 director classes have been written. These are roughly the reverse of
 the usual input and output typemaps used by the wrapper code. The
 typemap operation names are 'directorin', 'directorout', and
 'directorargout'. The director code does not currently use any of the
 other kinds of typemaps. It is not clear at this point which kinds are
 appropriate and need to be supported.</p>
<h3><a name="Python_nn39">32.5.7 Miscellaneous</a></h3>
<p> Director typemaps for STL classes are in place, and hence you should
 be able to use std::vector, std::string, etc., as you would any other
 type.</p>
<p><b> Note:</b> The director typemaps for return types based in const
 references, such as<div class="code">
<pre>
class Foo {
&hellip;
  virtual const int&amp; bar();
&hellip;
};
</pre>
</div></p>
<p> will work only for simple call scenarios. Usually the resulting code
 is neither thread or reentrant safe. Hence, the user is advised to
 avoid returning const references in director methods. For example, the
 user could modify the method interface to use lvalue return types,
 wherever possible, for example</p>
<div class="code">
<pre>
class Foo {
&hellip;
  virtual int bar();
&hellip;
};
</pre>
</div>
<p> If that is not possible, the user should avoid enabling the director
 feature for reentrant, recursive or threaded member methods that return
 const references.</p>
<h2><a name="Python_nn40">32.6 Common customization features</a></h2>
<p> The last 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
 your the interface to an extension module.</p>
<h3><a name="Python_nn41">32.6.1 C/C++ helper functions</a></h3>
<p> Sometimes when you create a module, it is missing certain bits of
 functionality. For example, if you had a function like this</p>
<div class="code">
<pre>
void set_transform(Image *im, double m[4][4]);
</pre>
</div>
<p> it would be accessible from Python, but there may be no easy way to
 call it. For example, you might get errors like this:</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; a = [
...   [1, 0, 0, 0],
...   [0, 1, 0, 0],
...   [0, 0, 1, 0],
...   [0, 0, 0, 1]]
&gt;&gt;&gt; set_transform(im, a)
Traceback (most recent call last):
  File &quot;&lt;stdin&gt;&quot;, line 1, in ?
TypeError: Type error. Expected _p_a_4__double
</pre>
</div>
<p> The problem here is that there is no easy way to construct and
 manipulate a suitable <tt>double [4][4]</tt> value to use. To fix this,
 you can write some extra C helper functions. Just use the <tt>%inline</tt>
 directive. For example:</p>
<div class="code">
<pre>
%inline %{
/* Note: double[4][4] is equivalent to a pointer to an array double (*)[4] */
double (*new_mat44())[4] {
  return (double (*)[4]) malloc(16*sizeof(double));
}
void free_mat44(double (*x)[4]) {
  free(x);
}
void mat44_set(double x[4][4], int i, int j, double v) {
  x[i][j] = v;
}
double mat44_get(double x[4][4], int i, int j) {
  return x[i][j];
}
%}
</pre>
</div>
<p> From Python, you could then write code like this:</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; a = new_mat44()
&gt;&gt;&gt; mat44_set(a, 0, 0, 1.0)
&gt;&gt;&gt; mat44_set(a, 1, 1, 1.0)
&gt;&gt;&gt; mat44_set(a, 2, 2, 1.0)
...
&gt;&gt;&gt; set_transform(im, a)
&gt;&gt;&gt;
</pre>
</div>
<p> Admittedly, this is not the most elegant looking approach. However,
 it works and it wasn't too hard to implement. It is possible to clean
 this up using Python code, typemaps, and other customization features
 as covered in later sections.</p>
<h3><a name="Python_nn42">32.6.2 Adding additional Python code</a></h3>
<p> If writing support code in C isn't enough, it is also possible to
 write code in Python. This code gets inserted in to the <tt>.py</tt>
 file created by SWIG. One use of Python code might be to supply a
 high-level interface to certain functions. For example:</p>
<div class="code">
<pre>
void set_transform(Image *im, double x[4][4]);

...
/* Rewrite the high level interface to set_transform */
%pythoncode %{
def set_transform(im, x):
    a = new_mat44()
    for i in range(4):
        for j in range(4):
            mat44_set(a, i, j, x[i][j])
    _example.set_transform(im, a)
    free_mat44(a)
%}
</pre>
</div>
<p> In this example, <tt>set_transform()</tt> provides a high-level
 Python interface built on top of low-level helper functions. For
 example, this code now seems to work:</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; a = [
...   [1, 0, 0, 0],
...   [0, 1, 0, 0],
...   [0, 0, 1, 0],
...   [0, 0, 0, 1]]
&gt;&gt;&gt; set_transform(im, a)
&gt;&gt;&gt;
</pre>
</div>
<p> Admittedly, this whole scheme for wrapping the two-dimension array
 argument is rather ad-hoc. Besides, shouldn't a Python list or a
 Numeric Python array just work normally? We'll get to those examples
 soon enough. For now, think of this example as an illustration of what
 can be done without having to rely on any of the more advanced
 customization features.</p>
<p> There is also <tt>%pythonbegin</tt> which is another directive very
 similar to <tt>%pythoncode</tt>, but generates the given Python code at
 the beginning of the <tt>.py</tt> file. This directive works in the
 same way as <tt>%pythoncode</tt>, except the code is copied just after
 the SWIG banner (comment) at the top of the file, before any real code.
 This provides an opportunity to add your own description in a comment
 near the top of the file as well as Python imports that have to appear
 at the top of the file, such as &quot;<tt>from __future__ import</tt>&quot;
 statements.</p>
<p> The following example for Python 2.x shows how to insert code into
 the generated wrapper to enable <tt>print</tt> to be used as a
 Python3-compatible function instead of a statement:</p>
<div class="code">
<pre>
%pythonbegin %{
# This module provides wrappers to the Whizz Bang library
%}

%pythonbegin %{
from __future__ import print_function
print(&quot;Loading&quot;, &quot;Whizz&quot;, &quot;Bang&quot;, sep=' ... ')
%}
</pre>
</div>
<p> The insert code can be seen at the start of the generated <tt>.py</tt>
 file:</p>
<div class="code">
<pre>
# This file was automatically generated by SWIG (http://www.swig.org).
# Version 4.0.0
#
# Do not make changes to this file unless you know what you are doing--modify
# the SWIG interface file instead.

# This module provides wrappers to the Whizz Bang library

from __future__ import print_function
print(&quot;Loading&quot;, &quot;Whizz&quot;, &quot;Bang&quot;, sep=' ... ')

</pre>
</div>
<p>When using <tt>%pythoncode</tt> and <tt>%pythonbegin</tt> you
 generally want to make sure that the block is delimited by <tt>%{</tt>
 and <tt>%}</tt>. If you delimit it with <tt>{</tt> and <tt>}</tt> then
 any lines with a leading <tt>#</tt> will be handled by SWIG as
 preprocessor directives, when you probably meant them as Python
 comments. Prior to SWIG 3.0.3, invalid preprocessor directives were
 silently ignored, so generally using the wrong delimiters resulted in
 such comments not appearing in the generated output (though a comment
 starting with a valid preprocessor directive could cause problems, for
 example: <tt># error handling</tt>). SWIG 3.0.3 and later report an
 error for invalid preprocessor directives, so you may have to update
 existing interface files to delimit blocks of Python code correctly.</p>
<p>As an alternative to providing a block containing Python code, you
 can include Python code from a file. The code is inserted exactly as in
 the file, so this avoids any issues with the SWIG preprocessor. It's a
 good approach if you have a non-trivial chunk of Python code to insert.
 To use this feature you specify a filename in double quotes, for
 example:</p>
<div class="code">
<pre>
%pythoncode &quot;somecode.py&quot;
</pre>
</div>
<p>Sometimes you may want to replace or modify the wrapper function that
 SWIG creates in the proxy <tt>.py</tt> file. The Python module in SWIG
 provides some features that enable you to do this. First, to entirely
 replace a proxy function you can use <tt>%feature(&quot;shadow&quot;)</tt>. For
 example:</p>
<div class="code">
<pre>
%module example

// Rewrite bar() Python code

%feature(&quot;shadow&quot;) Foo::bar(int) %{
def bar(*args):
    #do something before
    $action
    #do something after
%}

class Foo {
public:
  int bar(int x);
};
</pre>
</div>
<p> where <tt>$action</tt> will be replaced by the call to the C/C++
 proper method.</p>
<p> Often the proxy function created by SWIG is fine, but you simply
 want to add code to it without touching the rest of the generated
 function body. For these cases SWIG provides the <tt>pythonprepend</tt>
 and <tt>pythonappend</tt> features which do exactly as their names
 suggest. The <tt>pythonprepend</tt> feature will insert its value at
 the beginning of the proxy function, and <tt>pythonappend</tt> will
 insert code at the end of the proxy, just before the return statement.</p>
<div class="code">
<pre>
%module example

// Add Python code to bar()

%feature(&quot;pythonprepend&quot;) Foo::bar(int) %{
    #do something before C++ call
%}

%feature(&quot;pythonappend&quot;) Foo::bar(int) %{
    #do something after C++ call
    #the 'val' variable holds the return value
%}


class Foo {
public:
  int bar(int x);
};
</pre>
</div>
<p> Notes: Usually the <tt>pythonappend</tt> and <tt>pythonprepend</tt>
 features are safer to use than the <tt>shadow</tt> feature. Also, from
 SWIG version 1.3.28 you can use the directive forms <tt>%pythonappend</tt>
 and <tt>%pythonprepend</tt> as follows:</p>
<div class="code">
<pre>
%module example

// Add Python code to bar()

%pythonprepend Foo::bar(int) %{
    #do something before C++ call
%}

%pythonappend Foo::bar(int) %{
    #do something after C++ call
    #the 'val' variable holds the return value
%}


class Foo {
public:
  int bar(int x);
};
</pre>
</div>
<p> Note that when the underlying C++ method is overloaded, there is
 only one proxy Python method for multiple C++ methods. In this case,
 only one of parsed methods is examined for the feature. You are better
 off specifying the feature without the argument list to ensure it will
 get used, as it will then get attached to all the overloaded C++
 methods. For example:</p>
<div class="code">
<pre>
%module example

// Add Python code to bar()

%pythonprepend Foo::bar %{
    #do something before C++ call
%}

%pythonappend Foo::bar %{
    #do something after C++ call
%}


class Foo {
public:
  int bar(int x);
  int bar();
};
</pre>
</div>
<p> The same applies for overloaded constructors.</p>
<h3><a name="Python_nn43">32.6.3 Class extension with %extend</a></h3>
<p> One of the more interesting features of SWIG is that it can extend
 structures and classes with new methods--at least in the Python
 interface. Here is a simple example:</p>
<div class="code">
<pre>
%module example
%{
#include &quot;someheader.h&quot;
%}

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

%extend Vector {
  char *__str__() {
    static char tmp[1024];
    sprintf(tmp, &quot;Vector(%g, %g, %g)&quot;, $self-&gt;x, $self-&gt;y, $self-&gt;z);
    return tmp;
  }
  Vector(double x, double y, double z) {
    Vector *v = (Vector *) malloc(sizeof(Vector));
    v-&gt;x = x;
    v-&gt;y = y;
    v-&gt;z = z;
    return v;
  }
};
</pre>
</div>
<p> Now, in Python</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; v = example.Vector(2, 3, 4)
&gt;&gt;&gt; print v
Vector(2, 3, 4)
&gt;&gt;&gt;
</pre>
</div>
<p> <tt>%extend</tt> can be used for many more tasks than this. For
 example, if you wanted to overload a Python operator, you might do
 this:</p>
<div class="code">
<pre>
%extend Vector {
  Vector __add__(Vector *other) {
    Vector v;
    v.x = $self-&gt;x + other-&gt;x;
    v.y = $self-&gt;y + other-&gt;y;
    v.z = $self-&gt;z + other-&gt;z;
    return v;
  }
};
</pre>
</div>
<p> Use it like this:</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; import example
&gt;&gt;&gt; v = example.Vector(2, 3, 4)
&gt;&gt;&gt; w = example.Vector(10, 11, 12)
&gt;&gt;&gt; print v+w
Vector(12, 14, 16)
&gt;&gt;&gt;
</pre>
</div>
<p> <tt>%extend</tt> works with both C and C++ code. It does not modify
 the underlying object in any way---the extensions only show up in the
 Python interface.</p>
<h3><a name="Python_nn44">32.6.4 Exception handling with %exception</a></h3>
<p> If a C or C++ function throws an error, you may want to convert that
 error into a Python exception. To do this, you can use the <tt>
%exception</tt> directive. <tt>%exception</tt> simply lets you rewrite
 part of the generated wrapper code to include an error check.</p>
<p> In C, a function often indicates an error by returning a status code
 (a negative number or a NULL pointer perhaps). Here is a simple example
 of how you might handle that:</p>
<div class="code">
<pre>
%exception malloc {
  $action
  if (!result) {
    PyErr_SetString(PyExc_MemoryError, &quot;Not enough memory&quot;);
    SWIG_fail;
  }
}
void *malloc(size_t nbytes);
</pre>
</div>
<p> In Python,</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; a = example.malloc(2000000000)
Traceback (most recent call last):
  File &quot;&lt;stdin&gt;&quot;, line 1, in ?
MemoryError: Not enough memory
&gt;&gt;&gt;
</pre>
</div>
<p> If a library provides some kind of general error handling framework,
 you can also use that. For example:</p>
<div class="code">
<pre>
%exception {
  $action
  if (err_occurred()) {
    PyErr_SetString(PyExc_RuntimeError, err_message());
    SWIG_fail;
  }
}
</pre>
</div>
<p> No declaration name is given to <tt>%exception</tt>, it is applied
 to all wrapper functions.</p>
<p> C++ exceptions are also easy to handle. For example, you can write
 code like this:</p>
<div class="code">
<pre>
%exception getitem {
  try {
    $action
  } catch (std::out_of_range &amp;e) {
    PyErr_SetString(PyExc_IndexError, const_cast&lt;char*&gt;(e.what()));
    SWIG_fail;
  }
}

class Base {
public:
  Foo *getitem(int index);      // Exception handled added
  ...
};
</pre>
</div>
<p> When raising a Python exception from C, use the <tt>
PyErr_SetString()</tt> function as shown above followed by <tt>SWIG_fail</tt>
. The following exception types can be used as the first argument.</p>
<div class="code">
<pre>
PyExc_ArithmeticError
PyExc_AssertionError
PyExc_AttributeError
PyExc_EnvironmentError
PyExc_EOFError
PyExc_Exception
PyExc_FloatingPointError
PyExc_ImportError
PyExc_IndexError
PyExc_IOError
PyExc_KeyError
PyExc_KeyboardInterrupt
PyExc_LookupError
PyExc_MemoryError
PyExc_NameError
PyExc_NotImplementedError
PyExc_OSError
PyExc_OverflowError
PyExc_RuntimeError
PyExc_StandardError
PyExc_SyntaxError
PyExc_SystemError
PyExc_TypeError
PyExc_UnicodeError
PyExc_ValueError
PyExc_ZeroDivisionError
</pre>
</div>
<p> <tt>SWIG_fail</tt> is a C macro which when called within the context
 of SWIG wrapper function, will jump to the error handler code. This
 will call any cleanup code (freeing any temp variables) and then return
 from the wrapper function so that the Python interpreter can raise the
 Python exception. This macro should always be called after setting a
 Python error in code snippets, such as typemaps and <tt>%exception</tt>
, that are ultimately generated into the wrapper function.</p>
<p> The language-independent <tt>exception.i</tt> library file can also
 be used to raise exceptions. See the <a href="#Library">SWIG Library</a>
 chapter.</p>
<h3><a name="Python_optimization">32.6.5 Optimization options</a></h3>
<h4><a name="Python_fastproxy">32.6.5.1 -fastproxy</a></h4>
<p> The <tt>-fastproxy</tt> command line option enables faster method
 calling as the call is made directly into the C/C++ layer rather than
 going through a method wrapper.</p>
<p> Consider wrapping a C++ class:</p>
<div class="code">
<pre>
struct Go {
  void callme0() {}
  void callme4(int a, int b, int c, int d) {}
  void callme8(double a, double b, double c, double d, double e, double f, double g, double i) {}
};
</pre>
</div>
<p> The default generated proxy class is:</p>
<div class="targetlang">
<pre>
class Go(object):
    def callme0(self):
        return _example.Go_callme0(self)

    def callme4(self, a, b, c, d):
        return _example.Go_callme4(self, a, b, c, d)

    def callme8(self, a, b, c, d, e, f, g, i):
        return _example.Go_callme8(self, a, b, c, d, e, f, g, i)
    ...
</pre>
</div>
<p> Each method in the Python class contains a Python proxy method which
 passes the arguments on to the underlying function in the low-level
 C/C++ module (_example in this case). The generated proxy class when
 using <tt>-fastproxy</tt> is:</p>
<div class="targetlang">
<pre>
%module example
class Go(object):
    callme0 = _swig_new_instance_method(_example.Go_callme0)
    callme4 = _swig_new_instance_method(_example.Go_callme4)
    callme8 = _swig_new_instance_method(_example.Go_callme8)
    ...
</pre>
</div>
<p> where <tt>_swig_new_instance_method</tt> adds the method to the
 proxy class via C API calls for direct access to the underlying
 function in the low-level C/C++ module. Note that for some methods it
 is not possible to generate the direct access call and so <tt>
-fastproxy</tt> is ignored. This happens, for example, when adding <a href="#Python_nn42">
additional code</a> to Python proxy methods, such as using <tt>
%pythonprepend</tt>.</p>
<p> The overhead calling into C/C++ from Python is reduced slightly
 using <tt>-fastproxy</tt>. Below are some timings in microseconds
 calling the 3 functions in the example above. Also included in the
 table for comparison is using the <tt>-builtin</tt> option covered in
 the <a href="#Python_builtin_types">Built-in Types</a>.</p>
<table summary="Python fastproxy performance">
<tr><th>Method name</th><th>Default</th><th>-fastproxy</th><th>-builtin</th>
</tr>
<tr><td>callme0</td><td>0.15</td><td>0.09</td><td>0.07</td></tr>
<tr><td>callme4</td><td>0.26</td><td>0.16</td><td>0.14</td></tr>
<tr><td>callme8</td><td>0.32</td><td>0.20</td><td>0.17</td></tr>
</table>
<p> Although the <tt>-fastproxy</tt> option results in faster code over
 the default, the generated proxy code is not as user-friendly as
 docstring/doxygen comments and functions with default values are not
 visible in the generated Python proxy class. The <tt>-olddefs</tt>
 option can rectify this.</p>
<p> The generated proxy class for the example above when using <tt>
-fastproxy -olddefs</tt> is:</p>
<div class="targetlang">
<pre>
class Go(object):
    def callme0(self):
        return _example.Go_callme0(self)
    callme0 = _swig_new_instance_method(_example.Go_callme0)

    def callme4(self, a, b, c, d):
        return _example.Go_callme4(self, a, b, c, d)
    callme4 = _swig_new_instance_method(_example.Go_callme4)

    def callme8(self, a, b, c, d, e, f, g, i):
        return _example.Go_callme8(self, a, b, c, d, e, f, g, i)
    callme8 = _swig_new_instance_method(_example.Go_callme8)
    ...
</pre>
</div>
<p> The class defines each method in two different ways. The first
 definition is replaced by the second definition and so the second
 definition is the one used when the method is called. While this
 possibly provides the best of both worlds, the time to import the
 module will be slightly slower when the class is defined due to the
 additional method definitions.</p>
<p> The command line options mentioned above also apply to wrapped C/C++
 global functions, not just class methods.</p>
<h2><a name="Python_nn45">32.7 Tips and techniques</a></h2>
<p> Although SWIG is largely automatic, there are certain types of
 wrapping problems that require additional user input. Examples include
 dealing with output parameters, strings, binary data, and arrays. This
 chapter discusses the common techniques for solving these problems.</p>
<h3><a name="Python_nn46">32.7.1 Input and output parameters</a></h3>
<p> A common problem in some C programs is handling parameters passed as
 simple pointers. For example:</p>
<div class="code">
<pre>
void add(int x, int y, int *result) {
  *result = x + y;
}
</pre>
</div>
<p> or perhaps</p>
<div class="code">
<pre>
int sub(int *x, int *y) {
  return *x-*y;
}
</pre>
</div>
<p> The easiest way to handle these situations is to use the <tt>
typemaps.i</tt> file. For example:</p>
<div class="code">
<pre>
%module example
%include &quot;typemaps.i&quot;

void add(int, int, int *OUTPUT);
int  sub(int *INPUT, int *INPUT);
</pre>
</div>
<p> In Python, this allows you to pass simple values. For example:</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; a = add(3, 4)
&gt;&gt;&gt; print a
7
&gt;&gt;&gt; b = sub(7, 4)
&gt;&gt;&gt; print b
3
&gt;&gt;&gt;
</pre>
</div>
<p> Notice how the <tt>INPUT</tt> parameters allow integer values to be
 passed instead of pointers and how the <tt>OUTPUT</tt> parameter
 creates a return result.</p>
<p> If you don't want to use the names <tt>INPUT</tt> or <tt>OUTPUT</tt>
, use the <tt>%apply</tt> directive. For example:</p>
<div class="code">
<pre>
%module example
%include &quot;typemaps.i&quot;

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

void add(int x, int y, int *result);
int  sub(int *x, int *y);
</pre>
</div>
<p> If a function mutates one of its parameters like this,</p>
<div class="code">
<pre>
void negate(int *x) {
  *x = -(*x);
}
</pre>
</div>
<p> you can use <tt>INOUT</tt> like this:</p>
<div class="code">
<pre>
%include &quot;typemaps.i&quot;
...
void negate(int *INOUT);
</pre>
</div>
<p> In Python, a mutated parameter shows up as a return value. For
 example:</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; a = negate(3)
&gt;&gt;&gt; print a
-3
&gt;&gt;&gt;
</pre>
</div>
<p> Note: Since most primitive Python objects are immutable, it is not
 possible to perform in-place modification of a Python object passed as
 a parameter.</p>
<p> The most common use of these special typemap rules is to handle
 functions that return more than one value. For example, sometimes a
 function returns a result as well as a special error code:</p>
<div class="code">
<pre>
/* send message, return number of bytes sent, along with success code */
int send_message(char *text, int len, int *success);
</pre>
</div>
<p> To wrap such a function, simply use the <tt>OUTPUT</tt> rule above.
 For example:</p>
<div class="code">
<pre>
%module example
%include &quot;typemaps.i&quot;
%apply int *OUTPUT { int *success };
...
int send_message(char *text, int *success);
</pre>
</div>
<p> When used in Python, the function will return multiple values.</p>
<div class="targetlang">
<pre>
bytes, success = send_message(&quot;Hello World&quot;)
if not success:
    print &quot;Whoa!&quot;
else:
    print &quot;Sent&quot;, bytes
</pre>
</div>
<p> Another common use of multiple return values are in query functions.
 For example:</p>
<div class="code">
<pre>
void get_dimensions(Matrix *m, int *rows, int *columns);
</pre>
</div>
<p> To wrap this, you might use the following:</p>
<div class="code">
<pre>
%module example
%include &quot;typemaps.i&quot;
%apply int *OUTPUT { int *rows, int *columns };
...
void get_dimensions(Matrix *m, int *rows, *columns);
</pre>
</div>
<p> Now, in Python:</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; r, c = get_dimensions(m)
</pre>
</div>
<p> Be aware that the primary purpose of the <tt>typemaps.i</tt> file is
 to support primitive datatypes. Writing a function like this</p>
<div class="code">
<pre>
void foo(Bar *OUTPUT);
</pre>
</div>
<p> may not have the intended effect since <tt>typemaps.i</tt> does not
 define an OUTPUT rule for <tt>Bar</tt>.</p>
<h3><a name="Python_nn47">32.7.2 Simple pointers</a></h3>
<p> If you must work with simple pointers such as <tt>int *</tt> or <tt>
double *</tt> and you don't want to use <tt>typemaps.i</tt>, consider
 using the <tt>cpointer.i</tt> library file. For example:</p>
<div class="code">
<pre>
%module example
%include &quot;cpointer.i&quot;

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

%pointer_functions(int, intp);
</pre>
</div>
<p> The <tt>%pointer_functions(type, name)</tt> macro generates five
 helper functions that can be used to create, destroy, copy, assign, and
 dereference a pointer. In this case, the functions are as follows:</p>
<div class="code">
<pre>
int  *new_intp();
int  *copy_intp(int *x);
void  delete_intp(int *x);
void  intp_assign(int *x, int value);
int   intp_value(int *x);
</pre>
</div>
<p> In Python, you would use the functions like this:</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; result = new_intp()
&gt;&gt;&gt; print result
_108fea8_p_int
&gt;&gt;&gt; add(3, 4, result)
&gt;&gt;&gt; print intp_value(result)
7
&gt;&gt;&gt;
</pre>
</div>
<p> If you replace <tt>%pointer_functions()</tt> by <tt>
%pointer_class(type, name)</tt>, the interface is more class-like.</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; result = intp()
&gt;&gt;&gt; add(3, 4, result)
&gt;&gt;&gt; print result.value()
7
</pre>
</div>
<p> See the <a href="#Library">SWIG Library</a> chapter for further
 details.</p>
<h3><a name="Python_nn48">32.7.3 Unbounded C Arrays</a></h3>
<p> Sometimes a C function expects an array to be passed as a pointer.
 For example,</p>
<div class="code">
<pre>
int sumitems(int *first, int nitems) {
  int i, sum = 0;
  for (i = 0; i &lt; nitems; i++) {
    sum += first[i];
  }
  return sum;
}
</pre>
</div>
<p> To wrap this into Python, you need to pass an array pointer as the
 first argument. A simple way to do this is to use the <tt>carrays.i</tt>
 library file. For example:</p>
<div class="code">
<pre>
%include &quot;carrays.i&quot;
%array_class(int, intArray);
</pre>
</div>
<p> The <tt>%array_class(type, name)</tt> macro creates wrappers for an
 unbounded array object that can be passed around as a simple pointer
 like <tt>int *</tt> or <tt>double *</tt>. For instance, you will be
 able to do this in Python:</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; a = intArray(10000000)         # Array of 10-million integers
&gt;&gt;&gt; for i in xrange(10000):        # Set some values
...     a[i] = i
&gt;&gt;&gt; sumitems(a, 10000)
49995000
&gt;&gt;&gt;
</pre>
</div>
<p> The array &quot;object&quot; created by <tt>%array_class()</tt> does not
 encapsulate pointers inside a special array object. In fact, there is
 no bounds checking or safety of any kind (just like in C). Because of
 this, the arrays created by this library are extremely low-level
 indeed. You can't iterate over them nor can you even query their
 length. In fact, any valid memory address can be accessed if you want
 (negative indices, indices beyond the end of the array, etc.). Needless
 to say, this approach is not going to suit all applications. On the
 other hand, this low-level approach is extremely efficient and well
 suited for applications in which you need to create buffers, package
 binary data, etc.</p>
<h3><a name="Python_nn49">32.7.4 String handling</a></h3>
<p> If a C function has an argument of <tt>char *</tt>, then a Python
 string can be passed as input. For example:</p>
<div class="code">
<pre>
// C
void foo(char *s);
</pre>
</div><div class="targetlang">
<pre>
# Python
&gt;&gt;&gt; foo(&quot;Hello&quot;)
</pre>
</div>
<p> When a Python string is passed as a parameter, the C function
 receives a pointer to the raw data contained in the string. Since
 Python strings are immutable, it is illegal for your program to change
 the value. In fact, doing so will probably crash the Python
 interpreter.</p>
<p> If your program modifies the input parameter or uses it to return
 data, consider using the <tt>cstring.i</tt> library file described in
 the <a href="#Library">SWIG Library</a> chapter.</p>
<p> When functions return a <tt>char *</tt>, it is assumed to be a
 NULL-terminated string. Data is copied into a new Python string and
 returned.</p>
<p> If your program needs to work with binary data, you can use a
 typemap to expand a Python string into a pointer/length argument pair.
 As luck would have it, just such a typemap is already defined. Just do
 this:</p>
<div class="code">
<pre>
%apply (char *STRING, int LENGTH) { (char *data, int size) };
...
int parity(char *data, int size, int initial);
</pre>
</div>
<p> Now in Python:</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; parity(&quot;e\x09ffss\x00\x00\x01\nx&quot;, 0)
</pre>
</div>
<p> If you need to return binary data, you might use the <tt>cstring.i</tt>
 library file. The <tt>cdata.i</tt> library can also be used to extra
 binary data from arbitrary pointers.</p>
<h3><a name="Python_default_args">32.7.5 Default arguments</a></h3>
<p> C++ default argument code generation is documented in the main <a href="#SWIGPlus_default_args">
Default arguments</a> section. There is also an optional Python specific
 feature that can be used called the <tt>python:cdefaultargs</tt> <a href="#Customization_feature_flags">
feature flag</a>. By default, SWIG attempts to convert C++ default
 argument values into Python values and generates code into the Python
 layer containing these values. For example:</p>
<div class="code">
<pre>
struct CDA {
  int fff(int a = 1, bool b = false);
};
</pre>
</div>
<p> From Python this can be called as follows:</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; CDA().fff()        # C++ layer receives a=1 and b=false
&gt;&gt;&gt; CDA().fff(2)       # C++ layer receives a=2 and b=false
&gt;&gt;&gt; CDA().fff(3, True) # C++ layer receives a=3 and b=true
</pre>
</div>
<p> The default code generation in the Python layer is:</p>
<div class="targetlang">
<pre>
class CDA(object):
    ...
    def fff(self, a=1, b=False):
        return _default_args.CDA_fff(self, a, b)
</pre>
</div>
<p> Adding the feature:</p>
<div class="code">
<pre>
%feature(&quot;python:cdefaultargs&quot;) CDA::fff;
struct CDA {
  int fff(int a = 1, bool b = false);
</pre>
</div>
<p> results in identical behaviour when called from Python, however, it
 results in different code generation:</p>
<div class="targetlang">
<pre>
class CDA(object):
    ...
    def fff(self, *args):
        return _default_args.CDA_fff(self, *args)
</pre>
</div>
<p> The default arguments are obtained in the C++ wrapper layer instead
 of the Python layer. Some code generation modes are quite different, eg
 <tt>-builtin</tt> and <tt>-fastproxy</tt>, and are unaffected by <tt>
python:cdefaultargs</tt> as the default values are always obtained from
 the C++ layer.</p>
<p> Note that not all default arguments can be converted into a Python
 equivalent. When SWIG does not convert them, it will generate code to
 obtain them from the C++ layer as if <tt>python:cdefaultargs</tt> was
 specified. This will happen if just one argument cannot be converted
 into a Python equivalent. This occurs typically when the argument is
 not fully numeric, such as <tt>int(1)</tt>:</p>
<div class="code">
<pre>
struct CDA {
  int fff(int a = int(1), bool b = false);
};
</pre>
</div>
<p><b> Compatibility Note:</b> SWIG-3.0.6 introduced the <tt>
python:cdefaultargs</tt> feature. Versions of SWIG prior to this varied
 in their ability to convert C++ default values into equivalent Python
 default argument values.</p>
<h2><a name="Python_nn53">32.8 Typemaps</a></h2>
<p> This section describes how you can modify SWIG's default wrapping
 behavior for various C/C++ datatypes using the <tt>%typemap</tt>
 directive. This is an advanced topic that assumes familiarity with the
 Python C API as well as the material in the &quot;<a href="#Typemaps">
Typemaps</a>&quot; chapter.</p>
<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 primitive C-Python interface or if you want to elevate your guru
 status.</p>
<h3><a name="Python_nn54">32.8.1 What is a typemap?</a></h3>
<p> A typemap is nothing more than a code generation rule that is
 attached to a specific C datatype. For example, to convert integers
 from Python to C, you might define a typemap like this:</p>
<div class="code">
<pre>
%module example

%typemap(in) int {
  $1 = (int) PyLong_AsLong($input);
  printf(&quot;Received an integer : %d\n&quot;, $1);
}
%inline %{
extern int fact(int n);
%}
</pre>
</div>
<p> Typemaps are always associated with some specific aspect of code
 generation. In this case, the &quot;in&quot; 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 variable prefaced by a
 <tt>$</tt> are used. The <tt>$1</tt> variable is placeholder for a
 local variable of type <tt>int</tt>. The <tt>$input</tt> variable is
 the input object of type <tt>PyObject *</tt>.</p>
<p> When this example is compiled into a Python module, it operates as
 follows:</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; from example import *
&gt;&gt;&gt; fact(6)
Received an integer : 6
720
</pre>
</div>
<p> In this example, the typemap is applied to all occurrences of the <tt>
int</tt> datatype. You can refine this by supplying an optional
 parameter name. For example:</p>
<div class="code">
<pre>
%module example

%typemap(in) int nonnegative {
  $1 = (int) PyLong_AsLong($input);
  if ($1 &lt; 0) {
    PyErr_SetString(PyExc_ValueError, &quot;Expected a nonnegative value.&quot;);
    SWIG_fail;
  }
}
%inline %{
extern int fact(int nonnegative);
%}
</pre>
</div>
<p> In this case, the typemap code is only attached to arguments that
 exactly match <tt>int nonnegative</tt>.</p>
<p> The application of a typemap to specific datatypes and argument
 names involves more than simple text-matching--typemaps are fully
 integrated into the SWIG C++ type-system. When you define a typemap for
 <tt>int</tt>, that typemap applies to <tt>int</tt> and qualified
 variations such as <tt>const int</tt>. In addition, the typemap system
 follows <tt>typedef</tt> declarations. For example:</p>
<div class="code">
<pre>
%typemap(in) int n {
  $1 = (int) PyLong_AsLong($input);
  printf(&quot;n = %d\n&quot;, $1);
}
%inline %{
typedef int Integer;
extern int fact(Integer n);    // Above typemap is applied
%}
</pre>
</div>
<p> Typemaps can also be defined for groups of consecutive arguments.
 For example:</p>
<div class="code">
<pre>
%typemap(in) (char *str, int len) {
  $1 = PyString_AsString($input);
  $2 = PyString_Size($input);
};

int count(char c, char *str, int len);
</pre>
</div>
<p> When a multi-argument typemap is defined, the arguments are always
 handled as a single Python object. This allows the function to be used
 like this (notice how the length parameter is omitted):</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; example.count('e', 'Hello World')
1
&gt;&gt;&gt;
</pre>
</div>
<h3><a name="Python_nn55">32.8.2 Python typemaps</a></h3>
<p> The previous section illustrated an &quot;in&quot; typemap for converting
 Python objects to C. A variety of different typemap methods are defined
 by the Python module. For example, to convert a C integer back into a
 Python object, you might define an &quot;out&quot; typemap like this:</p>
<div class="code">
<pre>
%typemap(out) int {
    $result = PyInt_FromLong((long) $1);
}
</pre>
</div>
<p> A detailed list of available methods can be found in the &quot;<a href="#Typemaps">
Typemaps</a>&quot; chapter.</p>
<p> However, the best source of typemap information (and examples) is
 probably the Python module itself. In fact, all of SWIG's default type
 handling is defined by typemaps. You can view these typemaps by looking
 at the files in the SWIG library. Just take into account that in the
 latest versions of swig (1.3.22+), the library files are not very
 pristine clear for the casual reader, as they used to be. The extensive
 use of macros and other ugly techniques in the latest version produce a
 very powerful and consistent Python typemap library, but at the cost of
 simplicity and pedagogic value.</p>
<p> To learn how to write a simple or your first typemap, you better
 take a look at the SWIG library version 1.3.20 or so.</p>
<h3><a name="Python_nn56">32.8.3 Typemap variables</a></h3>
<p> Within typemap code, a number of special variables prefaced with a <tt>
$</tt> may appear. A full list of variables can be found in the &quot;<a href="#Typemaps">
Typemaps</a>&quot; chapter. This is a list of the most common variables:</p>
<p> <tt>$1</tt></p>
<div class="indent"> A C local variable corresponding to the actual type
 specified in the <tt>%typemap</tt> directive. For input values, this is
 a C local variable that's supposed to hold an argument value. For
 output values, this is the raw result that's supposed to be returned to
 Python.</div>
<p> <tt>$input</tt></p>
<div class="indent"> A <tt>PyObject *</tt> holding a raw Python object
 with an argument or variable value.</div>
<p> <tt>$result</tt></p>
<div class="indent"> A <tt>PyObject *</tt> that holds the result to be
 returned to Python.</div>
<p> <tt>$1_name</tt></p>
<div class="indent"> The parameter name that was matched.</div>
<p> <tt>$1_type</tt></p>
<div class="indent"> The actual C datatype matched by the typemap.</div>
<p> <tt>$1_ltype</tt></p>
<div class="indent"> An assignable version of the datatype matched by
 the typemap (a type that can appear on the left-hand-side of a C
 assignment operation). This type is stripped of qualifiers and may be
 an altered version of <tt>$1_type</tt>. All arguments and local
 variables in wrapper functions are declared using this type so that
 their values can be properly assigned.</div>
<p> <tt>$symname</tt></p>
<div class="indent"> The Python name of the wrapper function being
 created.</div>
<h3><a name="Python_nn57">32.8.4 Useful Python Functions</a></h3>
<p> When you write a typemap, you usually have to work directly with
 Python objects. The following functions may prove to be useful.</p>
<p><b> Python Integer Functions</b></p>
<div class="code">
<pre>
PyObject *PyInt_FromLong(long l);
long      PyInt_AsLong(PyObject *);
int       PyInt_Check(PyObject *);
</pre>
</div>
<p><b> Python Floating Point Functions</b></p>
<div class="code">
<pre>
PyObject *PyFloat_FromDouble(double);
double    PyFloat_AsDouble(PyObject *);
int       PyFloat_Check(PyObject *);
</pre>
</div>
<p><b> Python String Functions</b></p>
<div class="code">
<pre>
PyObject *PyString_FromString(char *);
PyObject *PyString_FromStringAndSize(char *, lint len);
int       PyString_Size(PyObject *);
char     *PyString_AsString(PyObject *);
int       PyString_Check(PyObject *);
</pre>
</div>
<p><b> Python List Functions</b></p>
<div class="code">
<pre>
PyObject *PyList_New(int size);
int       PyList_Size(PyObject *list);
PyObject *PyList_GetItem(PyObject *list, int i);
int       PyList_SetItem(PyObject *list, int i, PyObject *item);
int       PyList_Insert(PyObject *list, int i, PyObject *item);
int       PyList_Append(PyObject *list, PyObject *item);
PyObject *PyList_GetSlice(PyObject *list, int i, int j);
int       PyList_SetSlice(PyObject *list, int i, int , PyObject *list2);
int       PyList_Sort(PyObject *list);
int       PyList_Reverse(PyObject *list);
PyObject *PyList_AsTuple(PyObject *list);
int       PyList_Check(PyObject *);
</pre>
</div>
<p><b> Python Tuple Functions</b></p>
<div class="code">
<pre>
PyObject *PyTuple_New(int size);
int       PyTuple_Size(PyObject *);
PyObject *PyTuple_GetItem(PyObject *, int i);
int       PyTuple_SetItem(PyObject *, int i, PyObject *item);
PyObject *PyTuple_GetSlice(PyObject *t, int i, int j);
int       PyTuple_Check(PyObject *);
</pre>
</div>
<p><b> Python Dictionary Functions</b></p>
<div class="code">
<pre>
PyObject *PyDict_New();
int       PyDict_Check(PyObject *);
int       PyDict_SetItem(PyObject *p, PyObject *key, PyObject *val);
int       PyDict_SetItemString(PyObject *p, const char *key, PyObject *val);
int       PyDict_DelItem(PyObject *p, PyObject *key);
int       PyDict_DelItemString(PyObject *p, char *key);
PyObject* PyDict_Keys(PyObject *p);
PyObject* PyDict_Values(PyObject *p);
PyObject* PyDict_GetItem(PyObject *p, PyObject *key);
PyObject* PyDict_GetItemString(PyObject *p, const char *key);
int       PyDict_Next(PyObject *p, Py_ssize_t *ppos, PyObject **pkey, PyObject **pvalue);
Py_ssize_t PyDict_Size(PyObject *p);
int       PyDict_Update(PyObject *a, PyObject *b);
int       PyDict_Merge(PyObject *a, PyObject *b, int override);
PyObject* PyDict_Items(PyObject *p);
</pre>
</div>
<p><b> Python File Conversion Functions</b></p>
<div class="code">
<pre>
PyObject *PyFile_FromFile(FILE *f);
FILE     *PyFile_AsFile(PyObject *);
int       PyFile_Check(PyObject *);
</pre>
</div>
<p><b> Abstract Object Interface</b></p>
<div class="code">
<pre>
write me
</pre>
</div>
<h2><a name="Python_nn58">32.9 Typemap Examples</a></h2>
<p> This section includes a few examples of typemaps. For more examples,
 you might look at the files &quot;<tt>python.swg</tt>&quot; and &quot;<tt>typemaps.i</tt>
&quot; in the SWIG library.</p>
<h3><a name="Python_nn59">32.9.1 Converting Python list to a char **</a></h3>
<p> A common problem in many C programs is the processing of command
 line arguments, which are usually passed in an array of NULL terminated
 strings. The following SWIG interface file allows a Python list object
 to be used as a <tt>char **</tt> object.</p>
<div class="code">
<pre>
%module argv

// This tells SWIG to treat char ** as a special case
%typemap(in) char ** {
  /* Check if is a list */
  if (PyList_Check($input)) {
    int size = PyList_Size($input);
    int i = 0;
    $1 = (char **) malloc((size+1)*sizeof(char *));
    for (i = 0; i &lt; size; i++) {
      PyObject *o = PyList_GetItem($input, i);
      if (PyString_Check(o)) {
        $1[i] = PyString_AsString(PyList_GetItem($input, i));
      } else {
        free($1);
        PyErr_SetString(PyExc_TypeError, &quot;list must contain strings&quot;);
        SWIG_fail;
      }
    }
    $1[i] = 0;
  } else {
    PyErr_SetString(PyExc_TypeError, &quot;not a list&quot;);
    SWIG_fail;
  }
}

// This cleans up the char ** array we malloc'd before the function call
%typemap(freearg) char ** {
  free((char *) $1);
}

// Now a test function
%inline %{
int print_args(char **argv) {
  int i = 0;
  while (argv[i]) {
    printf(&quot;argv[%d] = %s\n&quot;, i, argv[i]);
    i++;
  }
  return i;
}
%}

</pre>
</div>
<p> When this module is compiled, the wrapped C function now operates as
 follows :</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; from argv import *
&gt;&gt;&gt; print_args([&quot;Dave&quot;, &quot;Mike&quot;, &quot;Mary&quot;, &quot;Jane&quot;, &quot;John&quot;])
argv[0] = Dave
argv[1] = Mike
argv[2] = Mary
argv[3] = Jane
argv[4] = John
5
</pre>
</div>
<p> In the example, two different typemaps are used. The &quot;in&quot; 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
 &quot;freearg&quot; typemap is used to later release this memory after the
 execution of the C function.</p>
<h3><a name="Python_nn60">32.9.2 Expanding a Python object into multiple
 arguments</a></h3>
<p> Suppose that you had a collection of C functions with arguments such
 as the following:</p>
<div class="code">
<pre>
int foo(int argc, char **argv);
</pre>
</div>
<p> In the previous example, a typemap was written to pass a Python list
 as the <tt>char **argv</tt>. This allows the function to be used from
 Python as follows:</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; foo(4, [&quot;foo&quot;, &quot;bar&quot;, &quot;spam&quot;, &quot;1&quot;])
</pre>
</div>
<p> Although this works, it's a little awkward to specify the argument
 count. To fix this, a multi-argument typemap can be defined. This is
 not very difficult--you only have to make slight modifications to the
 previous example:</p>
<div class="code">
<pre>
%typemap(in) (int argc, char **argv) {
  /* Check if is a list */
  if (PyList_Check($input)) {
    int i;
    $1 = PyList_Size($input);
    $2 = (char **) malloc(($1+1)*sizeof(char *));
    for (i = 0; i &lt; $1; i++) {
      PyObject *o = PyList_GetItem($input, i);
      if (PyString_Check(o)) {
        $2[i] = PyString_AsString(PyList_GetItem($input, i));
      } else {
        free($2);
        PyErr_SetString(PyExc_TypeError, &quot;list must contain strings&quot;);
        SWIG_fail;
      }
    }
    $2[i] = 0;
  } else {
    PyErr_SetString(PyExc_TypeError, &quot;not a list&quot;);
    SWIG_fail;
  }
}

%typemap(freearg) (int argc, char **argv) {
  free((char *) $2);
}
</pre>
</div>
<p> When writing a multiple-argument typemap, each of the types is
 referenced by a variable such as <tt>$1</tt> or <tt>$2</tt>. The
 typemap code simply fills in the appropriate values from the supplied
 Python object.</p>
<p> With the above typemap in place, you will find it no longer
 necessary to supply the argument count. This is automatically set by
 the typemap code. For example:</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; foo([&quot;foo&quot;, &quot;bar&quot;, &quot;spam&quot;, &quot;1&quot;])
</pre>
</div>
<p> If your function is overloaded in C++, for example:</p>
<div class="code">
<pre>
int foo(int argc, char **argv);
int foo();
</pre>
</div>
<p> don't forget to also provide a suitable <a href="#Typemaps_overloading">
typecheck typemap for overloading</a> such as:</p>
<div class="code">
<pre>
%typecheck(SWIG_TYPECHECK_STRING_ARRAY) (int argc, char **argv) {
  $1 = PyList_Check($input) ? 1 : 0;
}
</pre>
</div>
<p> If you don't you'll get an error message along the lines of:</p>
<div class="shell">
<pre>
Traceback (most recent call last):
  File &quot;runme.py&quot;, line 3, in &gt;module&lt;
    example.foo([&quot;foo&quot;, &quot;bar&quot;, &quot;spam&quot;, &quot;1&quot;])
TypeError: Wrong number or type of arguments for overloaded function 'foo'.
  Possible C/C++ prototypes are:
    foo(int, char **)
    foo()
</pre>
</div>
<h3><a name="Python_nn61">32.9.3 Using typemaps to return arguments</a></h3>
<p> A common problem in some C programs is that values may be returned
 in arguments rather than in the return value of a function. For
 example:</p>
<div class="code">
<pre>
/* Returns a status value and two values in out1 and out2 */
int spam(double a, double b, double *out1, double *out2) {
  ... Do a bunch of stuff ...
  *out1 = result1;
  *out2 = result2;
  return status;
}
</pre>
</div>
<p> A typemap can be used to handle this case as follows :</p>
<div class="code">
<pre>
%module outarg

// This tells SWIG to treat an double * argument with name 'OutValue' as
// an output value.  We'll append the value to the current result which
// is guaranteed to be a List object by SWIG.

%typemap(argout) double *OutValue {
  PyObject *o, *o2, *o3;
  o = PyFloat_FromDouble(*$1);
  if ((!$result) || ($result == Py_None)) {
    $result = o;
  } else {
    if (!PyTuple_Check($result)) {
      PyObject *o2 = $result;
      $result = PyTuple_New(1);
      PyTuple_SetItem($result, 0, o2);
    }
    o3 = PyTuple_New(1);
    PyTuple_SetItem(o3, 0, o);
    o2 = $result;
    $result = PySequence_Concat(o2, o3);
    Py_DECREF(o2);
    Py_DECREF(o3);
  }
}

int spam(double a, double b, double *OutValue, double *OutValue);

</pre>
</div>
<p> The typemap works as follows. First, a check is made to see if any
 previous result exists. If so, it is turned into a tuple and the new
 output value is concatenated to it. Otherwise, the result is returned
 normally. For the sample function <tt>spam()</tt>, there are three
 output values--meaning that the function will return a 3-tuple of the
 results.</p>
<p> As written, the function must accept 4 arguments as input values,
 last two being pointers to doubles. If these arguments are only used to
 hold output values (and have no meaningful input value), an additional
 typemap can be written. For example:</p>
<div class="code">
<pre>
%typemap(in, numinputs=0) double *OutValue(double temp) {
  $1 = &amp;temp;
}

</pre>
</div>
<p> By specifying numinputs=0, the input value is ignored. However,
 since the argument still has to be set to some meaningful value before
 calling C, it is set to point to a local variable <tt>temp</tt>. When
 the function stores its output value, it will simply be placed in this
 local variable. As a result, the function can now be used as follows:</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; a = spam(4, 5)
&gt;&gt;&gt; print a
(0, 2.45, 5.0)
&gt;&gt;&gt; x, y, z = spam(4, 5)
&gt;&gt;&gt;
</pre>
</div>
<h3><a name="Python_nn62">32.9.4 Mapping Python tuples into small arrays</a>
</h3>
<p> In some applications, it is sometimes desirable to pass small arrays
 of numbers as arguments. For example :</p>
<div class="code">
<pre>
extern void set_direction(double a[4]);       // Set direction vector
</pre>
</div>
<p> This too, can be handled used typemaps as follows :</p>
<div class="code">
<pre>
// Grab a 4 element array as a Python 4-tuple
%typemap(in) double[4](double temp[4]) {   // temp[4] becomes a local variable
  int i;
  if (PyTuple_Check($input)) {
    if (!PyArg_ParseTuple($input, &quot;dddd&quot;, temp, temp+1, temp+2, temp+3)) {
      PyErr_SetString(PyExc_TypeError, &quot;tuple must have 4 elements&quot;);
      SWIG_fail;
    }
    $1 = &amp;temp[0];
  } else {
    PyErr_SetString(PyExc_TypeError, &quot;expected a tuple.&quot;);
    SWIG_fail;
  }
}

</pre>
</div>
<p> This allows our <tt>set_direction</tt> function to be called from
 Python as follows :</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; set_direction((0.5, 0.0, 1.0, -0.25))
</pre>
</div>
<p> Since our mapping copies the contents of a Python tuple into a C
 array, such an approach would not be recommended for huge arrays, but
 for small structures, this approach works fine.</p>
<h3><a name="Python_nn63">32.9.5 Mapping sequences to C arrays</a></h3>
<p> Suppose that you wanted to generalize the previous example to handle
 C arrays of different sizes. To do this, you might write a typemap as
 follows:</p>
<div class="code">
<pre>
// Map a Python sequence into any sized C double array
%typemap(in) double[ANY](double temp[$1_dim0]) {
  int i;
  if (!PySequence_Check($input)) {
    PyErr_SetString(PyExc_TypeError, &quot;Expecting a sequence&quot;);
    SWIG_fail;
  }
  if (PyObject_Length($input) != $1_dim0) {
    PyErr_SetString(PyExc_ValueError, &quot;Expecting a sequence with $1_dim0 elements&quot;);
    SWIG_fail;
  }
  for (i =0; i &lt; $1_dim0; i++) {
    PyObject *o = PySequence_GetItem($input, i);
    if (!PyFloat_Check(o)) {
      Py_XDECREF(o);
      PyErr_SetString(PyExc_ValueError, &quot;Expecting a sequence of floats&quot;);
      SWIG_fail;
    }
    temp[i] = PyFloat_AsDouble(o);
    Py_DECREF(o);
  }
  $1 = &amp;temp[0];
}
</pre>
</div>
<p> In this case, the variable <tt>$1_dim0</tt> is expanded to match the
 array dimensions actually used in the C code. This allows the typemap
 to be applied to types such as:</p>
<div class="code">
<pre>
void foo(double x[10]);
void bar(double a[4], double b[8]);
</pre>
</div>
<p> Since the above typemap code gets inserted into every wrapper
 function where used, it might make sense to use a helper function
 instead. This will greatly reduce the amount of wrapper code. For
 example:</p>
<div class="code">
<pre>
%{
static int convert_darray(PyObject *input, double *ptr, int size) {
  int i;
  if (!PySequence_Check(input)) {
    PyErr_SetString(PyExc_TypeError, &quot;Expecting a sequence&quot;);
    return 0;
  }
  if (PyObject_Length(input) != size) {
    PyErr_SetString(PyExc_ValueError, &quot;Sequence size mismatch&quot;);
    return 0;
  }
  for (i =0; i &lt; size; i++) {
    PyObject *o = PySequence_GetItem(input, i);
    if (!PyFloat_Check(o)) {
      Py_XDECREF(o);
      PyErr_SetString(PyExc_ValueError, &quot;Expecting a sequence of floats&quot;);
      return 0;
    }
    ptr[i] = PyFloat_AsDouble(o);
    Py_DECREF(o);
  }
  return 1;
}
%}

%typemap(in) double [ANY](double temp[$1_dim0]) {
  if (!convert_darray($input, temp, $1_dim0)) {
    SWIG_fail;
  }
  $1 = &amp;temp[0];
}
</pre>
</div>
<h3><a name="Python_nn64">32.9.6 Pointer handling</a></h3>
<p> Occasionally, it might be necessary to convert pointer values that
 have been stored using the SWIG typed-pointer representation. Since
 there are several ways in which pointers can be represented, the
 following two functions are used to safely perform this conversion:</p>
<p> <tt>int SWIG_ConvertPtr(PyObject *obj, void **ptr, swig_type_info
 *ty, int flags)</tt></p>
<div class="indent"> Converts a Python object <tt>obj</tt> to a C
 pointer. The result of the conversion is placed into the pointer
 located at <tt>ptr</tt>. <tt>ty</tt> is a SWIG type descriptor
 structure. <tt>flags</tt> is used to handle error checking and other
 aspects of conversion. It is the bitwise-or of several flag values
 including <tt>SWIG_POINTER_EXCEPTION</tt> and <tt>SWIG_POINTER_DISOWN</tt>
. The first flag makes the function raise an exception on type error.
 The second flag additionally steals ownership of an object. Returns 0
 on success and -1 on error.</div>
<p> <tt>PyObject *SWIG_NewPointerObj(void *ptr, swig_type_info *ty, int
 own)</tt></p>
<div class="indent"> Creates a new Python pointer object. <tt>ptr</tt>
 is the pointer to convert, <tt>ty</tt> is the SWIG type descriptor
 structure that describes the type, and <tt>own</tt> is a flag that
 indicates whether or not Python should take ownership of the pointer.</div>
<p> Both of these functions require the use of a special SWIG
 type-descriptor structure. This structure contains information about
 the mangled name of the datatype, type-equivalence information, as well
 as information about converting pointer values under C++ inheritance.
 For a type of <tt>Foo *</tt>, the type descriptor structure is usually
 accessed as follows:</p>
<div class="code">
<pre>
Foo *f;
if (!SWIG_IsOK(SWIG_ConvertPtr($input, (void **) &amp;f, SWIGTYPE_p_Foo, 0))) {
  SWIG_exception_fail(SWIG_TypeError, &quot;in method '$symname', expecting type Foo&quot;);
}

PyObject *obj;
obj = SWIG_NewPointerObj(f, SWIGTYPE_p_Foo, 0);
</pre>
</div>
<p> In a typemap, the type descriptor should always be accessed using
 the special typemap variable <tt>$1_descriptor</tt>. For example:</p>
<div class="code">
<pre>
%typemap(in) Foo * {
  if (!SWIG_IsOK(SWIG_ConvertPtr($input, (void **) &amp;$1, $1_descriptor, 0))) {
    SWIG_exception_fail(SWIG_TypeError, &quot;in method '$symname', expecting type Foo&quot;);
  }
}
</pre>
</div>
<p> If necessary, the descriptor for any type can be obtained using the <tt>
$descriptor()</tt> macro in a typemap. For example:</p>
<div class="code">
<pre>
%typemap(in) Foo * {
  if (!SWIG_IsOK(SWIG_ConvertPtr($input, (void **) &amp;$1, $descriptor(Foo *), 0))) {
    SWIG_exception_fail(SWIG_TypeError, &quot;in method '$symname', expecting type Foo&quot;);
  }
}
</pre>
</div>
<p> Although the pointer handling functions are primarily intended for
 manipulating low-level pointers, both functions are fully aware of
 Python proxy classes. Specifically, <tt>SWIG_ConvertPtr()</tt> will
 retrieve a pointer from any object that has a <tt>this</tt> attribute.
 In addition, <tt>SWIG_NewPointerObj()</tt> can automatically generate a
 proxy class object (if applicable).</p>
<h3><a name="Python_memory_management_member_variables">32.9.7 Memory
 management when returning references to member variables</a></h3>
<p> This example shows how to prevent premature garbage collection of
 objects when the underlying C++ class returns a pointer or reference to
 a member variable. The example is a direct equivalent to this <a href="#Java_memory_management_objects">
Java equivalent</a>.</p>
<p> Consider the following C++ code:</p>
<div class="code">
<pre>
#include &lt;iostream&gt;
struct Wheel {
  int size;
  Wheel(int sz = 0) : size(sz) {}
  ~Wheel() { std::cout &lt;&lt; &quot;~Wheel&quot; &lt;&lt; std::endl; }
};

class Bike {
  Wheel wheel;
public:
  Bike(int val) : wheel(val) {}
  Wheel&amp; getWheel() { return wheel; }
};
</pre>
</div>
<p> and the following usage from Python after running the code through
 SWIG:</p>
<div class="code">
<pre>
bike = Bike(10)
wheel = bike.getWheel()
print(&quot;wheel size: {}&quot;.format(wheel.size))

del bike  # Allow bike to be garbage collected
print(&quot;wheel size: {}&quot;.format(wheel.size))
</pre>
</div>
<p> Don't be surprised that if the resulting output gives strange
 results such as...</p>
<div class="shell">
<pre>
wheel size: 10
~Wheel
wheel size: 135019664
</pre>
</div>
<p> What has happened here is the garbage collector has collected the <tt>
Bike</tt> instance as it doesn't think it is needed any more. The proxy
 instance, <tt>wheel</tt>, contains a reference to memory that was
 deleted when the <tt>Bike</tt> instance was collected. In order to
 prevent the garbage collector from collecting the <tt>Bike</tt>
 instance, a reference to the <tt>Bike</tt> must be added to the <tt>
wheel</tt> instance.</p>
<p> You can do this by adding the reference when the <tt>getWheel()</tt>
 method is called using one of three approaches:</p>
<p> The easier, but less optimized, way is to use the <tt>%pythonappend</tt>
 directive (see <a href="#Python_nn42">Adding additional Python code</a>
):</p>
<div class="code">
<pre>
%pythonappend getWheel %{
  # val is the Wheel proxy, self is the Bike instance
  val.__bike_reference = self
%}
</pre>
</div>
<p> The code gets appended to the Python code generated for the <tt>
Bike::getWheel</tt> wrapper function, where we store the <tt>Bike</tt>
 proxy instance onto the <tt>Wheel</tt> proxy instance before it is
 returned to the caller as follows.</p>
<div class="targetlang">
<pre>
class Bike(object):
    ...
    def getWheel(self):
        val = _example.Bike_getWheel(self)

        # val is the Wheel proxy, self is the Bike instance
        val.__bike_reference = self

        return val
</pre>
</div>
<p> The second option, which performs better and is required if you use
 the <tt>-builtin</tt> option, is to set the reference in the CPython
 implementation:<div class="code">
<pre>
%extend Wheel {
// A reference to the parent class is added to ensure the underlying C++
// object is not deleted while the item is in use
%typemap(ret) Wheel&amp; getWheel {
  PyObject *bike_reference_string = SWIG_Python_str_FromChar(&quot;__bike_reference&quot;);
  PyObject_SetAttr($result, bike_reference_string, $self);
  Py_DecRef(bike_reference_string);
}
}
</pre>
</div></p>
<p> The third approach, shown below, is an optimization of the above
 approach and creates the &quot;__bike_reference&quot; Python string object just
 once. While this looks more complex, it is just a small variation on
 the above typemap plus a support function <tt>bike_reference()</tt> in
 a fragment called <tt>bike_reference_function</tt>. The <tt>
bike_reference_init</tt> typemap generates code into the &quot;init&quot; section
 for an initial call to <tt>bike_reference()</tt> when the module is
 initialized and is done to create the &quot;__bike_reference&quot; Python string
 singleton in a thread-safe manner.</p>
<div class="code">
<pre>
%fragment(&quot;bike_reference_init&quot;, &quot;init&quot;) {
  // Thread-safe initialization - initialize during Python module initialization
  bike_reference();
}

%fragment(&quot;bike_reference_function&quot;, &quot;header&quot;, fragment=&quot;bike_reference_init&quot;) {

static PyObject *bike_reference() {
  static PyObject *bike_reference_string = SWIG_Python_str_FromChar(&quot;__bike_reference&quot;);
  return bike_reference_string;
}

}

%extend Wheel {
// A reference to the parent class is added to ensure the underlying C++
// object is not deleted while the item is in use
%typemap(ret, fragment=&quot;bike_reference_function&quot;) Wheel&amp; getWheel %{
  PyObject_SetAttr($result, bike_reference(), $self);
%}
}
</pre>
</div>
<h2><a name="Python_nn65">32.10 Docstring Features</a></h2>
<p> Using docstrings in Python code is becoming more and more important
 and more tools are coming on the scene that take advantage of them,
 everything from full-blown documentation generators to class browsers
 and popup call-tips in Python-aware IDEs. Given the way that SWIG
 generates the proxy code by default, your users will normally get
 something like <tt>&quot;function_name(*args)&quot;</tt> in the popup calltip of
 their IDE which is next to useless when the real function prototype
 might be something like this:</p>
<div class="code">
<pre>
bool function_name(int x, int y, Foo* foo=NULL, Bar* bar=NULL);
</pre>
</div>
<p> The features described in this section make it easy for you to add
 docstrings to your modules, functions and methods that can then be used
 by the various tools out there to make the programming experience of
 your users much simpler.</p>
<h3><a name="Python_nn66">32.10.1 Module docstring</a></h3>
<p> Python allows a docstring at the beginning of the <tt>.py</tt> file
 before any other statements, and it is typically used to give a general
 description of the entire module. SWIG supports this by setting an
 option of the <tt>%module</tt> directive. For example:</p>
<div class="code">
<pre>
%module(docstring=&quot;This is the example module's docstring&quot;) example
</pre>
</div>
<p> When you have more than just a line or so then you can retain the
 easy readability of the <tt>%module</tt> directive by using a macro.
 For example:</p>
<div class="code">
<pre>
%define DOCSTRING
&quot;The `XmlResource` class allows program resources defining menus,
layout of controls on a panel, etc. to be loaded from an XML file.&quot;
%enddef

%module(docstring=DOCSTRING) xrc
</pre>
</div>
<h3><a name="Python_nn67">32.10.2 %feature(&quot;autodoc&quot;)</a></h3>
<p> As alluded to above SWIG will generate all the function and method
 proxy wrappers with just &quot;*args&quot; (or &quot;*args, **kwargs&quot; if the -keyword
 option is used) for a parameter list and will then sort out the
 individual parameters in the C wrapper code. This is nice and simple
 for the wrapper code, but makes it difficult to be programmer and tool
 friendly as anyone looking at the <tt>.py</tt> file will not be able to
 find out anything about the parameters that the functions accept.</p>
<p>But since SWIG does know everything about the function it is possible
 to generate a docstring containing the parameter types, names and
 default values. Since many of the docstring tools are adopting a
 standard of recognizing if the first thing in the docstring is a
 function prototype then using that instead of what they found from
 introspection, then life is good once more.</p>
<p>SWIG's Python module provides support for the &quot;autodoc&quot; feature,
 which when attached to a node in the parse tree will cause a docstring
 to be generated that includes the name of the function, parameter
 names, default values if any, and return type if any. There are also
 four levels for autodoc controlled by the value given to the feature, <tt>
%feature(&quot;autodoc&quot;, &quot;<i>level</i>&quot;)</tt>. The four values for<i> level</i>
 are covered in the following sub-sections.</p>
<h4><a name="Python_nn68">32.10.2.1 %feature(&quot;autodoc&quot;, &quot;0&quot;)</a></h4>
<p> When level &quot;0&quot; is used then the types of the parameters will<em> not</em>
 be included in the autodoc string. For example, given this function
 prototype:</p>
<div class="code">
<pre>
%feature(&quot;autodoc&quot;, &quot;0&quot;);
bool function_name(int x, int y, Foo* foo=NULL, Bar* bar=NULL);
</pre>
</div>
<p> Then Python code like this will be generated:</p>
<div class="targetlang">
<pre>
def function_name(*args, **kwargs):
    &quot;&quot;&quot;function_name(x, y, foo=None, bar=None) -&gt; bool&quot;&quot;&quot;
    ...
</pre>
</div>
<h4><a name="Python_nn69">32.10.2.2 %feature(&quot;autodoc&quot;, &quot;1&quot;)</a></h4>
<p> When level &quot;1&quot; is used then the parameter types<em> will</em> be
 used in the autodoc string. In addition, an attempt is made to simplify
 the type name such that it makes more sense to the Python user.
 Pointer, reference and const info is removed if the associated type is
 has an associated Python type (<tt>%rename</tt>'s are thus shown
 correctly). This works most of the time, otherwise a C/C++ type will be
 used. See the next section for the &quot;docstring&quot; feature for tweaking the
 docstrings to your liking. Given the example above, then turning on the
 parameter types with level &quot;1&quot; will result in Python code like this:</p>
<div class="targetlang">
<pre>
def function_name(*args, **kwargs):
    &quot;&quot;&quot;function_name(int x, int y, Foo foo=None, Bar bar=None) -&gt; bool&quot;&quot;&quot;
    ...
</pre>
</div>
<h4><a name="Python_autodoc2">32.10.2.3 %feature(&quot;autodoc&quot;, &quot;2&quot;)</a></h4>
<p> Level &quot;2&quot; results in the function prototype as per level &quot;0&quot;. In
 addition, a line of documentation is generated for each parameter using
 <a href="https://github.com/numpy/numpy/blob/master/doc/HOWTO_DOCUMENT.rst.txt">
numpydoc</a> style. Using the previous example, the generated code will
 be:</p>
<div class="targetlang">
<pre>
def function_name(*args, **kwargs):
    &quot;&quot;&quot;
    function_name(x, y, foo=None, bar=None) -&gt; bool

    Parameters
    ----------
    x: int
    y: int
    foo: Foo *
    bar: Bar *

    &quot;&quot;&quot;
    ...
</pre>
</div>
<p> Note that the documentation for each parameter is sourced from the
 &quot;doc&quot; typemap which by default shows the C/C++ type rather than the
 simplified Python type name described earlier for level &quot;1&quot;. Typemaps
 can of course change the output for any particular type, for example
 the <tt>int x</tt> parameter:</p>
<div class="code">
<pre>
%feature(&quot;autodoc&quot;, &quot;2&quot;);
%typemap(&quot;doc&quot;) int x &quot;$1_name (C++ type: $1_type) -- Input $1_name dimension&quot;
bool function_name(int x, int y, Foo* foo=NULL, Bar* bar=NULL);
</pre>
</div>
<p> resulting in</p>
<div class="targetlang">
<pre>
def function_name(*args, **kwargs):
    &quot;&quot;&quot;
    function_name(x, y, foo=None, bar=None) -&gt; bool

    Parameters
    ----------
    x (C++ type: int) -- Input x dimension
    y: int
    foo: Foo *
    bar: Bar *

    &quot;&quot;&quot;
</pre>
</div>
<h4><a name="Python_autodoc3">32.10.2.4 %feature(&quot;autodoc&quot;, &quot;3&quot;)</a></h4>
<p> Level &quot;3&quot; results in the function prototype as per level &quot;1&quot; but
 also contains the same additional line of documentation for each
 parameter as per level &quot;2&quot;. Using our earlier example again, the
 generated code will be:</p>
<div class="targetlang">
<pre>
def function_name(*args, **kwargs):
    &quot;&quot;&quot;
    function_name(int x, int y, Foo foo=None, Bar bar=None) -&gt; bool

    Parameters
    ----------
    x: int
    y: int
    foo: Foo *
    bar: Bar *

    &quot;&quot;&quot;
    ...
</pre>
</div>
<h4><a name="Python_nn70">32.10.2.5 %feature(&quot;autodoc&quot;, &quot;docstring&quot;)</a></h4>
<p> Finally, there are times when the automatically generated autodoc
 string will make no sense for a Python programmer, particularly when a
 typemap is involved. So if you give an explicit value for the autodoc
 feature then that string will be used in place of the automatically
 generated string. For example:</p>
<div class="code">
<pre>
%feature(&quot;autodoc&quot;, &quot;GetPosition() -&gt; (x, y)&quot;) GetPosition;
void GetPosition(int* OUTPUT, int* OUTPUT);
</pre>
</div>
<h3><a name="Python_nn71">32.10.3 %feature(&quot;docstring&quot;)</a></h3>
<p> In addition to the autodoc strings described above, you can also
 attach any arbitrary descriptive text to a node in the parse tree with
 the &quot;docstring&quot; feature. When the proxy module is generated then any
 docstring associated with classes, function or methods are output. If
 an item already has an autodoc string then it is combined with the
 docstring and they are output together. If the docstring is all on a
 single line then it is output like this::</p>
<div class="targetlang">
<pre>
&quot;&quot;&quot;This is the docstring&quot;&quot;&quot;
</pre>
</div>
<p> Otherwise, to aid readability it is output like this:</p>
<div class="targetlang">
<pre>
&quot;&quot;&quot;
This is a multi-line docstring
with more than one line.
&quot;&quot;&quot;
</pre>
</div>
<h2><a name="Python_nn72">32.11 Python Packages</a></h2>
<p>Python has concepts of modules and packages. Modules are separate
 units of code and may be grouped together to form a package. Packages
 may be nested, that is they may contain subpackages. This leads to
 tree-like hierarchy, with packages as intermediate nodes and modules as
 leaf nodes.</p>
<p>The hierarchy of Python packages/modules follows the hierarchy of <tt>
*.py</tt> files found in a source tree (or, more generally, in the
 Python path). Normally, the developer creates new module by placing a <tt>
*.py</tt> file somewhere under Python path; the module is then named
 after that <tt>*.py</tt> file. A package is created by placing an <tt>
__init__.py</tt> file within a directory; the package is then named
 after that directory. For example, the following source tree:</p>
<div class="diagram">
<pre>
mod1.py
pkg1/__init__.py
pkg1/mod2.py
pkg1/pkg2/__init__.py
pkg1/pkg2/mod3.py
</pre>
</div>
<p> defines the following Python packages and modules:</p>
<div class="diagram">
<pre>
pkg1            # package
pkg1.pkg2       # package
mod1            # module
pkg1.mod2       # module
pkg1.pkg2.mod3  # module
</pre>
</div>
<p> The purpose of an <tt>__init__.py</tt> file is two-fold. First, the
 existence of <tt>__init__.py</tt> in a directory informs the Python
 interpreter that this directory contains a Python package. Second, the
 code in <tt>__init__.py</tt> is loaded/executed automatically when the
 package is initialized (when it or its submodule/subpackage gets <tt>
import</tt>'ed). By default, SWIG generates proxy Python code &ndash; one <tt>
*.py</tt> file for each <tt>*.i</tt> interface. The <tt>__init__.py</tt>
 files, however, are not generated by SWIG. They should be created by
 other means. Both files (module <tt>*.py</tt> and <tt>__init__.py</tt>)
 should be installed in appropriate destination directories in order to
 obtain a desirable package/module hierarchy.</p>
<p> Python3 adds another option for packages with <a href="https://www.python.org/dev/peps/pep-0420/">
PEP 0420</a> (implicit namespace packages). Implicit namespace packages
 no longer use __init__.py files. SWIG generated Python modules support
 implicit namespace packages. See <a href="#Python_implicit_namespace_packages">
Implicit namespace packages</a> for more information.</p>
<p> You can place a SWIG generated module into a Python package or keep
 as a global module, details are covered a little later in <a href="#Python_package_search">
Location of modules</a>.</p>
<p>The way Python defines its modules and packages impacts SWIG users.
 Some users may need to use special features such as the <tt>package</tt>
 option in the <tt>%module</tt> directive or import related command line
 options. These are explained in the following sections.</p>
<h3><a name="Python_modulepackage">32.11.1 Setting the Python package</a>
</h3>
<p> Using the <tt>package</tt> option in the <tt>%module</tt> directive
 allows you to specify a Python package that the module will be in when
 installed.</p>
<div class="code">
<pre>
%module(package=&quot;wx&quot;) xrc
</pre>
</div>
<p> This is useful when the <tt>.i</tt> file is <tt>%import</tt>ed by
 another <tt>.i</tt> file. By default SWIG will assume that the importer
 is able to find the importee with just the module name, but if they
 live in separate Python packages then this won't work. However if the
 importee specifies what its package is with the <tt>%module</tt> option
 then the Python code generated for the importer will use that package
 name when importing the other module and in base class declarations,
 etc..</p>
<p>SWIG assumes that the <tt>package</tt> option provided to <tt>%module</tt>
 together with the <tt>module</tt> name (that is, <tt>wx.xrc</tt> in the
 above example) forms a fully qualified (absolute) name of a module (in
 Python terms). This is important especially for Python 3, where
 absolute imports are used by default. It's up to you to place the
 generated module files (<tt>.py</tt>, <tt>.so</tt>) in appropriate
 subdirectories. For example, if you have an interface file <tt>foo.i</tt>
 with:</p>
<div class="code">
<pre>
%module(package=&quot;pkg1.pkg2&quot;) foo
</pre>
</div>
<p> then the resulting directory layout should be</p>
<div class="diagram">
<pre>
pkg1/
pkg1/__init__.py
pkg1/pkg2/__init__.py
pkg1/pkg2/foo.py        # (generated by SWIG)
pkg1/pkg2/_foo.so       # (shared library built from C/C++ code generated by SWIG)
</pre>
</div>
<h3><a name="Python_absrelimports">32.11.2 Absolute and relative imports</a>
</h3>
<p>Suppose, we have the following hierarchy of files:</p>
<div class="diagram">
<pre>
pkg1/
pkg1/__init__.py
pkg1/mod2.py
pkg1/pkg2/__init__.py
pkg1/pkg2/mod3.py
</pre>
</div>
<p>Let the contents of <tt>pkg1/pkg2/mod3.py</tt> be</p>
<div class="targetlang">
<pre>
class M3: pass
</pre>
</div>
<p> We edit <tt>pkg1/mod2.py</tt> and want to import module <tt>
pkg1/pkg2/mod3.py</tt> in order to derive from class <tt>M3</tt>. We can
 write appropriate Python code in several ways, for example:</p>
<ol>
<li>
<p>Using &quot;<tt>import &lt;&gt;</tt>&quot; syntax with absolute package name:</p>
<div class="targetlang">
<pre>
# pkg1/mod2.py
import pkg1.pkg2.mod3
class M2(pkg1.pkg2.mod3.M3): pass
</pre>
</div></li>
<li>
<p>Using &quot;<tt>import &lt;&gt;</tt>&quot; syntax with package name relative to <tt>
pkg1</tt> (only in Python 2.7 and earlier):</p>
<div class="targetlang">
<pre>
# pkg1/mod2.py
import pkg2.mod3
class M2(pkg2.mod3.M3): pass
</pre>
</div></li>
<li>
<p>Using &quot;<tt>from &lt;&gt; import &lt;&gt;</tt>&quot; syntax (relative import syntax,
 only in Python 2.5 and later):</p>
<div class="targetlang">
<pre>
# pkg1/mod2.py
from .pkg2 import mod3
class M2(mod3.M3): pass
</pre>
</div></li>
<li>
<p>Other variants, for example the following construction in order to
 have the <tt>pkg2.mod3.M3</tt> symbol available in <tt>mod2</tt> as in
 point 2 above (but now under Python 3):</p>
<div class="targetlang">
<pre>
# pkg1/mod2.py
from . import pkg2
from .pkg2 import mod3
class M2(pkg2.mod3.M3): pass
</pre>
</div></li>
</ol>
<p>Now suppose we have <tt>mod2.i</tt> with</p>
<div class="code">
<pre>
// mod2.i
%module (package=&quot;pkg1&quot;) mod2
%import &quot;mod3.i&quot;
// ...
</pre>
</div>
<p>and <tt>mod3.i</tt> with</p>
<div class="code">
<pre>
// mod3.i
%module (package=&quot;pkg1.pkg2&quot;) mod3
// ...
</pre>
</div>
<p>By default, SWIG will generate <tt>mod2.py</tt> proxy file with <tt>
import</tt> directive as in point 1. This can be changed with the <tt>
-relativeimport</tt> command line option. The <tt>-relativeimport</tt>
 instructs SWIG to organize imports as in point 4 for Python 2.7.0 and
 newer.</p>
<p><b> Compatibility Note:</b> Versions of SWIG prior to SWIG-4.0.0
 supported Python &lt; 2.7.0 and would organize the imports as in point 2
 if an older version of Python was detected at runtime.</p>
<p> In short, if you have <tt>mod2.i</tt> and <tt>mod3.i</tt> as above,
 then without <tt>-relativeimport</tt> SWIG will write</p>
<div class="targetlang">
<pre>
import pkg1.pkg2.mod3
</pre>
</div>
<p>to <tt>mod2.py</tt> proxy file, and with <tt>-relativeimport</tt> it
 will write</p>
<div class="targetlang">
<pre>
from . import pkg2
from .pkg2 import mod3
</pre>
</div>
<p>You should avoid using relative imports and use absolute ones
 whenever possible. There are some cases, however, when relative imports
 may be necessary. The first example is, when some (legacy) Python code
 refers entities imported by proxy files generated by SWIG, and it
 assumes that the proxy file uses relative imports. Second case is, when
 one puts import directives in <tt>__init__.py</tt> to import symbols
 from submodules or subpackages and the submodule depends on other
 submodules (discussed later).</p>
<h3><a name="Python_absimport">32.11.3 Enforcing absolute import
 semantics</a></h3>
<p>As you may know, there is an incompatibility in import semantics (for
 the <tt>import &lt;&gt;</tt> syntax) between Python 2 and 3. In Python 2.4
 and earlier it is not clear whether</p>
<div class="targetlang">
<pre>
import foo
</pre>
</div>
<p>refers to a top-level module or to another module inside the current
 package. In Python 3 it always refers to a top-level module (see <a href="https://www.python.org/dev/peps/pep-0328/">
PEP 328</a>). To instruct Python 2.5 through 2.7 to use new semantics
 (that is <tt>import foo</tt> is interpreted as absolute import), one
 has to put the following line</p>
<div class="targetlang">
<pre>
from __future__ import absolute_import
</pre>
</div>
<p>at the very beginning of your proxy <tt>*.py</tt> file. In SWIG, it
 may be accomplished with <tt>%pythonbegin</tt> directive as follows:</p>
<div class="code">
<pre>
%pythonbegin %{
from __future__ import absolute_import
%}
</pre>
</div>
<h3><a name="Python_importfrominit">32.11.4 Importing from __init__.py</a>
</h3>
<p>Imports in <tt>__init__.py</tt> are handy when you want to populate a
 package's namespace with names imported from other modules. In SWIG
 based projects this approach may also be used to split large pieces of
 code into smaller modules, compile them in parallel and then
 re-assemble everything at runtime by importing submodules' contents in <tt>
__init__.py</tt>, for example.</p>
<p>Unfortunately import directives in <tt>__init__.py</tt> may cause
 problems, especially if they refer to a package's submodules. This is
 caused by the way Python initializes packages. If you spot problems
 with imports from <tt>__init__.py</tt> try using <tt>-relativeimport</tt>
 option. Below we explain in detail one issue, for which the <tt>
-relativeimport</tt> workaround may be helpful.</p>
<p>Consider the following example (Python 3):</p>
<div class="diagram">
<pre>
pkg1/__init__.py        # (empty)
pkg1/pkg2/__init__.py   # (imports something from bar.py)
pkg1/pkg2/foo.py
pkg1/pkg2/bar.py        # (imports foo.py)
</pre>
</div>
<p>If the file contents are:</p>
<ul>
<li>
<p><tt>pkg1/pkg2/__init__.py:</tt></p>
<div class="targetlang">
<pre>
# pkg1/pkg2/__init__.py
from .bar import Bar
</pre>
</div></li>
<li>
<p><tt>pkg1/pkg2/foo.py:</tt></p>
<div class="targetlang">
<pre>
# pkg1/pkg2/foo.py
class Foo: pass
</pre>
</div></li>
<li>
<p><tt>pkg1/pkg2/bar.py:</tt></p>
<div class="targetlang">
<pre>
# pkg1/pkg2/bar.py
import pkg1.pkg2.foo
class Bar(pkg1.pkg2.foo.Foo): pass
</pre>
</div></li>
</ul>
<p>Now if one simply used <tt>import pkg1.pkg2</tt>, it will usually
 fail:</p>
<div class="diagram">
<pre>
&gt;&gt;&gt; import pkg1.pkg2
Traceback (most recent call last):
  File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt;
  File &quot;./pkg1/pkg2/__init__.py&quot;, line 2, in &lt;module&gt;
    from .bar import Bar
  File &quot;./pkg1/pkg2/bar.py&quot;, line 3, in &lt;module&gt;
    class Bar(pkg1.pkg2.foo.Foo): pass
AttributeError: 'module' object has no attribute 'pkg2'
</pre>
</div>
<p>Surprisingly, if we execute the <tt>import pkg1.pkg2</tt> directive
 for the second time, it succeeds. The reason seems to be following:
 when Python spots the <tt>from .bar import Bar</tt> directive in <tt>
pkg1/pkg2/__init__.py</tt> it starts loading <tt>pkg1/pkg2/bar.py</tt>.
 This module imports <tt>pkg1.pkg2.foo</tt> in turn and tries to use <tt>
pkg1.pkg2.foo.Foo</tt>, but the package <tt>pkg1</tt> is not fully
 initialized yet (the initialization procedure is actually in progress)
 and it seems like the effect of the already seen <tt>import
 pkg1.pkg2.pkg3.foo</tt> is &quot;delayed&quot; or ignored. Exactly the same may
 happen to a proxy module generated by SWIG.</p>
<p>One workaround for this case is to use a relative import in <tt>
pkg1/pkg2/bar.py</tt>. If we change <tt>bar.py</tt> to be:</p>
<div class="targetlang">
<pre>
from .pkg3 import foo
class Bar(foo.Foo): pass
</pre>
</div>
<p>or</p>
<div class="targetlang">
<pre>
from . import pkg3
from .pkg3 import foo
class Bar(pkg3.foo.Foo): pass
</pre>
</div>
<p>then the example works again. With SWIG, you need to enable the <tt>
-relativeimport</tt> option in order to have the above workaround in
 effect (note, that the Python 2 case also needs the <tt>-relativeimport</tt>
 workaround).</p>
<h3><a name="Python_implicit_namespace_packages">32.11.5 Implicit
 namespace packages</a></h3>
<p> Python 3.3 introduced <a href="https://www.python.org/dev/peps/pep-0420/">
PEP 0420</a> which implements implicit namespace packages. In a
 nutshell, implicit namespace packages remove the requirement of an
 __init__.py file and allow packages to be split across multiple PATH
 elements. For example:</p>
<div class="diagram">
<pre>
/fragment1/pkg1/mod1.py
/fragment2/pkg1/mod2.py
/fragment3/pkg1/mod3.py
</pre>
</div>
<p>If PYTHONPATH is set to &quot;/fragment1:/fragment2:/fragment3&quot;, then
 mod1, mod2 and mod3 will be part of pkg1. This allows for splitting of
 packages into separate pieces. This can be useful for SWIG generated
 wrappers in the following way.</p>
<p> Suppose you create a SWIG wrapper for a module called robin. The
 SWIG generated code consists of two files robin.py and _robin.so. You
 wish to make these modules part of a subpackage (brave.sir). With
 implicit namespace packages you can place these files in the following
 configurations:</p>
<p>Using PYTHONPATH=&quot;/some/path&quot;</p>
<div class="diagram">
<pre>
/some/path/brave/sir/robin.py
/some/path/brave/sir/_robin.so
</pre>
</div>
<p>Using PYTHONPATH=&quot;/some/path:/some/other/path&quot;<div class="diagram">
<pre>
/some/path/brave/sir/robin.py
/some/other/path/brave/sir/_robin.so
</pre>
</div></p>
<p> Finally suppose that your pure Python code is stored in a .zip file
 or some other way (database, web service connection, etc). Python can
 load the robin.py module using a custom importer. But the _robin.so
 module will need to be located on a file system. Implicit namespace
 packages make this possible. For example, using
 PYTHONPATH=&quot;/some/path/foo.zip:/some/other/path&quot;</p>
<p> Contents of foo.zip</p>
<div class="diagram">
<pre>
brave/
brave/sir/
brave/sir/robin.py
</pre>
</div>
<p> File system contents</p>
<div class="diagram">
<pre>
/some/other/path/brave/sir/_robin.so
</pre>
</div>
<p>Support for implicit namespace packages was added to python-3.3. The
 zipimporter requires python-3.5.1 or newer to work with subpackages.</p>
<p><b> Compatibility Note:</b> Support for implicit namespace packages
 was added in SWIG-3.0.9.</p>
<h3><a name="Python_package_search">32.11.6 Location of modules</a></h3>
<p> When SWIG creates wrappers from an interface file, say foo.i, two
 Python modules are created. There is a pure Python module (foo.py) and
 C/C++ code which is compiled and linked into a dynamically (or
 statically) loaded low-level module _foo (see the <a href="#Python_nn3">
Preliminaries section</a> for details). So, the interface file really
 defines two Python modules. How these two modules are loaded is covered
 next.</p>
<p> The pure Python module needs to load the C/C++ module in order to
 call the wrapped C/C++ methods. To do this it must make some
 assumptions about the location of the C/C++ module. There are two
 configurations that are supported by default.</p>
<ol>
<li>
<p>Both modules in the same package</p>
</li>
<li>
<p>Both modules are global</p>
</li>
</ol>
<p> Additional configurations are supported but require custom import
 code.</p>
<p> The following sub-sections look more closely at the two default
 configurations as well as some customized configurations. An input
 interface file, foo.i, results in the two modules foo.py and _foo.so
 for each of the configurations.</p>
<h4><a name="Python_package_search_both_package_modules">32.11.6.1 Both
 modules in the same package</a></h4>
<p> In this configuration, the pure Python module, foo.py, tries to load
 the C/C++ module, _foo, from the same package foo.py is located in. The
 package name is determined from the <tt>__package__</tt> attribute if
 available, see <a href="https://www.python.org/dev/peps/pep-0366/">PEP
 366</a>. Otherwise it is derived from the <tt>__name__</tt> attribute
 given to foo.py by the Python loader that imported foo.py. The
 interface file for this configuration would contain:</p>
<div class="code">
<pre>
%module(package=&quot;mypackage&quot;) foo
</pre>
</div>
<p>The location of the files could be as follows:</p>
<div class="diagram">
<pre>
/dir/mypackage/foo.py
/dir/mypackage/__init__.py
/dir/mypackage/_foo.so
</pre>
</div>
<p>Assuming /dir/ is in PYTHONPATH, the module can be imported using</p>
<div class="targetlang">
<pre>
from mypackage import foo
</pre>
</div>
<h4><a name="Python_package_search_both_global_modules">32.11.6.2 Both
 modules are global</a></h4>
<p> In this configuration, there are no packages. If foo.py is not in a
 package, that is, it is a global module, then _foo is loaded as a
 global module. The interface file for this configuration would contain:</p>
<div class="code">
<pre>
%module foo
</pre>
</div>
<p>The location of the files could be as follows:</p>
<div class="diagram">
<pre>
/dir/foo.py
/dir/_foo.so
</pre>
</div>
<p>Assuming /dir/ is in PYTHONPATH, the module can be imported using</p>
<div class="targetlang">
<pre>
import foo
</pre>
</div>
<h4><a name="Python_package_search_wrapper_split">32.11.6.3 Split
 modules custom configuration</a></h4>
<p>In this non-standard 'split module' configuration, the pure Python
 module is in a package and the low level C/C++ module is global. This
 configuration is not generally recommended and is not supported by
 default as it needs a custom configuration. The module import code
 customization required is via the <tt>moduleimport</tt> attribute in
 the <tt>%module</tt> directive. The next sub-section elaborates further
 on this. The interface file for this split module configuration would
 contain:</p>
<div class="code">
<pre>
%module(package=&quot;mypackage&quot;, moduleimport=&quot;import _foo&quot;) foo
</pre>
</div>
<p> When using <tt>-builtin</tt>, use the following instead (the reasons
 are also covered shortly in the next sub-section):</p>
<div class="code">
<pre>
%module(package=&quot;mypackage&quot;, moduleimport=&quot;from _foo import *&quot;) foo
</pre>
</div>
<p>The location of the files could be as follows:</p>
<div class="diagram">
<pre>
/dir/mypackage/foo.py
/dir/mypackage/__init__.py
/dir/_foo.so
</pre>
</div>
<p>Assuming /dir/ is in PYTHONPATH, the module can be imported using</p>
<div class="targetlang">
<pre>
from mypackage import foo
</pre>
</div>
<p><b> Compatibility Note:</b> Versions of SWIG prior to SWIG-4.0.0
 supported split modules without the above customization. However, this
 had to be removed as the default import code often led to confusion due
 to obfuscation of genuine Python <tt>ImportError</tt> problems. Using
 one of the two default configurations is the recommended approach now.</p>
<h4><a name="Python_custom_module_import">32.11.6.4 More on customizing
 the module import code</a></h4>
<p> The Python code implementing the default import logic is shown
 below. It supports the two configurations described earlier, that is,
 either both modules are in a package or loading both as global modules.
 The code is generated into the pure Python module, foo.py, and merely
 imports the low-level _foo module.</p>
<div class="targetlang">
<pre>
if __package__ or '.' in __name__:
    from . import _foo
else:
    import _foo
</pre>
</div>
<p> This import code implementation is non-trivial but it can be
 replaced with custom code providing opportunities to make it simpler
 and/or more flexible. This is not normally recommended though unless
 you have a good understanding of the intricacies of importing Python
 modules. The custom code can be specified by setting the <tt>
moduleimport</tt> option of the <tt>%module</tt> directive with the
 appropriate import code. For example:</p>
<div class="code">
<pre>
%module(moduleimport=&quot;import _foo&quot;) foo
</pre>
</div>
<p> This will replace the default import logic above and generate the
 following into the pure Python module, foo.py:</p>
<div class="targetlang">
<pre>
import _foo
</pre>
</div>
<p> In fact the above is a simplification customization for the
 configuration where both modules are global; it removes the logic for
 also handling the modules being in a package.</p>
<p> There is a special variable, <tt>$module</tt>, which is expanded
 into the low-level C/C++ module name, <tt>_foo</tt> in the case above.
 The identical output would be generated if instead the following had
 been used:</p>
<div class="code">
<pre>
%module(moduleimport=&quot;import $module&quot;) foo
</pre>
</div>
<p> When you have many lines you can retain the easy readability of the <tt>
%module</tt> directive by using a macro. For example:</p>
<div class="code">
<pre>
%define MODULEIMPORT
&quot;
print 'Loading low-level module $module'
import $module
print 'Module has loaded'
&quot;
%enddef

%module(moduleimport=MODULEIMPORT) foo
</pre>
</div>
<p> This will of course generate the following into the pure Python
 module:</p>
<div class="targetlang">
<pre>
print 'Loading low-level module $module'
import _foo
print 'Module has loaded'
</pre>
</div>
<p> When using the <tt>-builtin</tt> option, the link between the pure
 Python module and the low-level C/C++ module is slightly different as
 all the objects from the low-level module are imported directly into
 the pure Python module. The default import loading code is thus
 different:</p>
<div class="targetlang">
<pre>
if __package__ or '.' in __name__:
    from ._foo import *
else:
    from _foo import *
</pre>
</div>
<p> Any customizations must import the code in a similar manner. The
 best way to support both with and without <tt>-builtin</tt> is to make
 use of the <tt>SWIGPYTHON_BUILTIN</tt> macro which is defined when <tt>
-builtin</tt> is specified. The following will do this for the <a href="#Python_package_search_wrapper_split">
split modules</a> case above.</p>
<div class="code">
<pre>
#if defined(SWIGPYTHON_BUILTIN) /* defined when using -builtin */
%module(package=&quot;mypackage&quot;, moduleimport=&quot;from $module import *&quot;) foo
#else
%module(package=&quot;mypackage&quot;, moduleimport=&quot;import $module&quot;) foo
#endif
</pre>
</div>
<h4><a name="Python_package_search_static">32.11.6.5 Statically linked C
 modules</a></h4>
<p>It is strongly recommended to use dynamically linked modules for the
 C portion of your pair of Python modules. If for some reason you still
 need to link the C module of the pair of Python modules generated by
 SWIG into your interpreter, then this section provides some details on
 how this impacts the pure Python modules ability to locate the other
 part of the pair. Please also see the <a href="#Python_nn8">Static
 Linking</a> section.</p>
<p>When Python is extended with C code the Python interpreter needs to
 be informed about details of the new C functions that have been linked
 into the executable. The code to do this is created by SWIG and is
 automatically called in the correct way when the module is dynamically
 loaded. However when the code is not dynamically loaded (because it is
 statically linked) Then the initialization method for the module
 created by SWIG is not called automatically and the Python interpreter
 has no idea that the new SWIG C module exists.</p>
<p>Before Python 3, one could simply call the init method created by
 SWIG which would have normally been called when the shared object was
 dynamically loaded. The specific name of this method is not given here
 because statically linked modules are not encouraged with SWIG (<a href="#Python_nn8">
Static Linking</a>). However one can find this init function in the C
 file generated by SWIG.</p>
<p>If you are really keen on static linking there are two ways to
 initialize the SWIG generated C module with the init method. Which way
 you use depends on what version of Python your module is being linked
 with. Python 2 and Python 3 treat this init function differently. And
 the way they treat it affects how the pure Python module will be able
 to locate the C module.</p>
<p>The details concerning this are covered completely in the
 documentation for Python itself. Links to the relevant sections follow:</p>
<ul>
<li><a href="https://docs.python.org/2/extending/extending.html#methodtable">
Extending in python2</a></li>
<li><a href="https://docs.python.org/3.6/extending/extending.html#the-module-s-method-table-and-initialization-function">
Extending in python3</a></li>
</ul>
<p>There are two keys things to understand. The first is that in Python
 2 the init() function returns void. In Python 3 the init() function
 returns a <tt>PyObject *</tt> which points to the new module. Secondly,
 when you call the init() method manually, you are the Python importer.
 So, you determine which package the C module will be located in.</p>
<p>So, if you are using Python 3 it is important that you follow what is
 described in the Python documentation linked above. In particular, you
 can't simply call the init() function generated by SWIG and cast the <tt>
PyObject</tt> pointer it returns over the side. If you do then Python 3
 will have no idea that your C module exists and the pure Python half of
 your wrapper will not be able to find it. You need to register your
 module with the Python interpreter as described in the Python docs.</p>
<p>With Python 2 things are somewhat more simple. In this case the
 init() function returns void. Calling it will register your new C
 module as a<b> global</b> module. The pure Python part of the SWIG
 wrapper will be able to find it because it tries both the pure Python
 module it is part of and the global module. If you wish not to have the
 statically linked module be a global module then you will either need
 to refer to the Python documentation on how to do this (remember you
 are now the Python importer) or use dynamic linking.</p>
<h2><a name="Python_python3support">32.12 Python 3 Support</a></h2>
<p> SWIG is able to support Python 3.x. The wrapper code generated by
 SWIG can be compiled with both Python 2.x or 3.x. Further more, by
 passing the <tt>-py3</tt> command line option to SWIG, wrapper code
 with some Python 3 specific features can be generated (see below
 subsections for details of these features).</p>
<p> There is a list of known-to-be-broken features in Python 3:</p>
<ul>
<li>No more support for FILE* typemaps, because PyFile_AsFile has been
 dropped in Python 3.</li>
<li>The <tt>-apply</tt> command line option is removed and generating
 code using apply() is no longer supported.</li>
</ul>
<p> The following are Python 3 new features that are currently supported
 by SWIG.</p>
<h3><a name="Python_nn74">32.12.1 Function annotation</a></h3>
<p> The <tt>-py3</tt> option will enable function annotation support.
 When used SWIG is able to generate proxy method definitions like this:</p>
<div class="code">
<pre>
  def foo(self, bar : &quot;int&quot;=0) -&gt; &quot;void&quot; : ...
</pre>
</div>
<p> Also, even if without passing SWIG the <tt>-py3</tt> option, the
 parameter list still could be generated:</p>
<div class="code">
<pre>
  def foo(self, bar=0): ...
</pre>
</div>
<p> But for overloaded function or method, the parameter list would
 fallback to <tt>*args</tt> or <tt>self, *args</tt>, and <tt>**kwargs</tt>
 may be append depend on whether you enabled the keyword argument. This
 fallback is due to all overloaded functions share the same function in
 SWIG generated proxy class.</p>
<p> For detailed usage of function annotation, see <a href="https://www.python.org/dev/peps/pep-3107/">
PEP 3107</a>.</p>
<h3><a name="Python_nn75">32.12.2 Buffer interface</a></h3>
<p> SWIG has a series of typemaps to support buffer interfaces. These
 typemap macros are defined in <tt>pybuffer.i</tt>, which must be
 included in order to use them. By using these typemaps, your wrapped
 function will be able to accept any Python object that exposes a
 suitable buffer interface.</p>
<p> For example, the <tt>get_path()</tt> function puts the path string
 into the memory pointed to by its argument:</p>
<div class="code">
<pre>
void get_path(char *s);
</pre>
</div>
<p> Then you can write a typemap like this: (the following example is
 applied to both Python 2 and 3, since the <tt>bytearray</tt> type was
 backported to 2.6.</p>
<div class="code">
<pre>
%include &lt;pybuffer.i&gt;
%pybuffer_mutable_string(char *str);
void get_path(char *str);
</pre>
</div>
<p> And then on the Python side the wrapped <tt>get_path</tt> could be
 used in this way:</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; p = bytearray(10)
&gt;&gt;&gt; get_path(p)
&gt;&gt;&gt; print(p)
bytearray(b'/Foo/Bar/\x00')
</pre>
</div>
<p> The macros defined in <tt>pybuffer.i</tt> are similar to those in <tt>
cstring.i</tt>:</p>
<p><b> %pybuffer_mutable_binary(parm, size_parm)</b></p>
<div class="indent">
<p> The macro can be used to generate a typemap which maps a buffer of
 an object to a pointer provided by <tt>parm</tt> and a size argument
 provided by <tt>size_parm</tt>. For example:</p>
<div class="code">
<pre>
%pybuffer_mutable_binary(char *str, size_t size);
...
int snprintf(char *str, size_t size, const char *format, ...);
</pre>
</div>
<p> In Python:</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; buf = bytearray(6)
&gt;&gt;&gt; snprintf(buf, &quot;Hello world!&quot;)
&gt;&gt;&gt; print(buf)
bytearray(b'Hello\x00')
&gt;&gt;&gt;
</pre>
</div></div>
<p><b> %pybuffer_mutable_string(parm)</b></p>
<div class="indent">
<p> This typemap macro requires the buffer to be a zero terminated
 string, and maps the pointer of the buffer to <tt>parm</tt>. For
 example:</p>
<div class="code">
<pre>
%pybuffer_mutable_string(char *str);
...
size_t make_upper(char *str);
</pre>
</div>
<p> In Python:</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; buf = bytearray(b'foo\x00')
&gt;&gt;&gt; make_upper(buf)
&gt;&gt;&gt; print(buf)
bytearray(b'FOO\x00')
&gt;&gt;&gt;
</pre>
</div>
<p> Both <tt>%pybuffer_mutable_binary</tt> and <tt>
%pybuffer_mutable_string</tt> require the provided buffer to be mutable,
 eg. they can accept a <tt>bytearray</tt> type but can't accept an
 immutable <tt>byte</tt> type.</p>
</div>
<p><b> %pybuffer_binary(parm, size_parm)</b></p>
<div class="indent">
<p> This macro maps an object's buffer to a pointer <tt>parm</tt> and a
 size <tt>size_parm</tt>. It is similar to <tt>%pybuffer_mutable_binary</tt>
, except the <tt>%pybuffer_binary</tt> can accept both mutable and
 immutable buffers. As a result, the wrapped function should not modify
 the buffer.</p>
</div>
<p><b> %pybuffer_string(parm)</b></p>
<div class="indent">
<p> This macro maps an object's buffer as a string pointer <tt>parm</tt>
. It is similar to <tt>%pybuffer_mutable_string</tt> but the buffer
 could be both mutable and immutable. And your function should not
 modify the buffer.</p>
</div>
<h3><a name="Python_nn76">32.12.3 Abstract base classes</a></h3>
<p> By including <tt>pyabc.i</tt> and using the <tt>-py3</tt> command
 line option when calling SWIG, the proxy classes of the STL containers
 will automatically gain an appropriate abstract base class from the <tt>
collections.abc</tt> module. For example, the following SWIG interface:</p>
<div class="code">
<pre>
%include &lt;pyabc.i&gt;
%include &lt;std_map.i&gt;
%include &lt;std_list.i&gt;

namespace std {
  %template(Mapii) map&lt;int, int&gt;;
  %template(IntList) list&lt;int&gt;;
}
</pre>
</div>
<p> will generate a Python proxy class <tt>Mapii</tt> inheriting from <tt>
collections.abc.MutableMap</tt> and a proxy class <tt>IntList</tt>
 inheriting from <tt>collections.abc.MutableSequence</tt>.</p>
<p> <tt>pyabc.i</tt> also provides a macro <tt>%pythonabc</tt> that
 could be used to define an abstract base class for your own C++ class:</p>
<div class="code">
<pre>
%pythonabc(MySet, collections.abc.MutableSet);
</pre>
</div>
<p> For details of abstract base class, please see <a href="https://www.python.org/dev/peps/pep-3119/">
PEP 3119</a>.</p>
<p><b> Compatibility Note:</b> SWIG-4.0.0 changed the base classes to
 use the <tt>collections.abc</tt> module instead of <tt>collections</tt>
 due to the deprecation of the classes in the <tt>collections</tt>
 module in Python 3.7. The <tt>collections.abc</tt> module was
 introduced in Python 3.3 and hence this feature requires Python 3.3 or
 later.</p>
<h3><a name="Python_nn77">32.12.4 Byte string output conversion</a></h3>
<p> By default, any byte string (<tt>char*</tt> or <tt>std::string</tt>)
 returned from C or C++ code is decoded to text as UTF-8. This decoding
 uses the <tt>surrogateescape</tt> error handler under Python 3.1 or
 higher -- this error handler decodes invalid byte sequences to high
 surrogate characters in the range U+DC80 to U+DCFF. As an example,
 consider the following SWIG interface, which exposes a byte string that
 cannot be completely decoded as UTF-8:</p>
<div class="code">
<pre>
%module example

%inline %{

const char * non_utf8_c_str(void) {
  return &quot;h\xe9llo w\xc3\xb6rld&quot;;
}

void instring(const char *s) {
  ...
}

%}
</pre>
</div>
<p> Note that &quot;\xe9&quot; is an invalid UTF-8 encoding, but &quot;\xc3\xb6&quot; is
 valid. When this method is called from Python 3, the return value is
 the following text string:</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; s = example.non_utf8_c_str()
&gt;&gt;&gt; s
'h\udce9llo w&ouml;rld'
</pre>
</div>
<p> Since the C string contains bytes that cannot be decoded as UTF-8,
 those raw bytes are represented as high surrogate characters that can
 be used to obtain the original byte sequence:</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; b = s.encode('utf-8', errors='surrogateescape')
&gt;&gt;&gt; b
b'h\xe9llo w\xc3\xb6rld'
</pre>
</div>
<p> One can then attempt a different encoding, if desired (or simply
 leave the byte string as a raw sequence of bytes for use in binary
 protocols):</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; b.decode('latin-1')
'h&eacute;llo w&Atilde;&para;rld'
</pre>
</div>
<p> Note, however, that text strings containing surrogate characters are
 rejected with the default <tt>strict</tt> codec error handler. For
 example:</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; with open('test', 'w') as f:
...     print(s, file=f)
...
Traceback (most recent call last):
  File &quot;&lt;stdin&gt;&quot;, line 2, in &lt;module&gt;
UnicodeEncodeError: 'utf-8' codec can't encode character '\udce9' in position 1: surrogates not allowed
</pre>
</div>
<p> This requires the user to check most strings returned by SWIG
 bindings, but the alternative is for a non-UTF8 byte string to be
 completely inaccessible in Python 3 code.</p>
<p> For more details about the <tt>surrogateescape</tt> error handler,
 please see <a href="https://www.python.org/dev/peps/pep-0383/">PEP 383</a>
.</p>
<p> When Python 3 strings are passed to the C/C++ layer, they are
 expected to be valid UTF8 Unicode strings too. For example, when the <tt>
instring</tt> method above is wrapped and called, any invalid UTF8
 Unicode code strings will result in a TypeError because the attempted
 conversion fails:</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; example.instring('h\xe9llo')
&gt;&gt;&gt; example.instring('h\udce9llo')
Traceback (most recent call last):
  File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt;
TypeError: in method 'instring', argument 1 of type 'char const *'
</pre>
</div>
<p> In some cases, users may wish to instead handle all byte strings as
 bytes objects in Python 3. This can be accomplished by adding <tt>
SWIG_PYTHON_STRICT_BYTE_CHAR</tt> to the generated code:</p>
<div class="code">
<pre>
%module char_to_bytes
%begin %{
#define SWIG_PYTHON_STRICT_BYTE_CHAR
%}

char *charstring(char *s) {
  return s;
}
</pre>
</div>
<p> This will modify the behavior so that only Python 3 bytes objects
 will be accepted and converted to a C/C++ string, and any string
 returned from C/C++ will be converted to a bytes object in Python 3:</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; from char_to_bytes import *
&gt;&gt;&gt; charstring(b&quot;hi&quot;) # Byte string
b'hi'
&gt;&gt;&gt; charstring(&quot;hi&quot;)  # Unicode string
Traceback (most recent call last):
  File &quot;&lt;stdin&gt;&quot;, line 1, in ?
TypeError: in method 'charstring', argument 1 of type 'char *'
</pre>
</div>
<p> Note that in Python 2, defining <tt>SWIG_PYTHON_STRICT_BYTE_CHAR</tt>
 has no effect, since strings in Python 2 are equivalent to Python 3
 bytes objects. However, there is a similar capability to force
 unicode-only handling for wide characters C/C++ strings (<tt>wchar_t *</tt>
 or <tt>std::wstring</tt> types) in Python 2. By default, in Python 2
 both strings and unicode strings are converted to C/C++ wide strings,
 and returned wide strings are converted to a Python unicode string. To
 instead only convert unicode strings to wide strings, users can add <tt>
SWIG_PYTHON_STRICT_UNICODE_WCHAR</tt> to the generated code:</p>
<div class="code">
<pre>
%module wchar_to_unicode
%begin %{
#define SWIG_PYTHON_STRICT_UNICODE_WCHAR
%}

wchar_t *wcharstring(wchar_t *s) {
  return s;
}
</pre>
</div>
<p> This ensures that only unicode strings are accepted by wcharstring
 in both Python 2 and Python 3:</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; from wchar_to_unicode import *
&gt;&gt;&gt; wcharstring(u&quot;hi&quot;) # Unicode string
u'hi'
&gt;&gt;&gt; wcharstring(b&quot;hi&quot;) # Byte string
Traceback (most recent call last):
  File &quot;&lt;stdin&gt;&quot;, line 1, in ?
TypeError: in method 'charstring', argument 1 of type 'wchar_t *'
</pre>
</div>
<p> By defining both <tt>SWIG_PYTHON_STRICT_BYTE_CHAR</tt> and <tt>
SWIG_PYTHON_STRICT_UNICODE_WCHAR</tt>, Python wrapper code can support
 overloads taking both std::string (as Python bytes) and std::wstring
 (as Python unicode).</p>
<h3><a name="Python_2_unicode">32.12.5 Python 2 Unicode</a></h3>
<p> A Python 3 string is a Unicode string so by default a Python 3
 string that contains Unicode characters passed to C/C++ will be
 accepted and converted to a C/C++ string (<tt>char *</tt> or <tt>
std::string</tt> types). A Python 2 string is not a unicode string by
 default and should a Unicode string be passed to C/C++ it will fail to
 convert to a C/C++ string (<tt>char *</tt> or <tt>std::string</tt>
 types). The Python 2 behavior can be made more like Python 3 by
 defining <tt>SWIG_PYTHON_2_UNICODE</tt> when compiling the generated
 C/C++ code. By default when the following is wrapped:</p>
<div class="code">
<pre>
%module unicode_strings
char *charstring(char *s) {
  return s;
}
</pre>
</div>
<p> An error will occur when using Unicode strings in Python 2:</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; from unicode_strings import *
&gt;&gt;&gt; charstring(&quot;hi&quot;)
'hi'
&gt;&gt;&gt; charstring(u&quot;hi&quot;)
Traceback (most recent call last):
  File &quot;&lt;stdin&gt;&quot;, line 1, in ?
TypeError: in method 'charstring', argument 1 of type 'char *'
</pre>
</div>
<p> When the <tt>SWIG_PYTHON_2_UNICODE</tt> macro is added to the
 generated code:</p>
<div class="code">
<pre>
%module unicode_strings
%begin %{
#define SWIG_PYTHON_2_UNICODE
%}

char *charstring(char *s) {
  return s;
}
</pre>
</div>
<p> Unicode strings will be successfully accepted and converted from
 UTF-8, but note that they are returned as a normal Python 2 string:</p>
<div class="targetlang">
<pre>
&gt;&gt;&gt; from unicode_strings import *
&gt;&gt;&gt; charstring(&quot;hi&quot;)
'hi'
&gt;&gt;&gt; charstring(u&quot;hi&quot;)
'hi'
&gt;&gt;&gt;
</pre>
</div>
<p> Note that defining both <tt>SWIG_PYTHON_2_UNICODE</tt> and <tt>
SWIG_PYTHON_STRICT_BYTE_CHAR</tt> at the same time is not allowed, since
 the first is allowing unicode conversion and the second is explicitly
 prohibiting it.</p>
<h2><a name="Python_multithreaded">32.13 Support for Multithreaded
 Applications</a></h2>
<p>By default, SWIG does not enable support for multithreaded Python
 applications. More specifically, the Python wrappers generated by SWIG
 will not release the Python's interpreter's Global Interpreter Lock
 (GIL) when wrapped C/C++ code is entered. Hence, while any of the
 wrapped C/C++ code is executing, the Python interpreter will not be
 able to run any other threads, even if the wrapped C/C++ code is
 waiting in a blocking call for something like network or disk IO.
 Fortunately, SWIG does have the ability to enable multithreaded support
 and automatic release of the GIL either for all wrapped code in a
 module or on a more selective basis. The user interface for this is
 described in the next section.</p>
<h3><a name="Python_thread_UI">32.13.1 UI for Enabling Multithreading
 Support</a></h3>
<p>The user interface is as follows:</p>
<ol>
<li>
<p>Module thread support can be enabled in two ways:</p>
<ul>
<li>
<p> The <tt>-threads</tt> SWIG Python option at the command line (or in <tt>
setup.py</tt>):</p>
<div class="shell">
<pre>$ swig -python -threads example.i</pre>
</div></li>
<li>
<p> The <tt>threads</tt> module option in the *.i template file:</p>
<div class="code">
<pre>%module(&quot;threads&quot;=1)</pre>
</div></li>
</ul>
</li>
<li>
<p>You can disable thread support for a given method:</p>
<div class="code">
<pre>%feature(&quot;nothread&quot;) method;</pre>
</div> or<div class="code">
<pre>%nothread method;</pre>
</div></li>
<li>
<p>You can partially disable thread support for a given method:</p>
<ul>
<li>
<p>To disable the C++/Python thread protection:</p>
<div class="code">
<pre>%feature(&quot;nothreadblock&quot;) method;</pre>
</div> or<div class="code">
<pre>%nothreadblock method;</pre>
</div></li>
<li>
<p>To disable the Python/C++ thread protection</p>
<div class="code">
<pre>%feature(&quot;nothreadallow&quot;) method;</pre>
</div> or<div class="code">
<pre>%nothreadallow method;</pre>
</div></li>
</ul>
</li>
</ol>
<h3><a name="Python_thread_performance">32.13.2 Multithread Performance</a>
</h3>
<p> For the curious about performance, here are some numbers for the
 profiletest.i test, which is used to check the speed of the wrapped
 code:</p>
<table summary="Python multithread performance">
<tr><th>Thread Mode</th><th>Execution Time (sec)</th><th>Comment</th></tr>
<tr><td>Single Threaded</td><td>9.6</td><td>no &quot;-threads&quot; option given</td>
</tr>
<tr><td>Fully Multithreaded</td><td>15.5</td><td>&quot;-threads&quot; option =
 'allow' + 'block'</td></tr>
<tr><td>No Thread block</td><td>12.2</td><td>only 'allow'</td></tr>
<tr><td>No Thread Allow</td><td>13.6</td><td>only block'</td></tr>
</table>
<p> Fully threaded code decreases the wrapping performance by around
 60%. If that is important to your application, you can tune each method
 using the different 'nothread', 'nothreadblock' or 'nothreadallow'
 features as needed. Note that for some methods deactivating the 'thread
 block' or 'thread allow' code is not an option, so, be careful.</p>

<!--  LocalWords:  polymorphism Typemaps STL typemap typemaps Docstring autodoc
 -->

<!--  LocalWords:  docstring SWIG's cxx py GCC linux DLL gcc fPIC Wiki Xlinker
 -->

<!--  LocalWords:  examplemodule DHAVE CONFIG lpython lm ldl mypython lsocket
 -->

<!--  LocalWords:  lnsl lpthread distutils enums namespaces
 -->
<HR NOSHADE>
<h1><a name="R">33 SWIG and R</a></h1>

<!-- INDEX -->
<div class="sectiontoc">
<ul>
<li><a href="#R_nn2">Bugs</a></li>
<li><a href="#R_nn3">Using R and SWIG</a></li>
<li><a href="#R_nn4">Precompiling large R files</a></li>
<li><a href="#R_nn5">General policy</a></li>
<li><a href="#R_language_conventions">Language conventions</a></li>
<li><a href="#R_nn6">C++ classes</a>
<ul>
<li><a href="#R_class_examples">Examples</a></li>
</ul>
</li>
<li><a href="#R_nn7">Enumerations</a></li>
</ul>
</div>
<!-- INDEX -->
<p> R is a GPL'ed open source statistical and plotting environment.
 Information about R can be found at <a href="http://www.r-project.org/">
www.r-project.org</a>.</p>
<p> The R bindings are under active development. They have been used to
 compile and run an R interface to QuantLib running on Mandriva Linux
 with gcc. They are also used to create the SimpleITK R package, which
 runs on Linux and MacOS. SWIG is used to create all wrapper interfaces
 to <a href="http://http://www.simpleitk.org/">SimpleITK</a>. The R
 bindings also work on Microsoft Windows using Visual C++.</p>
<h2><a name="R_nn2">33.1 Bugs</a></h2>
<p> Currently the following features are not implemented or broken:</p>
<ul>
<li>Garbage collection of some created objects. Finalizers are available
 for wrapped C++ classes and are called by the garbage collection
 system.</li>
<li>C Array wrappings</li>
</ul>
<h2><a name="R_nn3">33.2 Using R and SWIG</a></h2>
<p> To use R and SWIG in C mode, execute the following commands where
 example.c is the name of the file with the functions in them</p>
<div class="shell">
<pre>
swig -r example.i
R CMD SHLIB example_wrap.c example.c
</pre>
</div>
<p> The corresponding options for C++ mode are</p>
<div class="shell">
<pre>
swig -c++ -r -o example_wrap.cpp example.i
R CMD SHLIB example_wrap.cpp example.cpp
</pre>
</div>
<p> Note that R is sensitive to the names of the files. The name of the
 wrapper file must be the name of the library unless you use the -o
 option to R when building the library, for example:</p>
<div class="shell">
<pre>
swig -c++ -r -o example_wrap.cpp example.i
R CMD SHLIB -o example.so example_wrap.cpp example.cpp
</pre>
</div>
<p> R is also sensitive to the name of the file extension in C and C++
 mode. In C++ mode, the file extension must be .cpp rather than .cxx for
 the R compile command to recognize it. If your C++ code is in a file
 using something other than a .cpp extension, then it may still work
 using PKG_LIBS:</p>
<div class="shell">
<pre>
swig -c++ -r -o example_wrap.cpp example.i
PKG_LIBS=&quot;example.cxx&quot; R CMD SHLIB -o example example_wrap.cpp
</pre>
</div>
<p> The commands produces two files. A dynamic shared object file called
 example.so, or example.dll, and an R wrapper file called example.R. To
 load these files, start up R and type in the following commands</p>
<div class="shell">
<pre>
dyn.load(paste(&quot;example&quot;, .Platform$dynlib.ext, sep=&quot;&quot;))
source(&quot;example.R&quot;)
cacheMetaData(1)
</pre>
</div>
<p> The cacheMetaData(1) will cause R to refresh its object tables.
 Without it, inheritance of wrapped objects may fail. These two files
 can be loaded in any order.</p>
<p> If you are compiling code yourself (not using R itself), there are a
 few things to watch out for:</p>
<ul>
<li>The output shared library name (to the left of the file extension)
 MUST match the module name, or alternatively, you can also set the
 -package NAME command line argument. See swig -r -help for more
 information</li>
<li>If you do not set the output file name appropriately, you might see
 errors like<div class="shell">
<pre>
&gt; fact(4)
Error in .Call(&quot;R_swig_fact&quot;, s_arg1, as.logical(.copy), PACKAGE = &quot;example&quot;) :
  &quot;R_swig_fact&quot; not available for .Call() for package &quot;example&quot;
</pre>
</div></li>
<li>Make sure the architecture of the shared library(x64 for instance),
 matches the architecture of the R program you want to load your shared
 library into</li>
</ul>
<h2><a name="R_nn4">33.3 Precompiling large R files</a></h2>
<p> In cases where the R file is large, one make save a lot of loading
 time by precompiling the R wrapper. This can be done by creating the
 file makeRData.R which contains the following</p>
<div class="code">
<pre>
source('BigFile.R')
save(list=ls(all=TRUE), file=&quot;BigFile.RData&quot;, compress=TRUE)
q(save=&quot;no&quot;)
</pre>
</div>
<p> This will generate a compiled R file called BigFile.RData that will
 save a large amount of loading time.</p>
<p> There is no need to precompile large R files if the SWIG-generated
 code is being included in an R package. The package infrastructure
 provides this service during package installation.</p>
<h2><a name="R_nn5">33.4 General policy</a></h2>
<p> The general policy of the module is to treat the C/C++ as a basic
 wrapping over the underlying functions and rely on the R type system to
 provide R syntax.</p>
<h2><a name="R_language_conventions">33.5 Language conventions</a></h2>
<p> getitem and setitem use C++ conventions (i.e. zero based indices).
 [&lt;- and [ are overloaded to allow for R syntax (one based indices and
 slices)</p>
<h2><a name="R_nn6">33.6 C++ classes</a></h2>
<p> Wrapping of C++ classes for R works quite well. R has a special
 type, known as an external reference, that can be used as a pointer to
 arbitary things, including C++ classes. The proxy layers generated for
 other classes are not required.</p>
<p> SWIG currently creates a custom hierarchy of R classes derived from
 the external reference type and implements type checking and function
 overloading in the R code it generates. In the future we hope to
 utilise the built in R6 class structures.</p>
<p> The R interface has the following capabilities:</p>
<ul>
<li> Destructor methods are registered and called automatically by the R
 garbage collector.</li>
<li> A range of std::vector types are converted automatically to R
 equivalents via the std_vector.i library.</li>
<li> The $ operator is used for method access.</li>
<li> Variable accessors are automatically generated and called via the
 $, [, [[, $&lt;-, [&lt;-, [[&lt;- operators.</li>
</ul>
<h3><a name="R_class_examples">33.6.1 Examples</a></h3>
<p> Consider the following simple example:</p>
<div class="code">
<pre>
class Vehicle {
private:
  int m_axles;

public:
  int Axles() {
    return(m_axles);
  }

  bool Available;

  Vehicle() {
    Available=false;
    m_axles=2;
  }

  Vehicle(int ax) {
    Available=false;
    m_axles=ax;
  }
};
</pre>
</div>
<p> The following options are available in R:</p>
<div class="code">
<pre>
v1 &lt;- Vehicle()
v2 &lt;- Vehicle(4)
# access members
v1$Axles()
[1] 2
v2$Axles
[1] 4
v1$Available
[1] FALSE
# Set availabilty
v1$Available &lt;- TRUE
v1$Available
[1] TRUE
</pre>
</div>
<p> A useful trick to determine the methods that are available is to
 query the R method definition as follows:</p>
<div class="code">
<pre>
# display the methods for the class
getMethod(&quot;$&quot;, class(v1))
    
Method Definition:

function (x, name) 
{
    accessorFuns = list(Axles = Vehicle_Axles, Available = Vehicle_Available_get)
    vaccessors = c(&quot;Available&quot;)
    idx = pmatch(name, names(accessorFuns))
    if (is.na(idx)) 
        return(callNextMethod(x, name))
    f = accessorFuns[[idx]]
    if (is.na(match(name, vaccessors))) 
        function(...) {
            f(x, ...)
        }
    else f(x)
}

Signatures:
        x           
target  &quot;_p_Vehicle&quot;
defined &quot;_p_Vehicle&quot;

</pre>
</div>
<p> The names in the <tt>accessorFuns</tt> list correspond to class
 methods while names in the <tt>vaccessors</tt> section correspond to
 variables that may be modified.</p>
<h2><a name="R_nn7">33.7 Enumerations</a></h2>
<p> R doesn't have a native enumeration type. Enumerations are
 represented as character strings in R, with calls to R functions that
 convert back and forth between integers.</p>
<p> The details of enumeration names and contents are stored in hidden R
 environments, which are named according the the enumeration name - for
 example, an enumeration colour:</p>
<div class="code">
<pre>
enum colour { red=-1, blue, green = 10 };
</pre>
</div>
<p> will be initialized by the following call in R:</p>
<div class="code">
<pre>
defineEnumeration(&quot;_colour&quot;,
 .values=c(&quot;red&quot; = .Call('R_swig_colour_red_get',FALSE, PACKAGE='enum_thorough'),
&quot;blue&quot; = .Call('R_swig_colour_blue_get',FALSE, PACKAGE='enum_thorough'),
&quot;green&quot; = .Call('R_swig_colour_green_get',FALSE, PACKAGE='enum_thorough')))
</pre>
</div>
<p> which will create an environment named <tt>.__E___colour</tt>. The
 enumeration values are initialised via calls to C/C++ code, allowing
 complex values for enumerations to be used. Calls to the C/C++ code
 require the compiled library to be loaded, so a <tt>delayedAssign</tt>
 is employed within <tt>defineEnumeration</tt> in order to allow the
 code to be easily used in R packages.</p>
<p> The user typically does not need to access the enumeration lookup
 functions or know the name of the enumeration type used by R.
 Attributes containing the type information are attached by swig to
 functions requiring enumeration arguments or returning enumeration
 values, and those attributes are used to identify and access the
 appropriate environments and thus translate between characters and
 integers.</p>
<p> The relevant functions, for debugging purposes, are <tt>
enumToInteger</tt> and <tt>enumFromInteger</tt>.</p>
<p> Anonymous enumerations are ignored by the binding generation
 process, leaving no way of accessing the value of anonymous
 enumerations from R code.</p>
<HR NOSHADE>
<h1><a name="Ruby">34 SWIG and Ruby</a></h1>

<!-- INDEX -->
<div class="sectiontoc">
<ul>
<li><a href="#Ruby_nn2">Preliminaries</a>
<ul>
<li><a href="#Ruby_nn3">Running SWIG</a></li>
<li><a href="#Ruby_nn4">Getting the right header files</a></li>
<li><a href="#Ruby_nn5">Compiling a dynamic module</a></li>
<li><a href="#Ruby_nn6">Using your module</a></li>
<li><a href="#Ruby_nn7">Static linking</a></li>
<li><a href="#Ruby_nn8">Compilation of C++ extensions</a></li>
</ul>
</li>
<li><a href="#Ruby_nn9">Building Ruby Extensions under Windows 95/NT</a>
<ul>
<li><a href="#Ruby_nn10">Running SWIG from Developer Studio</a></li>
</ul>
</li>
<li><a href="#Ruby_nn11">The Ruby-to-C/C++ Mapping</a>
<ul>
<li><a href="#Ruby_nn12">Modules</a></li>
<li><a href="#Ruby_nn13">Functions</a></li>
<li><a href="#Ruby_nn14">Variable Linking</a></li>
<li><a href="#Ruby_nn15">Constants</a></li>
<li><a href="#Ruby_nn16">Pointers</a></li>
<li><a href="#Ruby_nn17">Structures</a></li>
<li><a href="#Ruby_nn18">C++ classes</a></li>
<li><a href="#Ruby_nn19">C++ Inheritance</a></li>
<li><a href="#Ruby_nn20">C++ Overloaded Functions</a></li>
<li><a href="#Ruby_nn21">C++ Operators</a></li>
<li><a href="#Ruby_nn22">C++ namespaces</a></li>
<li><a href="#Ruby_nn23">C++ templates</a></li>
<li><a href="#Ruby_nn23_1">C++ Standard Template Library (STL)</a></li>
<li><a href="#Ruby_C_STL_Functors">C++ STL Functors</a></li>
<li><a href="#Ruby_C_Iterators">C++ STL Iterators</a></li>
<li><a href="#Ruby_nn24">C++ Smart Pointers</a>
<ul>
<li><a href="#Ruby_smart_pointers_shared_ptr">The shared_ptr Smart
 Pointer</a></li>
<li><a href="#Ruby_smart_pointers_generic">Generic Smart Pointers</a></li>
</ul>
</li>
<li><a href="#Ruby_nn25">Cross-Language Polymorphism</a>
<ul>
<li><a href="#Ruby_nn26">Exception Unrolling</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#Ruby_nn27">Naming</a>
<ul>
<li><a href="#Ruby_nn28">Defining Aliases</a></li>
<li><a href="#Ruby_nn29">Predicate Methods</a></li>
<li><a href="#Ruby_nn30">Bang Methods</a></li>
<li><a href="#Ruby_nn31">Getters and Setters</a></li>
</ul>
</li>
<li><a href="#Ruby_nn32">Input and output parameters</a></li>
<li><a href="#Ruby_nn33">Exception handling</a>
<ul>
<li><a href="#Ruby_nn34">Using the %exception directive</a></li>
<li><a href="#Ruby_nn34_2">Handling Ruby Blocks</a></li>
<li><a href="#Ruby_nn35">Raising exceptions</a></li>
<li><a href="#Ruby_nn36">Exception classes</a></li>
</ul>
</li>
<li><a href="#Ruby_nn37">Typemaps</a>
<ul>
<li><a href="#Ruby_nn38">What is a typemap?</a></li>
<li><a href="#Ruby_Typemap_scope">Typemap scope</a></li>
<li><a href="#Ruby_Copying_a_typemap">Copying a typemap</a></li>
<li><a href="#Ruby_Deleting_a_typemap">Deleting a typemap</a></li>
<li><a href="#Ruby_Placement_of_typemaps">Placement of typemaps</a></li>
<li><a href="#Ruby_nn39">Ruby typemaps</a>
<ul>
<li><a href="#Ruby_in_typemap">&quot;in&quot; typemap</a></li>
<li><a href="#Ruby_typecheck_typemap">&quot;typecheck&quot; typemap</a></li>
<li><a href="#Ruby_out_typemap">&quot;out&quot; typemap</a></li>
<li><a href="#Ruby_arginit_typemap">&quot;arginit&quot; typemap</a></li>
<li><a href="#Ruby_default_typemap">&quot;default&quot; typemap</a></li>
<li><a href="#Ruby_check_typemap">&quot;check&quot; typemap</a></li>
<li><a href="#Ruby_argout_typemap_">&quot;argout&quot; typemap</a></li>
<li><a href="#Ruby_freearg_typemap_">&quot;freearg&quot; typemap</a></li>
<li><a href="#Ruby_newfree_typemap">&quot;newfree&quot; typemap</a></li>
<li><a href="#Ruby_memberin_typemap">&quot;memberin&quot; typemap</a></li>
<li><a href="#Ruby_varin_typemap">&quot;varin&quot; typemap</a></li>
<li><a href="#Ruby_varout_typemap_">&quot;varout&quot; typemap</a></li>
<li><a href="#Ruby_throws_typemap">&quot;throws&quot; typemap</a></li>
<li><a href="#Ruby_directorin_typemap">directorin typemap</a></li>
<li><a href="#Ruby_directorout_typemap">directorout typemap</a></li>
<li><a href="#Ruby_directorargout_typemap">directorargout typemap</a></li>
<li><a href="#Ruby_ret_typemap">ret typemap</a></li>
<li><a href="#Ruby_globalin_typemap">globalin typemap</a></li>
</ul>
</li>
<li><a href="#Ruby_nn40">Typemap variables</a></li>
<li><a href="#Ruby_nn41">Useful Functions</a>
<ul>
<li><a href="#Ruby_nn42">C Datatypes to Ruby Objects</a></li>
<li><a href="#Ruby_nn43">Ruby Objects to C Datatypes</a></li>
<li><a href="#Ruby_nn44">Macros for VALUE</a></li>
<li><a href="#Ruby_nn45">Exceptions</a></li>
<li><a href="#Ruby_nn46">Iterators</a></li>
</ul>
</li>
<li><a href="#Ruby_nn47">Typemap Examples</a></li>
<li><a href="#Ruby_nn48">Converting a Ruby array to a char **</a></li>
<li><a href="#Ruby_nn49">Collecting arguments in a hash</a></li>
<li><a href="#Ruby_nn50">Pointer handling</a>
<ul>
<li><a href="#Ruby_nn51">Ruby Datatype Wrapping</a></li>
</ul>
</li>
<li><a href="#Ruby_nn52">Example: STL Vector to Ruby Array</a></li>
</ul>
</li>
<li><a href="#Ruby_nn65">Docstring Features</a>
<ul>
<li><a href="#Ruby_nn66">Module docstring</a></li>
<li><a href="#Ruby_nn67">%feature(&quot;autodoc&quot;)</a>
<ul>
<li><a href="#Ruby_nn68">%feature(&quot;autodoc&quot;, &quot;0&quot;)</a></li>
<li><a href="#Ruby_autodoc1">%feature(&quot;autodoc&quot;, &quot;1&quot;)</a></li>
<li><a href="#Ruby_autodoc2">%feature(&quot;autodoc&quot;, &quot;2&quot;)</a></li>
<li><a href="#Ruby_feature_autodoc3">%feature(&quot;autodoc&quot;, &quot;3&quot;)</a></li>
<li><a href="#Ruby_nn70">%feature(&quot;autodoc&quot;, &quot;docstring&quot;)</a></li>
</ul>
</li>
<li><a href="#Ruby_nn71">%feature(&quot;docstring&quot;)</a></li>
</ul>
</li>
<li><a href="#Ruby_nn53">Advanced Topics</a>
<ul>
<li><a href="#Ruby_operator_overloading">Operator overloading</a></li>
<li><a href="#Ruby_nn55">Creating Multi-Module Packages</a></li>
<li><a href="#Ruby_nn56">Specifying Mixin Modules</a></li>
</ul>
</li>
<li><a href="#Ruby_nn57">Memory Management</a>
<ul>
<li><a href="#Ruby_nn58">Mark and Sweep Garbage Collector</a></li>
<li><a href="#Ruby_nn59">Object Ownership</a></li>
<li><a href="#Ruby_nn60">Object Tracking</a></li>
<li><a href="#Ruby_nn61">Mark Functions</a></li>
<li><a href="#Ruby_nn62">Free Functions</a></li>
<li><a href="#Ruby_nn63">Embedded Ruby and the C++ Stack</a></li>
</ul>
</li>
</ul>
</div>
<!-- INDEX -->
<p>This chapter describes SWIG's support of Ruby.</p>
<h2><a name="Ruby_nn2">34.1 Preliminaries</a></h2>
<p> SWIG 4.0 is known to work with Ruby versions 1.9 and later. Given
 the choice, you should use the latest stable version of Ruby. You
 should also determine if your system supports shared libraries and
 dynamic loading. SWIG will work with or without dynamic loading, but
 the compilation process will vary.</p>
<p>This chapter covers most SWIG features, but in less depth than is
 found in earlier chapters. At the very least, make sure you also read
 the &quot;<a href="#SWIG">SWIG Basics</a>&quot; chapter. It is also assumed that
 the reader has a basic understanding of Ruby.</p>
<h3><a name="Ruby_nn3">34.1.1 Running SWIG</a></h3>
<p> To build a Ruby module, run SWIG using the <tt>-ruby</tt> option:</p>
<div class="code shell">
<pre>$ swig -ruby example.i
</pre>
</div>
<p> If building a C++ extension, add the <tt>-c++</tt> option:</p>
<div class="code shell">
<pre>$ swig -c++ -ruby example.i
</pre>
</div>
<p> This creates a file <tt>example_wrap.c</tt> (<tt>example_wrap.cxx</tt>
 if compiling a C++ extension) that contains all of the code needed to
 build a Ruby extension module. To finish building the module, you need
 to compile this file and link it with the rest of your program.</p>
<h3><a name="Ruby_nn4">34.1.2 Getting the right header files</a></h3>
<p> In order to compile the wrapper code, the compiler needs the <tt>
ruby.h</tt> header file and its dependencies, notably <tt>ruby/config.h</tt>
 which is found in a different, architecture-dependent, directory. The
 best way to find the compiler options needed to compile the code is to
 ask Ruby itself:</p>
<div class="code shell">
<pre>$ ruby -rrbconfig -e 'puts &quot;-I#{RbConfig::CONFIG[%q{rubyhdrdir}]} -I#{RbConfig::CONFIG[%q{rubyarchhdrdir}]}&quot;'
-I/usr/include/ruby-2.1.0 -I/usr/include/x86_64-linux-gnu/ruby-2.1.0
</pre>
</div>
<h3><a name="Ruby_nn5">34.1.3 Compiling a dynamic module</a></h3>
<p> Ruby extension modules are typically compiled into shared libraries
 that the interpreter loads dynamically at runtime. Since the exact
 commands for doing this vary from platform to platform, your best bet
 is to follow the steps described in the <tt>README.EXT</tt> file from
 the Ruby distribution:</p>
<ol>
<li>
<p>Create a file called <tt>extconf.rb</tt> that looks like the
 following:</p>
<div class="code targetlang">
<pre>require 'mkmf'
create_makefile('example')</pre>
</div></li>
<li>
<p>Type the following to build the extension:</p>
<div class="code shell">
<pre>
$ ruby extconf.rb
$ make
$ make install
    </pre>
</div></li>
</ol>
<p> Of course, there is the problem that mkmf does not work correctly on
 all platforms, e.g, HPUX. If you need to add your own make rules to the
 file that <tt>extconf.rb</tt> produces, you can add this:</p>
<div class="code targetlang">
<pre>open(&quot;Makefile&quot;, &quot;a&quot;) { |mf|
 puts &lt;&lt;EOM
 # Your make rules go here
 EOM
}
</pre>
</div>
<p> to the end of the <tt>extconf.rb</tt> file. If for some reason you
 don't want to use the standard approach, you'll need to determine the
 correct compiler and linker flags for your build platform. For example,
 assuming you have code you need to link to in a file called <tt>
example.c</tt>, a typical sequence of commands for the Linux operating
 system would look something like this:</p>
<div class="code shell">
<pre>$ swig -ruby example.i
$ gcc -O2 -fPIC -c example.c
$ gcc -O2 -fPIC -c example_wrap.c -I/usr/include/ruby-2.1.0
$ gcc -shared example.o example_wrap.o -o example.so
</pre>
</div>
<p> The -fPIC option tells GCC to generate position-independent code
 (PIC) which is required for most architectures (it's not vital on x86,
 but still a good idea as it allows code pages from the library to be
 shared between processes). Other compilers may need a different option
 specified instead of -fPIC.</p>
<p> If in doubt, consult the manual pages for your compiler and linker
 to determine the correct set of options. You might also check the <a href="https://github.com/swig/swig/wiki">
SWIG Wiki</a> for additional information.</p>
<h3><a name="Ruby_nn6">34.1.4 Using your module</a></h3>
<p> Ruby<i> module</i> names must be capitalized, but the convention for
 Ruby<i> feature</i> names is to use lowercase names. So, for example,
 the<b> Etc</b> extension module is imported by requiring the<b> etc</b>
 feature:</p>
<div class="code targetlang">
<pre># The feature name begins with a lowercase letter...
require 'etc'

# ... but the module name begins with an uppercase letter
puts &quot;Your login name: #{Etc.getlogin}&quot;
</pre>
</div>
<p> To stay consistent with this practice, you should always specify a<b>
 lowercase</b> module name with SWIG's <tt>%module</tt> directive. SWIG
 will automatically correct the resulting Ruby module name for your
 extension. So for example, a SWIG interface file that begins with:</p>
<div class="code">
<pre>%module example</pre>
</div>
<p> will result in an extension module using the feature name &quot;example&quot;
 and Ruby module name &quot;Example&quot;.</p>
<h3><a name="Ruby_nn7">34.1.5 Static linking</a></h3>
<p> An alternative approach to dynamic linking is to rebuild the Ruby
 interpreter with your extension module added to it. In the past, this
 approach was sometimes necessary due to limitations in dynamic loading
 support on certain machines. However, the situation has improved
 greatly over the last few years and you should not consider this
 approach unless there is really no other option.</p>
<p>The usual procedure for adding a new module to Ruby involves finding
 the Ruby source, adding an entry to the <tt>ext/Setup</tt> file, adding
 your directory to the list of extensions in the file, and finally
 rebuilding Ruby.</p>
<h3><a name="Ruby_nn8">34.1.6 Compilation of C++ extensions</a></h3>
<p> On most machines, C++ extension modules should be linked using the
 C++ compiler. For example:</p>
<div class="code shell">
<pre>
$ swig -c++ -ruby example.i
$ g++ -fPIC -c example.cxx
$ g++ -fPIC -c example_wrap.cxx -I/usr/include/ruby-2.1.0
$ g++ -shared example.o example_wrap.o -o example.so
</pre>
</div>
<p> If you've written an <tt>extconf.rb</tt> script to automatically
 generate a <tt>Makefile</tt> for your C++ extension module, keep in
 mind that (as of this writing) Ruby still uses <tt>gcc</tt> and not <tt>
g++</tt> as its linker. As a result, the required C++ runtime library
 support will not be automatically linked into your extension module and
 it may fail to load on some platforms. A workaround for this problem is
 use the <tt>mkmf</tt> module's <tt>append_library()</tt> method to add
 one of the C++ runtime libraries to the list of libraries linked into
 your extension, e.g.</p>
<div class="code targetlang">
<pre>require 'mkmf'
$libs = append_library($libs, &quot;supc++&quot;)
create_makefile('example')</pre>
</div>
<h2><a name="Ruby_nn9">34.2 Building Ruby Extensions under Windows 95/NT</a>
</h2>
<p> Building a SWIG extension to Ruby under Windows 95/NT is roughly
 similar to the process used with Unix. Normally, you will want to
 produce a DLL that can be loaded into the Ruby interpreter. For all
 recent versions of Ruby, the procedure described above (i.e. using an <tt>
extconf.rb</tt> script) will work with Windows as well; you should be
 able to build your code into a DLL by typing:</p>
<div class="code shell">
<pre>
C:\swigtest&gt; ruby extconf.rb
C:\swigtest&gt; nmake
C:\swigtest&gt; nmake install
</pre>
</div>
<p> The remainder of this section covers the process of compiling
 SWIG-generated Ruby extensions with Microsoft Visual C++ 6 (i.e. within
 the Developer Studio IDE, instead of using the command line tools). In
 order to build extensions, you may need to download the source
 distribution to the Ruby package, as you will need the Ruby header
 files.</p>
<h3><a name="Ruby_nn10">34.2.1 Running SWIG from Developer Studio</a></h3>
<p> If you are developing your application within Microsoft developer
 studio, SWIG can be invoked as a custom build option. The process
 roughly follows these steps :</p>
<ul>
<li> Open up a new workspace and use the AppWizard to select a DLL
 project.</li>
<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
 (i.e. <tt>example_wrap.c</tt>). Note : If using C++, choose a different
 suffix for the wrapper file such as <tt>example_wrap.cxx</tt>. Don't
 worry if the wrapper file doesn't exist yet--Developer Studio will keep
 a reference to it around.</li>
<li> Select the SWIG interface file and go to the settings menu. Under
 settings, select the &quot;Custom Build&quot; option.</li>
<li> Enter &quot;SWIG&quot; in the description field.</li>
<li> Enter &quot;<tt>swig -ruby -o $(ProjDir)\$(InputName)_wrap.c
 $(InputPath)</tt>&quot; in the &quot;Build command(s) field&quot;. You may have to
 include the path to swig.exe.</li>
<li> Enter &quot;<tt>$(ProjDir)\$(InputName)_wrap.c</tt>&quot; in the &quot;Output
 files(s) field&quot;.</li>
<li> Next, select the settings for the entire project and go to the
 C/C++ tab and select the Preprocessor category. Add NT=1 to the
 Preprocessor definitions. This must be set else you will get
 compilation errors. Also add IMPORT to the preprocessor definitions,
 else you may get runtime errors. Also add the include directories for
 your Ruby installation under &quot;Additional include directories&quot;.</li>
<li> Next, select the settings for the entire project and go to the Link
 tab and select the General category. Set the name of the output file to
 match the name of your Ruby module (i.e.. example.dll). Next add the
 Ruby library file to your link libraries under Object/Library modules.
 For example &quot;mswin32-ruby16.lib. You also need to add the path to the
 library under the Input tab - Additional library path.</li>
<li> Build your project.</li>
</ul>
<p> Now, assuming all went well, SWIG will be automatically invoked when
 you build your project. Any changes made to the interface file will
 result in SWIG being automatically invoked to produce a new version of
 the wrapper file. To run your new Ruby extension, simply run Ruby and
 use the <tt>require</tt> command as normal. For example if you have
 this ruby file run.rb:</p>
<div class="code targetlang">
<pre># file: run.rb
require 'Example'

# Call a c function
print &quot;Foo = &quot;, Example.Foo, &quot;\n&quot;</pre>
</div>
<p> Ensure the dll just built is in your path or current directory, then
 run the Ruby script from the DOS/Command prompt:</p>
<div class="code shell">
<pre>
C:\swigtest&gt; ruby run.rb
Foo = 3.0
</pre>
</div>
<h2><a name="Ruby_nn11">34.3 The Ruby-to-C/C++ Mapping</a></h2>
<p> This section describes the basics of how SWIG maps C or C++
 declarations in your SWIG interface files to Ruby constructs.</p>
<h3><a name="Ruby_nn12">34.3.1 Modules</a></h3>
<p> The SWIG <tt>%module</tt> directive specifies the name of the Ruby
 module. If you specify:</p>
<div class="code">
<pre>%module example</pre>
</div>
<p> then everything is wrapped into a Ruby module named <tt>Example</tt>
 that is nested directly under the global module. You can specify a more
 deeply nested module by specifying the fully-qualified module name in
 quotes, e.g.</p>
<div class="code">
<pre>%module &quot;foo::bar::spam&quot;</pre>
</div>
<p> An alternate method of specifying a nested module name is to use the
 <tt>-prefix</tt> option on the SWIG command line. The prefix that you
 specify with this option will be prepended to the module name specified
 with the <tt>%module</tt> directive in your SWIG interface file. So for
 example, this declaration at the top of your SWIG interface file:</p>
<div class="code">
<pre>%module &quot;foo::bar::spam&quot;</pre>
</div>
<p> will result in a nested module name of <tt>Foo::Bar::Spam</tt>, but
 you can achieve the <span style="font-style: italic;">same</span>
 effect by specifying:</p>
<div class="code">
<pre>%module spam</pre>
</div>
<p> and then running SWIG with the <tt>-prefix</tt> command line option:</p>
<div class="code shell">
<pre>
$ swig -ruby -prefix &quot;foo::bar::&quot; example.i
</pre>
</div>
<p> Starting with SWIG 1.3.20, you can also choose to wrap everything
 into the global module by specifying the <tt>-globalmodule</tt> option
 on the SWIG command line, i.e.</p>
<div class="code shell">
<pre>
$ swig -ruby -globalmodule example.i
</pre>
</div>
<p> Note that this does not relieve you of the requirement of specifying
 the SWIG module name with the <tt>%module</tt> directive (or the <tt>
-module</tt> command-line option) as described earlier.</p>
<p>When choosing a module name, do not use the same name as a built-in
 Ruby command or standard module name, as the results may be
 unpredictable. Similarly, if you're using the <tt>-globalmodule</tt>
 option to wrap everything into the global module, take care that the
 names of your constants, classes and methods don't conflict with any of
 Ruby's built-in names.</p>
<h3><a name="Ruby_nn13">34.3.2 Functions</a></h3>
<p> Global functions are wrapped as Ruby module methods. For example,
 given the SWIG interface file <tt>example.i</tt>:</p>
<div class="code">
<pre>%module example

int fact(int n);</pre>
</div>
<p> and C source file <tt>example.c</tt>:</p>
<div class="code">
<pre>int fact(int n) {
  if (n == 0)
  return 1;
  return (n * fact(n-1));
}</pre>
</div>
<p> SWIG will generate a method<i> fact</i> in the<i> Example</i> module
 that can be used like so:</p>
<div class="code targetlang">
<pre>$ <b>irb</b>
irb(main):001:0&gt; <b>require 'example'</b>
true
irb(main):002:0&gt; <b>Example.fact(4)</b>
24</pre>
</div>
<h3><a name="Ruby_nn14">34.3.3 Variable Linking</a></h3>
<p> C/C++ global variables are wrapped as a pair of singleton methods
 for the module: one to get the value of the global variable and one to
 set it. For example, the following SWIG interface file declares two
 global variables:</p>
<div class="code">
<pre>// SWIG interface file with global variables
%module example
...
%inline %{
  extern int variable1;
  extern double Variable2;
%}
...</pre>
</div>
<p> Now look at the Ruby interface:</p>
<div class="code targetlang">
<pre>$ <b>irb</b>
irb(main):001:0&gt; <b>require 'Example'</b>
true
irb(main):002:0&gt; <b>Example.variable1 = 2</b>
2
irb(main):003:0&gt; <b>Example.Variable2 = 4 * 10.3</b>
41.2
irb(main):004:0&gt; <b>Example.Variable2</b>
41.2</pre>
</div>
<p> If you make an error in variable assignment, you will receive an
 error message. For example:</p>
<div class="code targetlang">
<pre>irb(main):005:0&gt; <b>Example.Variable2 = &quot;hello&quot;</b>
TypeError: no implicit conversion to float from string
from (irb):5:in `Variable2='
from (irb):5</pre>
</div>
<p> If a variable is declared as <tt>const</tt>, it is wrapped as a
 read-only variable. Attempts to modify its value will result in an
 error.</p>
<p>To make ordinary variables read-only, you can also use the <tt>
%immutable</tt> directive. For example:</p>
<div class="code">
<pre>%immutable;
%inline %{
  extern char *path;
%}
%mutable;</pre>
</div>
<p> The <tt>%immutable</tt> directive stays in effect until it is
 explicitly disabled using <tt>%mutable</tt>.</p>
<p>Note: When SWIG is invoked with the <tt>-globalmodule</tt> option in
 effect, the C/C++ global variables will be translated into Ruby global
 variables. Type-checking and the optional read-only characteristic are
 available in the same way as described above. However the example would
 then have to be modified and executed in the following way:<div class="code targetlang">
<pre>$ <b>irb</b>
irb(main):001:0&gt; <b>require 'Example'</b>
true
irb(main):002:0&gt; <b>$variable1 = 2</b>
2
irb(main):003:0&gt; <b>$Variable2 = 4 * 10.3</b>
41.2
irb(main):004:0&gt; <b>$Variable2</b>
41.2</pre>
</div></p>
<h3><a name="Ruby_nn15">34.3.4 Constants</a></h3>
<p> C/C++ constants are wrapped as module constants initialized to the
 appropriate value. To create a constant, use <tt>#define</tt> or the <tt>
%constant</tt> directive. For example:</p>
<div class="code">
<pre>#define PI 3.14159
#define VERSION &quot;1.0&quot;

%constant int FOO = 42;
%constant const char *path = &quot;/usr/local&quot;;

const int BAR = 32;</pre>
</div>
<p> Remember to use the :: operator in Ruby to get at these constant
 values, e.g.</p>
<div class="code targetlang">
<pre>$ <b>irb</b>
irb(main):001:0&gt; <b>require 'Example'</b>
true
irb(main):002:0&gt; <b>Example::PI</b>
3.14159</pre>
</div>
<h3><a name="Ruby_nn16">34.3.5 Pointers</a></h3>
<p> &quot;Opaque&quot; pointers to arbitrary C/C++ types (i.e. types that aren't
 explicitly declared in your SWIG interface file) are wrapped as data
 objects. So, for example, consider a SWIG interface file containing
 only the declarations:</p>
<div class="code">
<pre>Foo *get_foo();
void set_foo(Foo *foo);</pre>
</div>
<p> For this case, the<i> get_foo()</i> method returns an instance of an
 internally generated Ruby class:</p>
<div class="code targetlang">
<pre>irb(main):001:0&gt; <b>foo = Example::get_foo()</b>
#&lt;SWIG::TYPE_p_Foo:0x402b1654&gt;</pre>
</div>
<p> A <tt>NULL</tt> pointer is always represented by the Ruby <tt>nil</tt>
 object.</p>
<h3><a name="Ruby_nn17">34.3.6 Structures</a></h3>
<p> C/C++ structs are wrapped as Ruby classes, with accessor methods
 (i.e. &quot;getters&quot; and &quot;setters&quot;) for all of the struct members. For
 example, this struct declaration:</p>
<div class="code">
<pre>struct Vector {
  double x, y;
};</pre>
</div>
<p> gets wrapped as a <tt>Vector</tt> class, with Ruby instance methods <tt>
x</tt>, <tt>x=</tt>, <tt>y</tt> and <tt>y=</tt>. These methods can be
 used to access structure data from Ruby as follows:</p>
<div class="code targetlang">
<pre>$ <b>irb</b>
irb(main):001:0&gt; <b>require 'Example'</b>
true
irb(main):002:0&gt; <b>f = Example::Vector.new</b>
#&lt;Example::Vector:0x4020b268&gt;
irb(main):003:0&gt; <b>f.x = 10</b>
nil
irb(main):004:0&gt; <b>f.x</b>
10.0</pre>
</div>
<p> Similar access is provided for unions and the public data members of
 C++ classes.</p>
<p><tt>const</tt> members of a structure are read-only. Data members can
 also be forced to be read-only using the <tt>%immutable</tt> directive
 (in C++, <tt>private</tt> may also be used). For example:</p>
<div class="code">
<pre>struct Foo {
  ...
  %immutable;
  int x; /* Read-only members */
  char *name;
  %mutable;
  ...
};</pre>
</div>
<p> When <tt>char *</tt> members of a structure are wrapped, the
 contents are assumed to be dynamically allocated using <tt>malloc</tt>
 or <tt>new</tt> (depending on whether or not SWIG is run with the <tt>
-c++</tt> 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 shortly).</p>
<p>Array members are normally wrapped as read-only. For example, this
 code:</p>
<div class="code">
<pre>struct Foo {
  int x[50];
};</pre>
</div>
<p> produces a single accessor function like this:</p>
<div class="code">
<pre>int *Foo_x_get(Foo *self) {
  return self-&gt;x;
};</pre>
</div>
<p> If you want to set an array member, you will need to supply a
 &quot;memberin&quot; typemap described in the <a href="#Ruby_memberin_typemap">
section on typemaps</a>. As a special case, SWIG does generate code to
 set array members of type <tt>char</tt> (allowing you to store a Ruby
 string in the structure).</p>
<p>When structure members are wrapped, they are handled as pointers. For
 example,</p>
<div class="code">
<pre>struct Foo {
  ...
};

struct Bar {
  Foo f;
};</pre>
</div>
<p> generates accessor functions such as this:</p>
<div class="code">
<pre>Foo *Bar_f_get(Bar *b) {
  return &amp;b-&gt;f;
}

void Bar_f_set(Bar *b, Foo *val) {
  b-&gt;f = *val;
}</pre>
</div>
<h3><a name="Ruby_nn18">34.3.7 C++ classes</a></h3>
<p> Like structs, C++ classes are wrapped by creating a new Ruby class
 of the same name with accessor methods for the public class member
 data. Additionally, public member functions for the class are wrapped
 as Ruby instance methods, and public static member functions are
 wrapped as Ruby singleton methods. So, given the C++ class declaration:</p>
<div class="code">
<pre>class List {
public:
  List();
  ~List();
  int search(char *item);
  void insert(char *item);
  void remove(char *item);
  char *get(int n);
  int length;
  static void print(List *l);
};</pre>
</div>
<p> SWIG would create a <tt>List</tt> class with:</p>
<ul>
<li> instance methods<i> search</i>,<i> insert</i>,<i> remove</i>, and<i>
 get</i>;</li>
<li> instance methods<i> length</i> and<i> length=</i> (to get and set
 the value of the<i> length</i> data member); and,</li>
<li> a<i> print</i> singleton method for the class.</li>
</ul>
<p> In Ruby, these functions are used as follows:</p>
<div class="code targetlang">
<pre>require 'Example'

l = Example::List.new

l.insert(&quot;Ale&quot;)
l.insert(&quot;Stout&quot;)
l.insert(&quot;Lager&quot;)
Example.print(l)
l.length()
----- produces the following output 
Lager
Stout
Ale
3</pre>
</div>
<h3><a name="Ruby_nn19">34.3.8 C++ Inheritance</a></h3>
<p> The SWIG type-checker is fully aware of C++ inheritance. Therefore,
 if you have classes like this:</p>
<div class="code">
<pre>class Parent {
  ...
};

class Child : public Parent {
  ...
};</pre>
</div>
<p> those classes are wrapped into a hierarchy of Ruby classes that
 reflect the same inheritance structure. All of the usual Ruby utility
 methods work normally:</p>
<div class="code">
<pre>irb(main):001:0&gt; <b>c = Child.new</b>
#&lt;Bar:0x4016efd4&gt;
irb(main):002:0&gt; <b>c.instance_of? Child</b>
true
irb(main):003:0&gt; <b>b.instance_of? Parent</b>
false
irb(main):004:0&gt; <b>b.is_a? Child</b>
true
irb(main):005:0&gt; <b>b.is_a? Parent</b>
true
irb(main):006:0&gt; <b>Child &lt; Parent</b>
true
irb(main):007:0&gt; <b>Child &gt; Parent</b>
false</pre>
</div>
<p> Furthermore, if you have a function like this:</p>
<div class="code">
<pre>void spam(Parent *f);</pre>
</div>
<p> then the function <tt>spam()</tt> accepts <tt>Parent</tt>* or a
 pointer to any class derived from <tt>Parent</tt>.</p>
<p>Until recently, the Ruby module for SWIG didn't support multiple
 inheritance, and this is still the default behavior. This doesn't mean
 that you can't wrap C++ classes which inherit from multiple base
 classes; it simply means that only the<b> first</b> base class listed
 in the class declaration is considered, and any additional base classes
 are ignored. As an example, consider a SWIG interface file with a
 declaration like this:</p>
<div class="code">
<pre>class Derived : public Base1, public Base2
{
  ...
};</pre>
</div>
<p> For this case, the resulting Ruby class (<tt>Derived</tt>) will only
 consider <tt>Base1</tt> as its superclass. It won't inherit any of <tt>
Base2</tt>'s member functions or data and it won't recognize <tt>Base2</tt>
 as an &quot;ancestor&quot; of <tt>Derived</tt> (i.e. the<em> is_a?</em>
 relationship would fail). When SWIG processes this interface file,
 you'll see a warning message like:</p>
<div class="code shell">
<pre>example.i:5: Warning 802: Warning for Derived: Base Base2 ignored.
Multiple inheritance is not supported in Ruby.</pre>
</div>
<p> Starting with SWIG 1.3.20, the Ruby module for SWIG provides limited
 support for multiple inheritance. Because the approach for dealing with
 multiple inheritance introduces some limitations, this is an optional
 feature that you can activate with the <tt>-minherit</tt> command-line
 option:</p>
<div class="code shell">
<pre>
$ swig -c++ -ruby -minherit example.i
</pre>
</div>
<p> Using our previous example, if your SWIG interface file contains a
 declaration like this:</p>
<div class="code">
<pre>class Derived : public Base1, public Base2
{
  ...
};</pre>
</div>
<p> and you run SWIG with the <tt>-minherit</tt> command-line option,
 then you will end up with a Ruby class <tt>Derived</tt> that appears to
 &quot;inherit&quot; the member data and functions from both <tt>Base1</tt> and <tt>
Base2</tt>. What actually happens is that three different top-level
 classes are created, with Ruby's <tt>Object</tt> class as their
 superclass. Each of these classes defines a nested module named <tt>
Impl</tt>, and it's in these nested <tt>Impl</tt> modules that the
 actual instance methods for the classes are defined, i.e.</p>
<div class="code targetlang">
<pre>class Base1
  module Impl
  # Define Base1 methods here
  end
  include Impl
end

class Base2
  module Impl
  # Define Base2 methods here
  end
  include Impl
end

class Derived
  module Impl
  include Base1::Impl
  include Base2::Impl
  # Define Derived methods here
  end
  include Impl
end</pre>
</div>
<p> Observe that after the nested <tt>Impl</tt> module for a class is
 defined, it is mixed-in to the class itself. Also observe that the <tt>
Derived::Impl</tt> module first mixes-in its base classes' <tt>Impl</tt>
 modules, thus &quot;inheriting&quot; all of their behavior.</p>
<p>The primary drawback is that, unlike the default mode of operation,
 neither <tt>Base1</tt> nor <tt>Base2</tt> is a true superclass of <tt>
Derived</tt> anymore:</p>
<div class="code targetlang">
<pre>obj = Derived.new
obj.is_a? Base1 # this will return false...
obj.is_a? Base2 # ... and so will this</pre>
</div>
<p> In most cases, this is not a serious problem since objects of type <tt>
Derived</tt> will otherwise behave as though they inherit from both <tt>
Base1</tt> and <tt>Base2</tt> (i.e. they exhibit <a href="http://c2.com/cgi/wiki?DuckTyping">
&quot;Duck Typing&quot;</a>).</p>
<h3><a name="Ruby_nn20">34.3.9 C++ Overloaded Functions</a></h3>
<p> C++ overloaded functions, methods, and constructors are mostly
 supported by SWIG. For example, if you have two functions like this:</p>
<div class="code">
<pre>void foo(int);
void foo(char *c);</pre>
</div>
<p> You can use them in Ruby in a straightforward manner:</p>
<div class="code targetlang">
<pre>irb(main):001:0&gt; <b>foo(3)</b> # foo(int)
irb(main):002:0&gt; <b>foo(&quot;Hello&quot;)</b> # foo(char *c)</pre>
</div>
<p>Similarly, if you have a class like this,</p>
<div class="code">
<pre>class Foo {
public:
  Foo();
  Foo(const Foo &amp;);
  ...
};</pre>
</div>
<p>you can write Ruby code like this:</p>
<div class="code targetlang">
<pre>irb(main):001:0&gt; <b>f = Foo.new</b> # Create a Foo
irb(main):002:0&gt; <b>g = Foo.new(f)</b> # Copy f</pre>
</div>
<p> Overloading support is not quite as flexible as in C++. Sometimes
 there are methods that SWIG can't disambiguate. For example:</p>
<div class="code">
<pre>void spam(int);
void spam(short);</pre>
</div>
<p>or</p>
<div class="code">
<pre>void foo(Bar *b);
void foo(Bar &amp;b);</pre>
</div>
<p> If declarations such as these appear, you will get a warning message
 like this:</p>
<div class="code shell">
<pre>
example.i:12: Warning 509: Overloaded method spam(short) effectively ignored,
example.i:11: Warning 509: as it is shadowed by spam(int).
</pre>
</div>
<p> To fix this, you either need to ignore or rename one of the methods.
 For example:</p>
<div class="code">
<pre>%rename(spam_short) spam(short);
...
void spam(int); 
void spam(short); // Accessed as spam_short</pre>
</div>
<p>or</p>
<div class="code">
<pre>%ignore spam(short);
...
void spam(int); 
void spam(short); // Ignored</pre>
</div>
<p> SWIG resolves overloaded functions and methods using a
 disambiguation scheme that ranks and sorts declarations according to a
 set of type-precedence rules. The order in which declarations appear in
 the input does not matter except in situations where ambiguity
 arises--in this case, the first declaration takes precedence.</p>
<p>Please refer to the <a href="#SWIGPlus">&quot;SWIG and C++&quot;</a> chapter
 for more information about overloading.</p>
<h3><a name="Ruby_nn21">34.3.10 C++ Operators</a></h3>
<p> For the most part, overloaded operators are handled automatically by
 SWIG and do not require any special treatment on your part. So if your
 class declares an overloaded addition operator, e.g.</p>
<div class="code">
<pre>class Complex {
  ...
  Complex operator+(Complex &amp;);
  ...
};</pre>
</div>
<p> the resulting Ruby class will also support the addition (+) method
 correctly.</p>
<p>For cases where SWIG's built-in support is not sufficient, C++
 operators can be wrapped using the <tt>%rename</tt> directive
 (available on SWIG 1.3.10 and later releases). All you need to do is
 give the operator the name of a valid Ruby identifier. For example:</p>
<div class="code">
<pre>%rename(add_complex) operator+(Complex &amp;, Complex &amp;);
...
Complex operator+(Complex &amp;, Complex &amp;);</pre>
</div>
<p>Now, in Ruby, you can do this:</p>
<div class="code targetlang">
<pre>a = Example::Complex.new(2, 3)
b = Example::Complex.new(4, -1)
c = Example.add_complex(a, b)</pre>
</div>
<p> More details about wrapping C++ operators into Ruby operators is
 discussed in the <a href="#Ruby_operator_overloading">section on
 operator overloading</a>.</p>
<h3><a name="Ruby_nn22">34.3.11 C++ namespaces</a></h3>
<p> 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,</p>
<div class="code">
<pre>%module example

namespace foo {
  int fact(int n);
  struct Vector {
    double x, y, z;
  };
};</pre>
</div>
<p>it works in Ruby as follows:</p>
<div class="code targetlang">
<pre>irb(main):001:0&gt; <b>require 'example'</b>
true
irb(main):002:0&gt; <b>Example.fact(3)</b>
6
irb(main):003:0&gt; <b>v = Example::Vector.new</b>
#&lt;Example::Vector:0x4016f4d4&gt;
irb(main):004:0&gt; <b>v.x = 3.4</b>
3.4
irb(main):004:0&gt; <b>v.y</b>
0.0</pre>
</div>
<p> If your program has more than one namespace, name conflicts (if any)
 can be resolved using <tt>%rename</tt> For example:</p>
<div class="code">
<pre>%rename(Bar_spam) Bar::spam;

namespace Foo {
  int spam();
}

namespace Bar {
  int spam();
}</pre>
</div>
<p> If you have more than one namespace and your want to keep their
 symbols separate, consider wrapping them as separate SWIG modules. For
 example, make the module name the same as the namespace and create
 extension modules for each namespace separately. If your program
 utilizes thousands of small deeply nested namespaces each with
 identical symbol names, well, then you get what you deserve.</p>
<h3><a name="Ruby_nn23">34.3.12 C++ templates</a></h3>
<p> C++ templates don't present a huge problem for SWIG. However, in
 order to create wrappers, you have to tell SWIG to create wrappers for
 a particular template instantiation. To do this, you use the <tt>
%template</tt> directive. For example:</p>
<div class="code">
<pre>%module example

%{
#include &quot;pair.h&quot;
%}

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

%template(Pairii) pair&lt;int, int&gt;;</pre>
</div>
<p>In Ruby:</p>
<div class="code targetlang">
<pre>irb(main):001:0&gt; <b>require 'example'</b>
true
irb(main):002:0&gt; <b>p = Example::Pairii.new(3, 4)</b>
#&lt;Example:Pairii:0x4016f4df&gt;
irb(main):003:0&gt; <b>p.first</b>
3
irb(main):004:0&gt; <b>p.second</b>
4</pre>
</div>
<h3><a name="Ruby_nn23_1">34.3.13 C++ Standard Template Library (STL)</a>
</h3>
<p> On a related note, the standard SWIG library contains a number of
 modules that provide typemaps for standard C++ library classes (such as
 <tt>std::pair</tt>, <tt>std::string</tt> and <tt>std::vector</tt>).
 These library modules don't provide wrappers around the templates
 themselves, but they do make it convenient for users of your extension
 module to pass Ruby objects (such as arrays and strings) to wrapped C++
 code that expects instances of standard C++ templates. For example,
 suppose the C++ library you're wrapping has a function that expects a
 vector of floats:</p>
<div class="code">
<pre>%module example

float sum(const std::vector&lt;float&gt;&amp; values);</pre>
</div>
<p> Rather than go through the hassle of writing an &quot;in&quot; typemap to
 convert an array of Ruby numbers into a std::vector&lt;float&gt;, you can
 just use the <tt>std_vector.i</tt> module from the standard SWIG
 library:</p>
<div class="code">
<pre>%module example

%include std_vector.i
float sum(const std::vector&lt;float&gt;&amp; values);</pre>
</div>
<p>Ruby's STL wrappings provide additional methods to make them behave
 more similarly to Ruby's native classes.</p>
<p>Thus, you can do, for example:</p>
<div class="targetlang">
<pre>v = IntVector.new
v &lt;&lt; 2
v &lt;&lt; 3
v &lt;&lt; 4
v.each { |x| puts x }

=&gt; 2
3
4
v.delete_if { |x| x == 3 }
=&gt; [2, 4]</pre>
</div>
<p>The SWIG Ruby module provides also the ability for all the STL
 containers to carry around Ruby native objects (Fixnum, Classes, etc)
 making them act almost like Ruby's own Array, Hash, etc. To do that,
 you need to define a container that contains a swig::GC_VALUE, like:</p>
<div class="code">
<pre>
%module nativevector

%{
std::vector&lt; swig::GC_VALUE &gt; NativeVector;
%}

%template(NativeVector) std::vector&lt; swig::GC_VALUE &gt;;
</pre>
</div>
<p>This vector can then contain any Ruby object, making them almost
 identical to Ruby's own Array class.</p>
<div class="targetlang">
<pre>require 'nativevector'
include NativeVector

v = NativeVector.new
v &lt;&lt; 1
v &lt;&lt; [1, 2]
v &lt;&lt; 'hello'

class A; end

v &lt;&lt; A.new

puts v
=&gt; [1, [1, 2], 'hello', #&lt;A:0x245325&gt;]
</pre>
</div>
<p>Obviously, there is a lot more to template wrapping than shown in
 these examples. More details can be found in the <a href="#SWIGPlus">
SWIG and C++</a> chapter.</p>
<h3><a name="Ruby_C_STL_Functors">34.3.14 C++ STL Functors</a></h3>
<p>Some containers in the STL allow you to modify their default behavior
 by using so called functors or function objects. Functors are often
 just a very simple struct with <tt>operator()</tt> redefined or an
 actual C/C++ function. This allows you, for example, to always keep the
 sort order of a STL container to your liking.</p>
<p>The Ruby STL mappings allows you to modify those containers that
 support functors using Ruby procs or methods, instead. Currently, this
 includes <tt>std::set</tt>, <tt>set::map</tt>, <tt>std::multiset</tt>
 and <tt>std::multimap</tt>.</p>
<p>The functors in swig are called <tt>swig::UnaryFunction</tt> and <tt>
swig::BinaryFunction</tt>. For C++ predicates (ie. functors that must
 return bool as a result) <tt>swig::UnaryPredicate</tt> and <tt>
swig::BinaryPredicate</tt> are provided.</p>
<p>As an example, if given this swig file:</p>
<div class="code">
<pre>
%module intset;

%include &lt;std_set.i&gt;

%template(IntSet) std::set&lt; int, swig::BinaryPredicate &gt;;
</pre>
</div>
<p>You can then use the set from Ruby with or without a proc object as a
 predicate:</p>
<div class="targetlang">
<pre>
require 'intset'
include Intset

# Default sorting behavior defined in C++
a = IntSet.new
a &lt;&lt; 1
a &lt;&lt; 2
a &lt;&lt; 3
a
<b>=&gt; [1, 2, 3]</b>

# Custom sorting behavior defined by a Ruby proc
b = IntSet.new( proc { |a, b| a &gt; b } )
b &lt;&lt; 1
b &lt;&lt; 2
b &lt;&lt; 3
b
<b>=&gt;  [3, 2, 1]</b>
</pre>
</div>
<h3><a name="Ruby_C_Iterators">34.3.15 C++ STL Iterators</a></h3>
<p>The STL is well known for the use of iterators. There are a number of
 iterators possible with different properties, but in general there are
 two main categories: const iterators and non-const iterators. The const
 iterators can access and not modify the values they point at, while the
 non-const iterators can both read and modify the values.</p>
<p>The Ruby STL wrappings support both type of iterators by using a
 proxy class in-between. This proxy class is <tt>swig::Iterator</tt> or <tt>
swig::ConstIterator</tt>. Derived from them are template classes that
 need to be initialized with the actual iterator for the container you
 are wrapping and often times with the beginning and ending points of
 the iteration range.</p>
<p>The SWIG STL library already provides typemaps to all the standard
 containers to do this wrapping automatically for you, but if you have
 your own STL-like iterator, you will need to write your own typemap for
 them. For out typemaps, the special functions <tt>make_const_iterator</tt>
 and <tt>make_nonconst_iterator</tt> are provided.</p>
<p>These can be used either like:</p>
<div class="code">
<pre>
make_const_iterator( iterator, rubyclass );
make_const_iterator( iterator, iterator_begin, iterator_end, rubyclass );
</pre>
</div>
<p>The iterators support a <tt>next()</tt> and <tt>previous()</tt>
 member function to just change the iterator without returning anything.
 <tt>previous()</tt> should obviously only be used for bidirectional
 iterators. You can also advance the iterator multiple steps by using
 standard math operations like <tt>+=</tt>.</p>
<p>The value the iterator points at can be accessed with <tt>value()</tt>
 -- this is equivalent to dereferencing it with <tt>*i</tt>. For
 non-const iterators, a <tt>value=()</tt> function is also provided
 which allows you to change the value pointed by the iterator. This is
 equivalent to the C++ construct of dereferencing and assignment, like <tt>
*i = something</tt>.</p>
<p>Thus, given say a vector class of doubles defined as:</p>
<div class="code">
<pre>
%module doublevector

%include std_vector.i

%template(DoubleVector) std::vector&lt;double&gt;;
</pre>
</div>
<p>Its iterator can then be used from Ruby like:</p>
<div class="targetlang">
<pre>
require 'doublevector'
include Doublevector

v = DoubleVector.new
v &lt;&lt; 1
v &lt;&lt; 2
v &lt;&lt; 3

#
# an elaborate and less efficient way of doing v.map! { |x| x+2 }
#
i = v.begin
e = v.end
while i != e
  val = i.value
  val += 2
  i.value = val
  i.next
end
i
<b>&gt;&gt; [3, 4, 5 ]</b>
</pre>
</div>
<p>If you'd rather have STL classes without any iterators, you should
 define <tt>-DSWIG_NO_EXPORT_ITERATOR_METHODS</tt> when running swig.</p>
<h3><a name="Ruby_nn24">34.3.16 C++ Smart Pointers</a></h3>
<h4><a name="Ruby_smart_pointers_shared_ptr">34.3.16.1 The shared_ptr
 Smart Pointer</a></h4>
<p> The C++11 standard provides <tt>std::shared_ptr</tt> which was
 derived from the Boost implementation, <tt>boost::shared_ptr</tt>. Both
 of these are available for Ruby in the SWIG library and usage is
 outlined in the <a href="#Library_std_shared_ptr">shared_ptr smart
 pointer</a> library section.</p>
<h4><a name="Ruby_smart_pointers_generic">34.3.16.2 Generic Smart
 Pointers</a></h4>
<p> In certain C++ programs, it is common to use classes that have been
 wrapped by so-called &quot;smart pointers.&quot; Generally, this involves the use
 of a template class that implements <tt>operator-&gt;()</tt> like this:</p>
<div class="code">
<pre>template&lt;class T&gt; class SmartPtr {
  ...
  T *operator-&gt;();
  ...
}</pre>
</div>
<p>Then, if you have a class like this,</p>
<div class="code">
<pre>class Foo {
public:
  int x;
  int bar();
};</pre>
</div>
<p>A smart pointer would be used in C++ as follows:</p>
<div class="code">
<pre>SmartPtr&lt;Foo&gt; p = CreateFoo(); // Created somehow (not shown)
...
p-&gt;x = 3; // Foo::x
int y = p-&gt;bar(); // Foo::bar</pre>
</div>
<p> To wrap this in Ruby, simply tell SWIG about the <tt>SmartPtr</tt>
 class and the low-level <tt>Foo</tt> object. Make sure you instantiate <tt>
SmartPtr</tt> using <tt>%template</tt> if necessary. For example:</p>
<div class="code">
<pre>%module example
...
%template(SmartPtrFoo) SmartPtr&lt;Foo&gt;;
...</pre>
</div>
<p>Now, in Ruby, everything should just &quot;work&quot;:</p>
<div class="code targetlang">
<pre>irb(main):001:0&gt; <b>p = Example::CreateFoo()</b> # Create a smart-pointer somehow
#&lt;Example::SmartPtrFoo:0x4016f4df&gt;
irb(main):002:0&gt; <b>p.x = 3</b> # Foo::x
3
irb(main):003:0&gt; <b>p.bar()</b> # Foo::bar</pre>
</div>
<p> If you ever need to access the underlying pointer returned by <tt>
operator-&gt;()</tt> itself, simply use the <tt>__deref__()</tt> method.
 For example:</p>
<div class="code targetlang">
<pre>irb(main):004:0&gt; <b>f = p.__deref__()</b> # Returns underlying Foo *</pre>
</div>
<h3><a name="Ruby_nn25">34.3.17 Cross-Language Polymorphism</a></h3>
<p> SWIG's Ruby module supports cross-language polymorphism (a.k.a. the
 &quot;directors&quot; feature) similar to that for SWIG's Python module. Rather
 than duplicate the information presented in the <a href="#Python">
Python</a> chapter, this section just notes the differences that you
 need to be aware of when using this feature with Ruby.</p>
<h4><a name="Ruby_nn26">34.3.17.1 Exception Unrolling</a></h4>
<p> Whenever a C++ director class routes one of its virtual member
 function calls to a Ruby instance method, there's always the
 possibility that an exception will be raised in the Ruby code. By
 default, those exceptions are ignored, which simply means that the
 exception will be exposed to the Ruby interpreter. If you would like to
 change this behavior, you can use the <tt>%feature(&quot;director:except&quot;)</tt>
 directive to indicate what action should be taken when a Ruby exception
 is raised. The following code should suffice in most cases:</p>
<div class="code">
<pre>%feature(&quot;director:except&quot;) {
  throw Swig::DirectorMethodException($error);
}</pre>
</div>
<p> When this feature is activated, the call to the Ruby instance method
 is &quot;wrapped&quot; using the <tt>rb_rescue2()</tt> function from Ruby's C
 API. If any Ruby exception is raised, it will be caught here and a C++
 exception is raised in its place.</p>
<h2><a name="Ruby_nn27">34.4 Naming</a></h2>
<p>Ruby has several common naming conventions. Constants are generally
 in upper case, module and class names are in camel case and methods are
 in lower case with underscores. For example:</p>
<div class="code">
<ul>
<li><strong>MATH::PI</strong> is a constant name</li>
<li><strong>MyClass</strong> is a class name</li>
<li><strong>my_method</strong> is a method name</li>
</ul>
</div>
<p>Prior to version 1.3.28, SWIG did not support these Ruby conventions.
 The only modifications it made to names was to capitalize the first
 letter of constants (which includes module and class names).</p>
<p>SWIG 1.3.28 introduces the new -autorename command line parameter.
 When this parameter is specified, SWIG will automatically change
 constant, class and method names to conform with the standard Ruby
 naming conventions. For example:</p>
<div class="code shell">
<pre>$ swig -ruby -autorename example.i
</pre>
</div>
<p>To disable renaming use the -noautorename command line option.</p>
<p>Since this change significantly changes the wrapper code generated by
 SWIG, it is turned off by default in SWIG 1.3.28. However, it is
 planned to become the default option in future releases.</p>
<h3><a name="Ruby_nn28">34.4.1 Defining Aliases</a></h3>
<p> It's a fairly common practice in the Ruby built-ins and standard
 library to provide aliases for method names. For example,<em>
 Array#size</em> is an alias for<em> Array#length</em>. If you would
 like to provide an alias for one of your class' instance methods, one
 approach is to use SWIG's <tt>%extend</tt> directive to add a new
 method of the aliased name that calls the original function. For
 example:</p>
<div class="code">
<pre>class MyArray {
public:
  // Construct an empty array
  MyArray();

  // Return the size of this array
  size_t length() const;
};

%extend MyArray {
  // MyArray#size is an alias for MyArray#length
  size_t size() const {
    return $self-&gt;length();
  }
}
 </pre>
</div>
<p> A better solution is to use the <tt>%alias</tt> directive (unique to
 SWIG's Ruby module). The previous example could then be rewritten as:</p>
<div class="code">
<pre>// MyArray#size is an alias for MyArray#length
%alias MyArray::length &quot;size&quot;;

class MyArray {
public:
  // Construct an empty array
  MyArray();
 
  // Return the size of this array
  size_t length() const;
};</pre>
</div>
<p> Multiple aliases can be associated with a method by providing a
 comma-separated list of aliases to the <tt>%alias</tt> directive, e.g.</p>
<div class="code">
<pre>%alias MyArray::length &quot;amount, quantity, size&quot;;</pre>
</div>
<p> From an end-user's standpoint, there's no functional difference
 between these two approaches; i.e. they should get the same result from
 calling either<em> MyArray#size</em> or<em> MyArray#length</em>.
 However, when the <tt>%alias</tt> directive is used, SWIG doesn't need
 to generate all of the wrapper code that's usually associated with
 added methods like our<em> MyArray::size()</em> example.</p>
<p>Note that the <tt>%alias</tt> directive is implemented using SWIG's
 &quot;features&quot; mechanism and so the same name matching rules used for other
 kinds of features apply (see the chapter on <a href="#Customization">
&quot;Customization Features&quot;</a>) for more details).</p>
<h3><a name="Ruby_nn29">34.4.2 Predicate Methods</a></h3>
<p> Ruby methods that return a boolean value and end in a question mark
 are known as predicate methods. Examples of predicate methods in
 standard Ruby classes include<em> Array#empty?</em> (which returns <tt>
true</tt> for an array containing no elements) and<em>
 Object#instance_of?</em> (which returns <tt>true</tt> if the object is
 an instance of the specified class). For consistency with Ruby
 conventions, methods that return boolean values should be marked as
 predicate methods.</p>
<p>One cumbersome solution to this problem is to rename the method
 (using SWIG's <tt>%rename</tt> directive) and provide a custom typemap
 that converts the function's actual return type to Ruby's <tt>true</tt>
 or <tt>false</tt>. For example:</p>
<div class="code">
<pre>%rename(&quot;is_it_safe?&quot;) is_it_safe();

%typemap(out) int is_it_safe &quot;$result = ($1 != 0) ? Qtrue : Qfalse;&quot;;

int is_it_safe();</pre>
</div>
<p> A better solution is to use the <tt>%predicate</tt> directive
 (unique to SWIG's Ruby module) to designate a method as a predicate
 method. For the previous example, this would look like:</p>
<div class="code">
<pre>%predicate is_it_safe();

int is_it_safe();</pre>
</div>
<p>This method would be invoked from Ruby code like this:</p>
<div class="code targetlang">
<pre>irb(main):001:0&gt; <b>Example::is_it_safe?</b>
true</pre>
</div>
<p> The <tt>%predicate</tt> directive is implemented using SWIG's
 &quot;features&quot; mechanism and so the same name matching rules used for other
 kinds of features apply (see the chapter on <a href="#Customization">
&quot;Customization Features&quot;</a>) for more details).</p>
<h3><a name="Ruby_nn30">34.4.3 Bang Methods</a></h3>
<p> Ruby methods that modify an object in-place and end in an
 exclamation mark are known as bang methods. An example of a bang method
 is<em> Array#sort!</em> which changes the ordering of items in an
 array. Contrast this with<em> Array#sort</em>, which returns a copy of
 the array with the items sorted instead of modifying the original
 array. For consistency with Ruby conventions, methods that modify
 objects in place should be marked as bang methods.</p>
<p>Bang methods can be marked using the <tt>%bang</tt> directive which
 is unique to the Ruby module and was introduced in SWIG 1.3.28. For
 example:</p>
<div class="code">
<pre>%bang sort(int arr[]);

int sort(int arr[]); </pre>
</div>
<p>This method would be invoked from Ruby code like this:</p>
<div class="code">
<pre>irb(main):001:0&gt; <b>Example::sort!(arr)</b></pre>
</div>
<p> The <tt>%bang</tt> directive is implemented using SWIG's &quot;features&quot;
 mechanism and so the same name matching rules used for other kinds of
 features apply (see the chapter on <a href="#Customization">
&quot;Customization Features&quot;</a>) for more details).</p>
<h3><a name="Ruby_nn31">34.4.4 Getters and Setters</a></h3>
<p> Often times a C++ library will expose properties through getter and
 setter methods. For example:</p>
<div class="code">
<pre>class Foo {
  Foo() {}
  int getValue() { return value_; }
  void setValue(int value) { value_ = value; }

private:
  int value_;
};</pre>
</div>
<p>By default, SWIG will expose these methods to Ruby as <tt>get_value</tt>
 and <tt>set_value.</tt> However, it more natural for these methods to
 be exposed in Ruby as <tt>value</tt> and <tt>value=.</tt> That allows
 the methods to be used like this:</p>
<div class="code">
<pre>irb(main):001:0&gt; <b>foo = Foo.new()</b>
irb(main):002:0&gt; <b>foo.value = 5</b>
irb(main):003:0&gt; <b>puts foo.value</b></pre>
</div>
<p> This can be done by using the %rename directive:</p>
<div class="code">
<pre>%rename(&quot;value&quot;) Foo::getValue();
%rename(&quot;value=&quot;) Foo::setValue(int value);</pre>
</div>
<h2><a name="Ruby_nn32">34.5 Input and output parameters</a></h2>
<p> A common problem in some C programs is handling parameters passed as
 simple pointers. For example:</p>
<div class="code">
<pre>void add(int x, int y, int *result) {
  *result = x + y;
}</pre>
</div>
<p> or</p>
<div class="code">
<pre>
int sub(int *x, int *y) {
  return *x-*y;
}</pre>
</div>
<p> The easiest way to handle these situations is to use the <tt>
typemaps.i</tt> file. For example:</p>
<div class="code">
<pre>%module Example
%include &quot;typemaps.i&quot;

void add(int, int, int *OUTPUT);
int sub(int *INPUT, int *INPUT);</pre>
</div>
<p>In Ruby, this allows you to pass simple values. For example:</p>
<div class="code targetlang">
<pre>a = Example.add(3, 4)
puts a
7
b = Example.sub(7, 4)
puts b
3</pre>
</div>
<p> Notice how the <tt>INPUT</tt> parameters allow integer values to be
 passed instead of pointers and how the <tt>OUTPUT</tt> parameter
 creates a return result.</p>
<p>If you don't want to use the names <tt>INPUT</tt> or <tt>OUTPUT</tt>,
 use the <tt>%apply</tt> directive. For example:</p>
<div class="code">
<pre>%module Example
%include &quot;typemaps.i&quot;

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

void add(int x, int y, int *result);
int sub(int *x, int *y);</pre>
</div>
<p> If a function mutates one of its parameters like this,</p>
<div class="code">
<pre>void negate(int *x) {
 *x = -(*x);
}</pre>
</div>
<p>you can use <tt>INOUT</tt> like this:</p>
<div class="code">
<pre>%include &quot;typemaps.i&quot;
...
void negate(int *INOUT);</pre>
</div>
<p>In Ruby, a mutated parameter shows up as a return value. For example:</p>
<div class="code targetlang">
<pre>a = Example.negate(3)
print a
-3</pre>
</div>
<p> The most common use of these special typemap rules is to handle
 functions that return more than one value. For example, sometimes a
 function returns a result as well as a special error code:</p>
<div class="code">
<pre>/* send message, return number of bytes sent, success code, and error_code */
int send_message(char *text, int *success, int *error_code);</pre>
</div>
<p> To wrap such a function, simply use the <tt>OUTPUT</tt> rule above.
 For example:</p>
<div class="code">
<pre>%module example
%include &quot;typemaps.i&quot;
...
int send_message(char *, int *OUTPUT, int *OUTPUT);</pre>
</div>
<p> When used in Ruby, the function will return an array of multiple
 values.</p>
<div class="code targetlang">
<pre>bytes, success, error_code = send_message(&quot;Hello World&quot;)
if not success
  print &quot;error #{error_code} : in send_message&quot;
else
  print &quot;Sent&quot;, bytes
end</pre>
</div>
<p> Another way to access multiple return values is to use the <tt>
%apply</tt> rule. In the following example, the parameters rows and
 columns are related to SWIG as <tt>OUTPUT</tt> values through the use
 of <tt>%apply</tt></p>
<div class="code">
<pre>%module Example
%include &quot;typemaps.i&quot;
%apply int *OUTPUT { int *rows, int *columns };
...
void get_dimensions(Matrix *m, int *rows, int*columns);</pre>
</div>
<p>In Ruby:</p>
<div class="code targetlang">
<pre>r, c = Example.get_dimensions(m)</pre>
</div>
<h2><a name="Ruby_nn33">34.6 Exception handling</a></h2>
<h3><a name="Ruby_nn34">34.6.1 Using the %exception directive</a></h3>
<p>The SWIG <tt>%exception</tt> directive can be used to define a
 user-definable exception handler that can convert C/C++ errors into
 Ruby exceptions. The chapter on <a href="#Customization">Customization
 Features</a> contains more details, but suppose you have a C++ class
 like the following :</p>
<div class="code">
<pre>class DoubleArray {
private:
  int n;
  double *ptr;
public:
  // Create a new array of fixed size
  DoubleArray(int size) {
    ptr = new double[size];
    n = size;
  }
 
  // Destroy an array
  ~DoubleArray() {
    delete ptr;
  } 
 
  // Return the length of the array
  int length() {
    return n;
  }
 
  // Get an array item and perform bounds checking.
  double getitem(int i) {
    if ((i &gt;= 0) &amp;&amp; (i &lt; n))
      return ptr[i];
    else
      throw RangeError();
  }
 
  // Set an array item and perform bounds checking.
  void setitem(int i, double val) {
    if ((i &gt;= 0) &amp;&amp; (i &lt; n))
      ptr[i] = val;
    else {
      throw RangeError();
    }
  }
};</pre>
</div>
<p> Since several methods in this class can throw an exception for an
 out-of-bounds access, you might want to catch this in the Ruby
 extension by writing the following in an interface file:</p>
<div class="code">
<pre>%exception {
  try {
    $action
  }
  catch (const RangeError&amp;) {
    static VALUE cpperror = rb_define_class(&quot;CPPError&quot;, rb_eStandardError);
    rb_raise(cpperror, &quot;Range error.&quot;);
  }
}

class DoubleArray {
  ...
};</pre>
</div>
<p> The exception handling code is inserted directly into generated
 wrapper functions. When an exception handler is defined, errors can be
 caught and used to gracefully raise a Ruby exception instead of forcing
 the entire program to terminate with an uncaught error.</p>
<p>As shown, the exception handling code will be added to every wrapper
 function. Because this is somewhat inefficient, you might consider
 refining the exception handler to only apply to specific methods like
 this:</p>
<div class="code">
<pre>%exception getitem {
  try {
    $action
  } catch (const RangeError&amp;) {
    static VALUE cpperror = rb_define_class(&quot;CPPError&quot;, rb_eStandardError);
    rb_raise(cpperror, &quot;Range error in getitem.&quot;);
  }
}
 
%exception setitem {
  try {
    $action
  } catch (const RangeError&amp;) {
    static VALUE cpperror = rb_define_class(&quot;CPPError&quot;, rb_eStandardError);
    rb_raise(cpperror, &quot;Range error in setitem.&quot;);
  }
}</pre>
</div>
<p> In this case, the exception handler is only attached to methods and
 functions named <tt>getitem</tt> and <tt>setitem</tt>.</p>
<p>Since SWIG's exception handling is user-definable, you are not
 limited to C++ exception handling. See the chapter on <a href="#Customization">
Customization Features</a> for more examples.</p>
<h3><a name="Ruby_nn34_2">34.6.2 Handling Ruby Blocks</a></h3>
<p>One of the highlights of Ruby and most of its standard library is the
 use of blocks, which allow the easy creation of continuations and other
 niceties. Blocks in ruby are also often used to simplify the passing of
 many arguments to a class.</p>
<p>In order to make your class constructor support blocks, you can take
 advantage of the %exception directive, which will get run after the C++
 class' constructor was called.</p>
<p>For example, this yields the class over after its construction:</p>
<div class="code">
<pre>class Window
{
public:
  Window(int x, int y, int w, int h);
  // .... other methods here ....
};

// Add support for yielding self in the Class' constructor.
%exception Window::Window {
  $action
  if (rb_block_given_p()) {
    rb_yield(self);
  }
}</pre>
</div>
<p> Then, in ruby, it can be used like:</p>
<div class="targetlang">
<pre>
Window.new(0, 0, 360, 480) { |w|
  w.color = Fltk::RED
  w.border = false
}
</pre>
</div>
<p>For other methods, you can usually use a dummy parameter with a
 special in typemap, like:</p>
<div class="code">
<pre>
//
// original function was:
//
// void func(int x);

%typemap(in, numinputs=0) int RUBY_YIELD_SELF {
  if ( !rb_block_given_p() )
    rb_raise(&quot;No block given&quot;);
  return rb_yield(self);
}

%extend {
  void func(int x, int RUBY_YIELD_SELF );
}
</pre>
</div>
<p>For more information on typemaps, see <a href="#Ruby_nn37">Typemaps</a>
.</p>
<h3><a name="Ruby_nn35">34.6.3 Raising exceptions</a></h3>
<p>There are three ways to raise exceptions from C++ code to Ruby.</p>
<p>The first way is to use <tt>SWIG_exception(int code, const char *msg)</tt>
. The following table shows the mappings from SWIG error codes to Ruby
 exceptions:</p>
<div class="diagram">
<table border="1" class="diagram" summary="Mapping between SWIG error codes and Ruby exceptions."
width="80%"><tbody>
<tr><td class="diagram"><div>SWIG_MemoryError</div></td><td><div>
rb_eNoMemError</div></td></tr>
<tr><td class="diagram"><div>SWIG_IOError</div></td><td><div>rb_eIOError</div>
</td></tr>
<tr><td class="diagram"><div>SWIG_RuntimeError</div></td><td><div>
rb_eRuntimeError</div></td></tr>
<tr><td class="diagram"><div>SWIG_IndexError</div></td><td><div>
rb_eIndexError</div></td></tr>
<tr><td class="diagram"><div>SWIG_TypeError</div></td><td><div>
rb_eTypeError</div></td></tr>
<tr><td class="diagram"><div>SWIG_DivisionByZero</div></td><td><div>
rb_eZeroDivError</div></td></tr>
<tr><td class="diagram"><div>SWIG_OverflowError</div></td><td><div>
rb_eRangeError</div></td></tr>
<tr><td class="diagram"><div>SWIG_SyntaxError</div></td><td><div>
rb_eSyntaxError</div></td></tr>
<tr><td class="diagram"><div>SWIG_ValueError</div></td><td><div>
rb_eArgError</div></td></tr>
<tr><td class="diagram"><div>SWIG_SystemError</div></td><td><div>
rb_eFatal</div></td></tr>
<tr><td class="diagram"><div>SWIG_AttributeError</div></td><td><div>
rb_eRuntimeError</div></td></tr>
<tr><td class="diagram"><div>SWIG_NullReferenceError</div></td><td><div>
rb_eNullReferenceError*</div></td></tr>
<tr><td class="diagram"><div>SWIG_ObjectPreviouslyDeletedError</div></td><td>
<div>rb_eObjectPreviouslyDeleted*</div></td></tr>
<tr><td class="diagram"><div>SWIG_UnknownError</div></td><td><div>
rb_eRuntimeError</div></td></tr>
<tr class="diagram"><td colspan="2"><div>* These error classes are
 created by SWIG and are not built-in Ruby exception classes</div></td></tr>
</tbody></table>
</div>
<p>The second way to raise errors is to use <tt>SWIG_Raise(obj, type,
 desc)</tt>. Obj is a C++ instance of an exception class, type is a
 string specifying the type of exception (for example, &quot;MyError&quot;) and
 desc is the SWIG description of the exception class. For example:</p>
<div class="code">
<pre>
%raise(SWIG_NewPointerObj(e, SWIGTYPE_p_AssertionFailedException, 0), &quot;:AssertionFailedException&quot;, SWIGTYPE_p_AssertionFailedException);
</pre>
</div>
<p>This is useful when you want to pass the current exception object
 directly to Ruby, particularly when the object is an instance of class
 marked as an <tt>%exceptionclass</tt> (see the next section for more
 information).</p>
<p>Last, you can raise an exception by directly calling Ruby's C api.
 This is done by invoking the <tt>rb_raise()</tt> function. The first
 argument passed to <tt>rb_raise()</tt> is the exception type. You can
 raise a custom exception type or one of the built-in Ruby exception
 types.</p>
<h3><a name="Ruby_nn36">34.6.4 Exception classes</a></h3>
<p>Starting with SWIG 1.3.28, the Ruby module supports the <tt>
%exceptionclass</tt> directive, which is used to identify C++ classes
 that are used as exceptions. Classes that are marked with the <tt>
%exceptionclass</tt> directive are exposed in Ruby as child classes of <tt>
rb_eRuntimeError</tt>. This allows C++ exceptions to be directly mapped
 to Ruby exceptions, providing for a more natural integration between
 C++ code and Ruby code.</p>
<div class="code">
<pre>%exceptionclass CustomError;

%inline %{
  class CustomError { };

  class Foo { 
  public:
    void test() { throw CustomError; }
  };
%}</pre>
</div>
<p>From Ruby you can now call this method like this:</p>
<div class="code targetlang">
<pre>foo = Foo.new
begin
  foo.test()
rescue CustomError =&gt; e
  puts &quot;Caught custom error&quot;
end </pre>
</div>
<p>For another example look at swig/Examples/ruby/exception_class.</p>
<h2><a name="Ruby_nn37">34.7 Typemaps</a></h2>
<p> This section describes how you can modify SWIG's default wrapping
 behavior for various C/C++ datatypes using the <tt>%typemap</tt>
 directive. This is an advanced topic that assumes familiarity with the
 Ruby C API as well as the material in the &quot;<a href="#Typemaps">Typemaps</a>
&quot; chapter.</p>
<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 primitive C-Ruby interface.</p>
<h3><a name="Ruby_nn38">34.7.1 What is a typemap?</a></h3>
<p> A typemap is nothing more than a code generation rule that is
 attached to a specific C datatype. The general form of this declaration
 is as follows ( parts enclosed in [...] are optional ):</p>
<div class="code">
<pre>
%typemap( method [, modifiers...] ) typelist code;
</pre>
</div>
<p><em> method</em> is a simply a name that specifies what kind of
 typemap is being defined. It is usually a name like <tt>&quot;in&quot;</tt>, <tt>
&quot;out&quot;</tt>, or <tt>&quot;argout&quot;</tt> (or its director variations). The
 purpose of these methods is described later.</p>
<p><em> modifiers</em> is an optional comma separated list of <tt>
name=&quot;value&quot;</tt> values. These are sometimes to attach extra
 information to a typemap and is often target-language dependent.</p>
<p><em> typelist</em> is a list of the C++ type patterns that the
 typemap will match. The general form of this list is as follows:</p>
<div class="diagram">
<pre>typelist : typepattern [, typepattern, typepattern, ... ] ;

typepattern : type [ (parms) ]
  | type name [ (parms) ]
  | ( typelist ) [ (parms) ]</pre>
</div>
<p> Each type pattern is either a simple type, a simple type and
 argument name, or a list of types in the case of multi-argument
 typemaps. In addition, each type pattern can be parameterized with a
 list of temporary variables (parms). The purpose of these variables
 will be explained shortly.</p>
<p><em>code</em> specifies the C code used in the typemap. It can take
 any one of the following forms:</p>
<div class="diagram">
<pre>code : { ... }
  | &quot; ... &quot;
  | %{ ... %}</pre>
</div>
<p>For example, to convert integers from Ruby to C, you might define a
 typemap like this:</p>
<div class="code">
<pre>%module example

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

%inline %{
  extern int fact(int n);
%}</pre>
</div>
<p> Typemaps are always associated with some specific aspect of code
 generation. In this case, the &quot;in&quot; 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 placeholder for a
 local variable of type <tt>int</tt>. The <tt>$input</tt> variable is
 the input Ruby object.</p>
<p>When this example is compiled into a Ruby module, the following
 sample code:</p>
<div class="code targetlang">
<pre>require 'example'

puts Example.fact(6)</pre>
</div>
<p>prints the result:</p>
<div class="code shell">
<pre>
Received an integer : 6
720
</pre>
</div>
<p> In this example, the typemap is applied to all occurrences of the <tt>
int</tt> datatype. You can refine this by supplying an optional
 parameter name. For example:</p>
<div class="code">
<pre>%module example

%typemap(in) int n {
  $1 = (int) NUM2INT($input);
  printf(&quot;n = %d\n&quot;, $1);
}

%inline %{
  extern int fact(int n);
%}</pre>
</div>
<p> In this case, the typemap code is only attached to arguments that
 exactly match &quot;<tt>int n</tt>&quot;.</p>
<p>The application of a typemap to specific datatypes and argument names
 involves more than simple text-matching--typemaps are fully integrated
 into the SWIG type-system. When you define a typemap for <tt>int</tt>,
 that typemap applies to <tt>int</tt> and qualified variations such as <tt>
const int</tt>. In addition, the typemap system follows <tt>typedef</tt>
 declarations. For example:</p>
<div class="code">
<pre>%typemap(in) int n {
  $1 = (int) NUM2INT($input);
  printf(&quot;n = %d\n&quot;, $1);
}

typedef int Integer;
extern int fact(Integer n); // Above typemap is applied</pre>
</div>
<p> However, the matching of <tt>typedef</tt> only occurs in one
 direction. If you defined a typemap for <tt>Integer</tt>, it is not
 applied to arguments of type <tt>int</tt>.</p>
<p>Typemaps can also be defined for groups of consecutive arguments. For
 example:</p>
<div class="code">
<pre>%typemap(in) (char *str, int len) {
  $1 = StringValuePtr($input);
  $2 = (int) RSTRING($input)-&gt;len;
};

int count(char c, char *str, int len);</pre>
</div>
<p> When a multi-argument typemap is defined, the arguments are always
 handled as a single Ruby object. This allows the function <tt>count</tt>
 to be used as follows (notice how the length parameter is omitted):</p>
<div class="code targetlang">
<pre>puts Example.count('o', 'Hello World')
2</pre>
</div>
<h3><a name="Ruby_Typemap_scope">34.7.2 Typemap scope</a></h3>
<p> Once defined, a typemap remains in effect for all of the
 declarations that follow. A typemap may be redefined for different
 sections of an input file. For example:</p>
<div class="code">
<pre>// typemap1
%typemap(in) int {
  ...
}

int fact(int); // typemap1
int gcd(int x, int y); // typemap1

// typemap2
%typemap(in) int {
  ...
}

int isprime(int); // typemap2</pre>
</div>
<p> One exception to the typemap scoping rules pertains to the <tt>
%extend</tt> declaration. <tt>%extend</tt> is used to attach new
 declarations to a class or structure definition. Because of this, all
 of the declarations in an <tt>%extend</tt> block are subject to the
 typemap rules that are in effect at the point where the class itself is
 defined. For example:</p>
<div class="code">
<pre>class Foo {
  ...
};

%typemap(in) int {
  ...
}

%extend Foo {
  int blah(int x); // typemap has no effect. Declaration is attached to Foo which 
  // appears before the %typemap declaration.
};</pre>
</div>
<h3><a name="Ruby_Copying_a_typemap">34.7.3 Copying a typemap</a></h3>
<p> A typemap is copied by using assignment. For example:</p>
<div class="code">
<pre>%typemap(in) Integer = int;</pre>
</div>
<p> or this:</p>
<div class="code">
<pre>%typemap(in) Integer, Number, int32_t = int;</pre>
</div>
<p> Types are often managed by a collection of different typemaps. For
 example:</p>
<div class="code">
<pre>%typemap(in) int { ... }
%typemap(out) int { ... }
%typemap(varin) int { ... }
%typemap(varout) int { ... }</pre>
</div>
<p> To copy all of these typemaps to a new type, use <tt>%apply</tt>.
 For example:</p>
<div class="code">
<pre>%apply int { Integer }; // Copy all int typemaps to Integer
%apply int { Integer, Number }; // Copy all int typemaps to both Integer and Number</pre>
</div>
<p> The patterns for <tt>%apply</tt> follow the same rules as for <tt>
%typemap</tt>. For example:</p>
<div class="code">
<pre>%apply int *output { Integer *output }; // Typemap with name
%apply (char *buf, int len) { (char *buffer, int size) }; // Multiple arguments</pre>
</div>
<h3><a name="Ruby_Deleting_a_typemap">34.7.4 Deleting a typemap</a></h3>
<p> A typemap can be deleted by simply defining no code. For example:</p>
<div class="code">
<pre>%typemap(in) int; // Clears typemap for int
%typemap(in) int, long, short; // Clears typemap for int, long, short
%typemap(in) int *output; </pre>
</div>
<p> The <tt>%clear</tt> directive clears all typemaps for a given type.
 For example:</p>
<div class="code">
<pre>%clear int; // Removes all types for int
%clear int *output, long *output;</pre>
</div>
<p><b> Note:</b> Since SWIG's default behavior is defined by typemaps,
 clearing a fundamental type like <tt>int</tt> will make that type
 unusable unless you also define a new set of typemaps immediately after
 the clear operation.</p>
<h3><a name="Ruby_Placement_of_typemaps">34.7.5 Placement of typemaps</a>
</h3>
<p> Typemap declarations can be declared in the global scope, within a
 C++ namespace, and within a C++ class. For example:</p>
<div class="code">
<pre>%typemap(in) int {
  ...
}

namespace std {
  class string;
  %typemap(in) string {
    ...
  }
}

class Bar {
public:
  typedef const int &amp; const_reference;
  %typemap(out) const_reference {
    ...
  }
};</pre>
</div>
<p> When a typemap appears inside a namespace or class, it stays in
 effect until the end of the SWIG input (just like before). However, the
 typemap takes the local scope into account. Therefore, this code</p>
<div class="code">
<pre>namespace std {
  class string;
  %typemap(in) string {
    ...
  }
}</pre>
</div>
<p> is really defining a typemap for the type <tt>std::string</tt>. You
 could have code like this:</p>
<div class="code">
<pre>namespace std {
  class string;
  %typemap(in) string { /* std::string */
  ...
  }
}

namespace Foo {
  class string;
  %typemap(in) string { /* Foo::string */
  ...
  }
}</pre>
</div>
<p> In this case, there are two completely distinct typemaps that apply
 to two completely different types (<tt>std::string</tt> and <tt>
Foo::string</tt>).</p>
<p> It should be noted that for scoping to work, SWIG has to know that <tt>
string</tt> is a typename defined within a particular namespace. In this
 example, this is done using the class declaration <tt>class string</tt>
 .</p>
<h3><a name="Ruby_nn39">34.7.6 Ruby typemaps</a></h3>
<p>The following list details all of the typemap methods that can be
 used by the Ruby module:</p>
<h4><a name="Ruby_in_typemap">34.7.6.1 &quot;in&quot; typemap</a></h4>
<p>Converts Ruby objects to input function arguments. For example:</p>
<div class="code">
<pre>%typemap(in) int {
  $1 = NUM2INT($input);
}</pre>
</div>
<p> The following special variables are available:</p>
<div class="diagram">
<table border="1" cellpadding="2" cellspacing="2" summary="Special variables - in typemap"
width="100%"><tbody>
<tr><td>$input</td><td> Input object holding value to be converted.</td></tr>
<tr><td>$symname</td><td> Name of function/method being wrapped</td></tr>
<tr><td>$1...n</td><td> Argument being sent to the function</td></tr>
<tr><td>$1_name</td><td> Name of the argument (if provided)</td></tr>
<tr><td>$1_type</td><td> The actual C datatype matched by the typemap.</td>
</tr>
<tr><td>$1_ltype</td><td> The assignable version of the C datatype
 matched by the typemap.</td></tr>
</tbody></table>
</div>
<p> This is probably the most commonly redefined typemap because it can
 be used to implement customized conversions.</p>
<p> In addition, the &quot;in&quot; typemap allows the number of converted
 arguments to be specified. For example:</p>
<div class="code">
<pre>// Ignored argument.
%typemap(in, numinputs=0) int *out (int temp) {
  $1 = &amp;temp;
}</pre>
</div>
<p> At this time, only zero or one arguments may be converted.</p>
<h4><a name="Ruby_typecheck_typemap">34.7.6.2 &quot;typecheck&quot; typemap</a></h4>
<p> The &quot;typecheck&quot; typemap is used to support overloaded functions and
 methods. It merely checks an argument to see whether or not it matches
 a specific type. For example:</p>
<div class="code">
<pre>%typemap(typecheck, precedence=SWIG_TYPECHECK_INTEGER) int {
  $1 = FIXNUM_P($input) ? 1 : 0;
}</pre>
</div>
<p> For typechecking, the $1 variable is always a simple integer that is
 set to 1 or 0 depending on whether or not the input argument is the
 correct type.</p>
<p> If you define new &quot;in&quot; typemaps<em> and</em> your program uses
 overloaded methods, you should also define a collection of &quot;typecheck&quot;
 typemaps. More details about this follow in a later section on
 &quot;Typemaps and Overloading.&quot;</p>
<h4><a name="Ruby_out_typemap">34.7.6.3 &quot;out&quot; typemap</a></h4>
<p>Converts return value of a C function to a Ruby object.</p>
<div class="code">
<pre>%typemap(out) int {
  $result = INT2NUM( $1 );
}
</pre>
</div>
<p> The following special variables are available.</p>
<div class="diagram">
<table border="1" cellpadding="2" cellspacing="2" summary="Special variables - out typemap"
width="100%"><tbody>
<tr><td>$result</td><td> Result object returned to target language.</td></tr>
<tr><td>$symname</td><td> Name of function/method being wrapped</td></tr>
<tr><td>$1...n</td><td> Argument being wrapped</td></tr>
<tr><td>$1_name</td><td> Name of the argument (if provided)</td></tr>
<tr><td>$1_type</td><td> The actual C datatype matched by the typemap.</td>
</tr>
<tr><td>$1_ltype</td><td> The assignable version of the C datatype
 matched by the typemap.</td></tr>
</tbody></table>
</div>
<h4><a name="Ruby_arginit_typemap">34.7.6.4 &quot;arginit&quot; typemap</a></h4>
<p> The &quot;arginit&quot; typemap is used to set the initial value of a function
 argument--before any conversion has occurred. This is not normally
 necessary, but might be useful in highly specialized applications. For
 example:</p>
<div class="code">
<pre>// Set argument to NULL before any conversion occurs
%typemap(arginit) int *data {
  $1 = NULL;
}</pre>
</div>
<h4><a name="Ruby_default_typemap">34.7.6.5 &quot;default&quot; typemap</a></h4>
<p> The &quot;default&quot; typemap is used to turn an argument into a default
 argument. For example:</p>
<div class="code">
<pre>%typemap(default) int flags {
  $1 = DEFAULT_FLAGS;
}
...
int foo(int x, int y, int flags);</pre>
</div>
<p> The primary use of this typemap is to either change the wrapping of
 default arguments or specify a default argument in a language where
 they aren't supported (like C). Target languages that do not support
 optional arguments, such as Java and C#, effectively ignore the value
 specified by this typemap as all arguments must be given.</p>
<p> Once a default typemap has been applied to an argument, all
 arguments that follow must have default values. See the <a href="#SWIG_default_args">
 Default/optional arguments</a> section for further information on
 default argument wrapping.</p>
<h4><a name="Ruby_check_typemap">34.7.6.6 &quot;check&quot; typemap</a></h4>
<p> The &quot;check&quot; typemap is used to supply value checking code during
 argument conversion. The typemap is applied<em> after</em> arguments
 have been converted. For example:</p>
<div class="code">
<pre>%typemap(check) int positive {
  if ($1 &lt;= 0) {
    SWIG_exception(SWIG_ValueError, &quot;Expected positive value.&quot;);
  }
}</pre>
</div>
<h4><a name="Ruby_argout_typemap_">34.7.6.7 &quot;argout&quot; typemap</a></h4>
<p> The &quot;argout&quot; typemap is used to return values from arguments. This
 is most commonly used to write wrappers for C/C++ functions that need
 to return multiple values. The &quot;argout&quot; typemap is almost always
 combined with an &quot;in&quot; typemap---possibly to ignore the input value. For
 example:</p>
<div class="code">
<pre>/* Set the input argument to point to a temporary variable */
%typemap(in, numinputs=0) int *out (int temp) {
  $1 = &amp;temp;
}

%typemap(argout, fragment=&quot;output_helper&quot;) int *out {
  // Append output value $1 to $result (assuming a single integer in this case)
  $result = output_helper( $result, INT2NUM(*$1) );
}</pre>
</div>
<p> The following special variables are available.</p>
<div class="diagram">
<table border="1" cellpadding="2" cellspacing="2" summary="Special variables - argout typemap"
width="100%"><tbody>
<tr><td>$result</td><td> Result object returned to target language.</td></tr>
<tr><td>$input</td><td> The original input object passed.</td></tr>
<tr><td>$symname</td><td> Name of function/method being wrapped.</td></tr>
</tbody></table>
</div>
<p> The code supplied to the &quot;argout&quot; typemap is always placed after the
 &quot;out&quot; typemap. If multiple return values are used, the extra return
 values are often appended to return value of the function.</p>
<p>Output helper is a fragment that usually defines a macro to some
 function like SWIG_Ruby_AppendOutput.</p>
<p> See the <tt>typemaps.i</tt> library for examples.</p>
<h4><a name="Ruby_freearg_typemap_">34.7.6.8 &quot;freearg&quot; typemap</a></h4>
<p> The &quot;freearg&quot; typemap is used to cleanup argument data. It is only
 used when an argument might have allocated resources that need to be
 cleaned up when the wrapper function exits. The &quot;freearg&quot; typemap
 usually cleans up argument resources allocated by the &quot;in&quot; typemap. For
 example:</p>
<div class="code">
<pre>// Get a list of integers
%typemap(in) int *items {
  int nitems = Length($input); 
  $1 = (int *) malloc(sizeof(int)*nitems);
}
// Free the list 
%typemap(freearg) int *items {
  free($1);
}</pre>
</div>
<p> The &quot;freearg&quot; typemap inserted at the end of the wrapper function,
 just before control is returned back to the target language. This code
 is also placed into a special variable <tt>$cleanup</tt> that may be
 used in other typemaps whenever a wrapper function needs to abort
 prematurely.</p>
<h4><a name="Ruby_newfree_typemap">34.7.6.9 &quot;newfree&quot; typemap</a></h4>
<p> The &quot;newfree&quot; typemap is used in conjunction with the <tt>%newobject</tt>
 directive and is used to deallocate memory used by the return result of
 a function. For example:</p>
<div class="code">
<pre>%typemap(newfree) string * {
  delete $1;
}
%typemap(out) string * {
  $result = PyString_FromString($1-&gt;c_str());
}
...

%newobject foo;
...
string *foo();</pre>
</div>
<p> See <a href="#Customization_ownership">Object ownership and
 %newobject</a> for further details.</p>
<h4><a name="Ruby_memberin_typemap">34.7.6.10 &quot;memberin&quot; typemap</a></h4>
<p> The &quot;memberin&quot; typemap is used to copy data from<em> an already
 converted input value</em> into a structure member. It is typically
 used to handle array members and other special cases. For example:</p>
<div class="code">
<pre>%typemap(memberin) int [4] {
  memmove($1, $input, 4*sizeof(int));
}</pre>
</div>
<p> It is rarely necessary to write &quot;memberin&quot; typemaps---SWIG already
 provides a default implementation for arrays, strings, and other
 objects.</p>
<h4><a name="Ruby_varin_typemap">34.7.6.11 &quot;varin&quot; typemap</a></h4>
<p> The &quot;varin&quot; typemap is used to convert objects in the target
 language to C for the purposes of assigning to a C/C++ global variable.
 This is implementation specific.</p>
<h4><a name="Ruby_varout_typemap_">34.7.6.12 &quot;varout&quot; typemap</a></h4>
<p> The &quot;varout&quot; typemap is used to convert a C/C++ object to an object
 in the target language when reading a C/C++ global variable. This is
 implementation specific.</p>
<h4><a name="Ruby_throws_typemap">34.7.6.13 &quot;throws&quot; typemap</a></h4>
<p> The &quot;throws&quot; typemap is only used when SWIG parses a C++ method with
 an exception specification or has the <tt>%catches</tt> feature
 attached to the method. It provides a default mechanism for handling
 C++ methods that have declared the exceptions they will throw. The
 purpose of this typemap is to convert a C++ exception into an error or
 exception in the target language. It is slightly different to the other
 typemaps as it is based around the exception type rather than the type
 of a parameter or variable. For example:</p>
<div class="code">
<pre>%typemap(throws) const char * %{
  rb_raise(rb_eRuntimeError, $1);
  SWIG_fail;
%}
void bar() throw (const char *);</pre>
</div>
<p> As can be seen from the generated code below, SWIG generates an
 exception handler with the catch block comprising the &quot;throws&quot; typemap
 content.</p>
<div class="code">
<pre>...
try {
  bar();
}
catch(char const *_e) {
  rb_raise(rb_eRuntimeError, _e);
  SWIG_fail;
}
...</pre>
</div>
<p> Note that if your methods do not have an exception specification yet
 they do throw exceptions, SWIG cannot know how to deal with them. For a
 neat way to handle these, see the <a href="#Customization_exception">
Exception handling with %exception</a> section.</p>
<h4><a name="Ruby_directorin_typemap">34.7.6.14 directorin typemap</a></h4>
<p>Converts C++ objects in director member functions to ruby objects. It
 is roughly the opposite of the &quot;in&quot; typemap, making its typemap rule
 often similar to the &quot;out&quot; typemap.</p>
<div class="code">
<pre>
%typemap(directorin) int {
  $result = INT2NUM($1);
}
</pre>
</div>
<p> The following special variables are available.</p>
<div class="diagram">
<table border="1" cellpadding="2" cellspacing="2" summary="Special variables - directorin typemap"
width="100%"><tbody>
<tr><td>$result</td><td> Result object returned to target language.</td></tr>
<tr><td>$symname</td><td> Name of function/method being wrapped</td></tr>
<tr><td>$1...n</td><td> Argument being wrapped</td></tr>
<tr><td>$1_name</td><td> Name of the argument (if provided)</td></tr>
<tr><td>$1_type</td><td> The actual C datatype matched by the typemap.</td>
</tr>
<tr><td>$1_ltype</td><td> The assignable version of the C datatype
 matched by the typemap.</td></tr>
<tr><td>this</td><td> C++ this, referring to the class itself.</td></tr>
</tbody></table>
</div>
<h4><a name="Ruby_directorout_typemap">34.7.6.15 directorout typemap</a></h4>
<p>Converts Ruby objects in director member functions to C++ objects. It
 is roughly the opposite of the &quot;out&quot; typemap, making its rule often
 similar to the &quot;in&quot; typemap.</p>
<div class="code">
<pre>
%typemap(directorout) int {
  $result = NUM2INT($1);
}
</pre>
</div>
<p> The following special variables are available:</p>
<div class="diagram">
<table border="1" cellpadding="2" cellspacing="2" summary="Special variables - directorout typemap"
width="100%"><tbody>
<tr><td>$input</td><td>Ruby object being sent to the function</td></tr>
<tr><td>$symname</td><td>Name of function/method being wrapped</td></tr>
<tr><td>$1...n</td><td>Argument being sent to the function</td></tr>
<tr><td>$1_name</td><td> Name of the argument (if provided)</td></tr>
<tr><td>$1_type</td><td> The actual C datatype matched by the typemap.</td>
</tr>
<tr><td>$1_ltype</td><td> The assignable version of the C datatype
 matched by the typemap.</td></tr>
<tr><td>this</td><td> C++ this, referring to the class itself.</td></tr>
</tbody></table>
</div>
<p>Currently, the directorout nor the out typemap support the option <tt>
numoutputs</tt>, but the Ruby module provides that functionality through
 a %feature directive. Thus, a function can be made to return &quot;nothing&quot;
 if you do:</p>
<div class="code">
<pre>
%feature(&quot;numoutputs&quot;, &quot;0&quot;) MyClass::function;
</pre>
</div>
<p>This feature can be useful if a function returns a status code, which
 you want to discard but still use the typemap to raise an exception.</p>
<h4><a name="Ruby_directorargout_typemap">34.7.6.16 directorargout
 typemap</a></h4>
<p>Output argument processing in director member functions.</p>
<div class="code">
<pre>
%typemap(directorargout,
fragment=&quot;output_helper&quot;) int {
  $result = output_helper( $result, NUM2INT($1) );
}
</pre>
</div>
<p> The following special variables are available:</p>
<div class="diagram">
<table border="1" cellpadding="2" cellspacing="2" style="text-align: left; width: 100%;"
summary="Special variables - directorargout typemap"><tbody>
<tr><td>$result</td><td>Result that the director function returns</td></tr>
<tr><td>$input</td><td>Ruby object being sent to the function</td></tr>
<tr><td>$symname</td><td>name of the function/method being wrapped</td></tr>
<tr><td>$1...n</td><td>Argument being sent to the function</td></tr>
<tr><td>$1_name</td><td>Name of the argument (if provided)</td></tr>
<tr><td>$1_type</td><td>The actual C datatype matched by the typemap</td>
</tr>
<tr><td>$1_ltype</td><td>The assignable version of the C datatype
 matched by the typemap</td></tr>
<tr><td>this</td><td>C++ this, referring to the instance of the class
 itself</td></tr>
</tbody></table>
</div>
<h4><a name="Ruby_ret_typemap">34.7.6.17 ret typemap</a></h4>
<p>Cleanup of function return values</p>
<h4><a name="Ruby_globalin_typemap">34.7.6.18 globalin typemap</a></h4>
<p>Setting of C global variables</p>
<h3><a name="Ruby_nn40">34.7.7 Typemap variables</a></h3>
<p> Within a typemap, a number of special variables prefaced with a <tt>
$</tt> may appear. A full list of variables can be found in the &quot;<a href="#Typemaps">
Typemaps</a>&quot; chapter. This is a list of the most common variables:</p>
<p><tt>$1</tt></p>
<div class="indent">A C local variable corresponding to the actual type
 specified in the <tt>%typemap</tt> directive. For input values, this is
 a C local variable that is supposed to hold an argument value. For
 output values, this is the raw result that is supposed to be returned
 to Ruby.</div>
<p><tt>$input</tt></p>
<div class="indent">A <tt>VALUE</tt> holding a raw Ruby object with an
 argument or variable value.</div>
<p><tt>$result</tt></p>
<div class="indent">A <tt>VALUE</tt> that holds the result to be
 returned to Ruby.</div>
<p><tt>$1_name</tt></p>
<div class="indent">The parameter name that was matched.</div>
<p><tt>$1_type</tt></p>
<div class="indent">The actual C datatype matched by the typemap.</div>
<p><tt>$1_ltype</tt></p>
<div class="indent">An assignable version of the datatype matched by the
 typemap (a type that can appear on the left-hand-side of a C assignment
 operation). This type is stripped of qualifiers and may be an altered
 version of <tt>$1_type</tt>. All arguments and local variables in
 wrapper functions are declared using this type so that their values can
 be properly assigned.</div>
<p><tt>$symname</tt></p>
<div class="indent">The Ruby name of the wrapper function being created.</div>
<h3><a name="Ruby_nn41">34.7.8 Useful Functions</a></h3>
<p> When you write a typemap, you usually have to work directly with
 Ruby objects. The following functions may prove to be useful. (These
 functions plus many more can be found in<em> Programming Ruby</em>
 book, by David Thomas and Andrew Hunt.)</p>
<p>In addition, we list equivalent functions that SWIG defines, which
 provide a language neutral conversion (these functions are defined for
 each swig language supported). If you are trying to create a swig file
 that will work under multiple languages, it is recommended you stick to
 the swig functions instead of the native Ruby functions. That should
 help you avoid having to rewrite a lot of typemaps across multiple
 languages.</p>
<h4><a name="Ruby_nn42">34.7.8.1 C Datatypes to Ruby Objects</a></h4>
<div class="diagram">
<table border="1" cellpadding="2" cellspacing="2" style="width: 100%;" summary="Datatypes">
<tbody>
<tr><th><b>RUBY</b></th><th><b>SWIG</b></th><td></td></tr>
<tr><td>INT2NUM(long or int)</td><td>SWIG_From_int(int x)</td><td> int
 to Fixnum or Bignum</td></tr>
<tr><td>INT2FIX(long or int)</td><td></td><td> int to Fixnum (faster
 than INT2NUM)</td></tr>
<tr><td>CHR2FIX(char)</td><td>SWIG_From_char(char x)</td><td> char to
 Fixnum</td></tr>
<tr><td>rb_str_new2(char*)</td><td>SWIG_FromCharPtrAndSize(char*,
 size_t)</td><td> char* to String</td></tr>
<tr><td>rb_float_new(double)</td><td>SWIG_From_double(double),
<br> SWIG_From_float(float)</td><td>float/double to Float</td></tr>
</tbody></table>
</div>
<h4><a name="Ruby_nn43">34.7.8.2 Ruby Objects to C Datatypes</a></h4>
<p>Here, while the Ruby versions return the value directly, the SWIG
 versions do not, but return a status value to indicate success (<tt>
SWIG_OK</tt>). While more awkward to use, this allows you to write
 typemaps that report more helpful error messages, like:</p>
<div class="code">
<pre>
%typemap(in) size_t (int ok)
  ok = SWIG_AsVal_size_t($input, &amp;$1);
  if (!SWIG_IsOK(ok)) {
    SWIG_exception_fail(SWIG_ArgError(ok), Ruby_Format_TypeError( &quot;$1_name&quot;, &quot;$1_type&quot;, &quot;$symname&quot;, $argnum, $input));
  }
}
</pre>
</div><div class="diagram">
<table border="1" cellpadding="2" cellspacing="2" summary="Ruby objects" width="100%">
<tbody>
<tr><td>int NUM2INT(Numeric)</td><td>SWIG_AsVal_int(VALUE, int*)</td></tr>
<tr><td>int FIX2INT(Numeric)</td><td>SWIG_AsVal_int(VALUE, int*)</td></tr>
<tr><td>unsigned int NUM2UINT(Numeric)</td><td>
SWIG_AsVal_unsigned_SS_int(VALUE, int*)</td></tr>
<tr><td>unsigned int FIX2UINT(Numeric)</td><td>
SWIG_AsVal_unsigned_SS_int(VALUE, int*)</td></tr>
<tr><td>long NUM2LONG(Numeric)</td><td>SWIG_AsVal_long(VALUE, long*)</td>
</tr>
<tr><td>long FIX2LONG(Numeric)</td><td>SWIG_AsVal_long(VALUE, long*)</td>
</tr>
<tr><td>unsigned long FIX2ULONG(Numeric)</td><td>
SWIG_AsVal_unsigned_SS_long(VALUE, unsigned long*)</td></tr>
<tr><td>char NUM2CHR(Numeric or String)</td><td>SWIG_AsVal_char(VALUE,
 int*)</td></tr>
<tr><td>char * StringValuePtr(String)</td><td>
SWIG_AsCharPtrAndSize(VALUE, char*, size_t, int* alloc)</td></tr>
<tr><td>char * rb_str2cstr(String, int*length)</td><td></td></tr>
<tr><td>double NUM2DBL(Numeric)</td><td>(double) SWIG_AsVal_int(VALUE)
 or similar</td></tr>
</tbody></table>
</div>
<h4><a name="Ruby_nn44">34.7.8.3 Macros for VALUE</a></h4>
<p> <tt>RSTRING_LEN(str)</tt></p>
<div class="indent">length of the Ruby string</div>
<p><tt>RSTRING_PTR(str)</tt></p>
<div class="indent">pointer to string storage</div>
<p><tt>RARRAY_LEN(arr)</tt></p>
<div class="indent">length of the Ruby array</div>
<p><tt>RARRAY(arr)-&gt;capa</tt></p>
<div class="indent">capacity of the Ruby array</div>
<p><tt>RARRAY_PTR(arr)</tt></p>
<div class="indent">pointer to array storage</div>
<h4><a name="Ruby_nn45">34.7.8.4 Exceptions</a></h4>
<p> <tt>void rb_raise(VALUE exception, const char *fmt, ...)</tt></p>
<div class="indent"> Raises an exception. The given format string<i> fmt</i>
 and remaining arguments are interpreted as with <tt>printf()</tt>.</div>
<p><tt>void rb_fatal(const char *fmt, ...)</tt></p>
<div class="indent"> Raises a fatal exception, terminating the process.
 No rescue blocks are called, but ensure blocks will be called. The
 given format string<i> fmt</i> and remaining arguments are interpreted
 as with <tt>printf()</tt>.</div>
<p><tt>void rb_bug(const char *fmt, ...)</tt></p>
<div class="indent"> Terminates the process immediately -- no handlers
 of any sort will be called. The given format string<i> fmt</i> and
 remaining arguments are interpreted as with <tt>printf()</tt>. You
 should call this function only if a fatal bug has been exposed.</div>
<p><tt>void rb_sys_fail(const char *msg)</tt></p>
<div class="indent"> Raises a platform-specific exception corresponding
 to the last known system error, with the given string<i> msg</i>.</div>
<p><tt>VALUE rb_rescue(VALUE (*body)(VALUE), VALUE args,
 VALUE(*rescue)(VALUE, VALUE), VALUE rargs)</tt></p>
<div class="indent"> Executes<i> body</i> with the given<i> args</i>. If
 a <tt>StandardError</tt> exception is raised, then execute<i> rescue</i>
 with the given<i> rargs</i>.</div>
<p><tt>VALUE rb_ensure(VALUE(*body)(VALUE), VALUE args,
 VALUE(*ensure)(VALUE), VALUE eargs)</tt></p>
<div class="indent"> Executes<i> body</i> with the given<i> args</i>.
 Whether or not an exception is raised, execute<i> ensure</i> with the
 given<i> rargs</i> after<i> body</i> has completed.</div>
<p><tt>VALUE rb_protect(VALUE (*body)(VALUE), VALUE args, int *result)</tt>
</p>
<div class="indent"> Executes<i> body</i> with the given<i> args</i> and
 returns nonzero in result if any exception was raised.</div>
<p><tt>void rb_notimplement()</tt></p>
<div class="indent"> Raises a <tt>NotImpError</tt> exception to indicate
 that the enclosed function is not implemented yet, or not available on
 this platform.</div>
<p><tt>void rb_exit(int status)</tt></p>
<div class="indent"> Exits Ruby with the given<i> status</i>. Raises a <tt>
SystemExit</tt> exception and calls registered exit functions and
 finalizers.</div>
<p><tt>void rb_warn(const char *fmt, ...)</tt></p>
<div class="indent"> Unconditionally issues a warning message to
 standard error. The given format string<i> fmt</i> and remaining
 arguments are interpreted as with <tt>printf()</tt>.</div>
<p><tt>void rb_warning(const char *fmt, ...)</tt></p>
<div class="indent"> Conditionally issues a warning message to standard
 error if Ruby was invoked with the <tt>-w</tt> flag. The given format
 string<i> fmt</i> and remaining arguments are interpreted as with <tt>
printf()</tt>.</div>
<h4><a name="Ruby_nn46">34.7.8.5 Iterators</a></h4>
<p> <tt>void rb_iter_break()</tt></p>
<div class="indent"> Breaks out of the enclosing iterator block.</div>
<p><tt>VALUE rb_each(VALUE obj)</tt></p>
<div class="indent"> Invokes the <tt>each</tt> method of the given<i>
 obj</i>.</div>
<p><tt>VALUE rb_yield(VALUE arg)</tt></p>
<div class="indent"> Transfers execution to the iterator block in the
 current context, passing<i> arg</i> as an argument. Multiple values may
 be passed in an array.</div>
<p><tt>int rb_block_given_p()</tt></p>
<div class="indent"> Returns <tt>true</tt> if <tt>yield</tt> would
 execute a block in the current context; that is, if a code block was
 passed to the current method and is available to be called.</div>
<p><tt>VALUE rb_iterate(VALUE (*method)(VALUE), VALUE args, VALUE
 (*block)(VALUE, VALUE), VALUE arg2)</tt></p>
<div class="indent"> Invokes<i> method</i> with argument<i> args</i> and
 block<i> block</i>. A <tt>yield</tt> from that method will invoke<i>
 block</i> with the argument given to <tt>yield</tt>, and a second
 argument<i> arg2</i>.</div>
<p><tt>VALUE rb_catch(const char *tag, VALUE (*proc)(VALUE, VALUE),
 VALUE value)</tt></p>
<div class="indent"> Equivalent to Ruby's <tt>catch</tt>.</div>
<p><tt>void rb_throw(const char *tag, VALUE value)</tt></p>
<div class="indent"> Equivalent to Ruby's <tt>throw</tt>.</div>
<h3><a name="Ruby_nn47">34.7.9 Typemap Examples</a></h3>
<p> This section includes a few examples of typemaps. For more examples,
 you might look at the examples in the <tt>Example/ruby</tt> directory.</p>
<h3><a name="Ruby_nn48">34.7.10 Converting a Ruby array to a char **</a></h3>
<p> A common problem in many C programs is the processing of command
 line arguments, which are usually passed in an array of <tt>NULL</tt>
 terminated strings. The following SWIG interface file allows a Ruby
 Array instance to be used as a <tt>char **</tt> object.</p>
<div class="code">
<pre>%module argv

// This tells SWIG to treat char ** as a special case
%typemap(in) char ** {
  /* Get the length of the array */
  int size = RARRAY($input)-&gt;len; 
  int i;
  $1 = (char **) malloc((size+1)*sizeof(char *));
  /* Get the first element in memory */
  VALUE *ptr = RARRAY($input)-&gt;ptr; 
  for (i=0; i &lt; size; i++, ptr++) {
    /* Convert Ruby Object String to char* */
    $1[i]= StringValuePtr(*ptr); 
  }
  $1[i]=NULL; /* End of list */
}

// This cleans up the char ** array created before 
// the function call

%typemap(freearg) char ** {
  free((char *) $1);
}

// Now a test function
%inline %{
int print_args(char **argv) {
  int i = 0;
  while (argv[i]) {
    printf(&quot;argv[%d] = %s\n&quot;, i, argv[i]);
    i++;
  }
  return i;
}
%}</pre>
</div>
<p> When this module is compiled, the wrapped C function now operates as
 follows :</p>
<div class="code targetlang">
<pre>require 'Argv'
Argv.print_args([&quot;Dave&quot;, &quot;Mike&quot;, &quot;Mary&quot;, &quot;Jane&quot;, &quot;John&quot;])
argv[0] = Dave
argv[1] = Mike
argv[2] = Mary
argv[3] = Jane
argv[4] = John</pre>
</div>
<p> In the example, two different typemaps are used. The &quot;in&quot; 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
 &quot;freearg&quot; typemap is used to later release this memory after the
 execution of the C function.</p>
<h3><a name="Ruby_nn49">34.7.11 Collecting arguments in a hash</a></h3>
<p> Ruby's solution to the &quot;keyword arguments&quot; capability of some other
 languages is to allow the programmer to pass in one or more key-value
 pairs as arguments to a function. All of those key-value pairs are
 collected in a single <tt>Hash</tt> argument that's presented to the
 function. If it makes sense, you might want to provide similar
 functionality for your Ruby interface. For example, suppose you'd like
 to wrap this C function that collects information about people's vital
 statistics:</p>
<div class="code">
<pre>void setVitalStats(const char *person, int nattributes, const char **names, int *values);</pre>
</div>
<p> and you'd like to be able to call it from Ruby by passing in an
 arbitrary number of key-value pairs as inputs, e.g.</p>
<div class="code targetlang">
<pre>setVitalStats(&quot;Fred&quot;, 
  'weight' =&gt; 270, 
  'age' =&gt; 42 
)</pre>
</div>
<p> To make this work, you need to write a typemap that expects a Ruby <tt>
Hash</tt> as its input and somehow extracts the last three arguments (<i>
nattributes</i>,<i> names</i> and<i> values</i>) needed by your C
 function. Let's start with the basics:</p>
<div class="code">
<pre>%typemap(in) (int nattributes, const char **names, const int *values)
  (VALUE keys_arr, int i, VALUE key, VALUE val) {
}
 </pre>
</div>
<p> This <tt>%typemap</tt> directive tells SWIG that we want to match
 any function declaration that has the specified types and names of
 arguments somewhere in the argument list. The fact that we specified
 the argument names (<i>nattributes</i>,<i> names</i> and<i> values</i>)
 in our typemap is significant; this ensures that SWIG won't try to
 apply this typemap to<i> other</i> functions it sees that happen to
 have a similar declaration with different argument names. The arguments
 that appear in the second set of parentheses (<i>keys_arr</i>,<i> i</i>
,<i> key</i> and<i> val</i>) define local variables that our typemap
 will need.</p>
<p>Since we expect the input argument to be a <tt>Hash</tt>, let's next
 add a check for that:</p>
<div class="code">
<pre>%typemap(in) (int nattributes, const char **names, const int *values)
  (VALUE keys_arr, int i, VALUE key, VALUE val) {
    <b>Check_Type($input, T_HASH);</b>
}</pre>
</div>
<p> <tt>Check_Type()</tt> is just a macro (defined in the Ruby header
 files) that confirms that the input argument is of the correct type; if
 it isn't, an exception will be raised.</p>
<p>The next task is to determine how many key-value pairs are present in
 the hash; we'll assign this number to the first typemap argument (<tt>
$1</tt>). This is a little tricky since the Ruby/C API doesn't provide a
 public function for querying the size of a hash, but we can get around
 that by calling the hash's<i> size</i> method directly and converting
 its result to a C <tt>int</tt> value:</p>
<div class="code">
<pre>%typemap(in) (int nattributes, const char **names, const int *values)
  (VALUE keys_arr, int i, VALUE key, VALUE val) {
    Check_Type($input, T_HASH);
    <b>$1 = NUM2INT(rb_funcall($input, rb_intern(&quot;size&quot;), 0, Qnil));</b>
}</pre>
</div>
<p> So now we know the number of attributes. Next we need to initialize
 the second and third typemap arguments (i.e. the two C arrays) to <tt>
NULL</tt> and set the stage for extracting the keys and values from the
 hash:</p>
<div class="code">
<pre>%typemap(in) (int nattributes, const char **names, const int *values)
  (VALUE keys_arr, int i, VALUE key, VALUE val) {
    Check_Type($input, T_HASH);
    $1 = NUM2INT(rb_funcall($input, rb_intern(&quot;size&quot;), 0, Qnil));
    <b>$2 = NULL;
    $3 = NULL;
    if ($1 &gt; 0) {
      $2 = (char **) malloc($1*sizeof(char *));
      $3 = (int *) malloc($1*sizeof(int));
    }</b>
}</pre>
</div>
<p> There are a number of ways we could extract the keys and values from
 the input hash, but the simplest approach is to first call the hash's<i>
 keys</i> method (which returns a Ruby array of the keys) and then start
 looping over the elements in that array:</p>
<div class="code">
<pre>%typemap(in) (int nattributes, const char **names, const int *values)
  (VALUE keys_arr, int i, VALUE key, VALUE val) {
    Check_Type($input, T_HASH);
    $1 = NUM2INT(rb_funcall($input, rb_intern(&quot;size&quot;), 0, Qnil));
    $2 = NULL;
    $3 = NULL;
    if ($1 &gt; 0) {
      $2 = (char **) malloc($1*sizeof(char *));
      $3 = (int *) malloc($1*sizeof(int));
      <b>keys_arr = rb_funcall($input, rb_intern(&quot;keys&quot;), 0, Qnil);
      for (i = 0; i &lt; $1; i++) {
      }</b>
    }
}</pre>
</div>
<p> Recall that<i> keys_arr</i> and<i> i</i> are local variables for
 this typemap. For each element in the<i> keys_arr</i> array, we want to
 get the key itself, as well as the value corresponding to that key in
 the hash:</p>
<div class="code">
<pre>%typemap(in) (int nattributes, const char **names, const int *values)
  (VALUE keys_arr, int i, VALUE key, VALUE val) {
    Check_Type($input, T_HASH);
    $1 = NUM2INT(rb_funcall($input, rb_intern(&quot;size&quot;), 0, Qnil));
    $2 = NULL;
    $3 = NULL;
    if ($1 &gt; 0) {
      $2 = (char **) malloc($1*sizeof(char *));
      $3 = (int *) malloc($1*sizeof(int));
      keys_arr = rb_funcall($input, rb_intern(&quot;keys&quot;), 0, Qnil);
      for (i = 0; i &lt; $1; i++) {
        <b>key = rb_ary_entry(keys_arr, i);
        val = rb_hash_aref($input, key);</b>
      }
    }
}</pre>
</div>
<p> To be safe, we should again use the <tt>Check_Type()</tt> macro to
 confirm that the key is a <tt>String</tt> and the value is a <tt>Fixnum</tt>
:</p>
<div class="code">
<pre>%typemap(in) (int nattributes, const char **names, const int *values)
  (VALUE keys_arr, int i, VALUE key, VALUE val) {
    Check_Type($input, T_HASH);
    $1 = NUM2INT(rb_funcall($input, rb_intern(&quot;size&quot;), 0, Qnil));
    $2 = NULL;
    $3 = NULL;
    if ($1 &gt; 0) {
      $2 = (char **) malloc($1*sizeof(char *));
      $3 = (int *) malloc($1*sizeof(int));
      keys_arr = rb_funcall($input, rb_intern(&quot;keys&quot;), 0, Qnil);
      for (i = 0; i &lt; $1; i++) {
        key = rb_ary_entry(keys_arr, i);
        val = rb_hash_aref($input, key);
        <b>Check_Type(key, T_STRING);
        Check_Type(val, T_FIXNUM);</b>
      }
    }
}</pre>
</div>
<p> Finally, we can convert these Ruby objects into their C equivalents
 and store them in our local C arrays:</p>
<div class="code">
<pre>%typemap(in) (int nattributes, const char **names, const int *values)
  (VALUE keys_arr, int i, VALUE key, VALUE val) {
  Check_Type($input, T_HASH);
  $1 = NUM2INT(rb_funcall($input, rb_intern(&quot;size&quot;), 0, Qnil));
  $2 = NULL;
  $3 = NULL;
  if ($1 &gt; 0) {
    $2 = (char **) malloc($1*sizeof(char *));
    $3 = (int *) malloc($1*sizeof(int));
    keys_arr = rb_funcall($input, rb_intern(&quot;keys&quot;), 0, Qnil);
    for (i = 0; i &lt; $1; i++) {
      key = rb_ary_entry(keys_arr, i);
      val = rb_hash_aref($input, key);
      Check_Type(key, T_STRING);
      Check_Type(val, T_FIXNUM);
      <b>$2[i] = StringValuePtr(key);
      $3[i] = NUM2INT(val);</b>
    }
  }
}</pre>
</div>
<p> We're not done yet. Since we used <tt>malloc()</tt> to dynamically
 allocate the memory used for the<i> names</i> and<i> values</i>
 arguments, we need to provide a corresponding &quot;freearg&quot; typemap to free
 that memory so that there is no memory leak. Fortunately, this typemap
 is a lot easier to write:</p>
<div class="code">
<pre>%typemap(freearg) (int nattributes, const char **names, const int *values) {
  free((void *) $2);
  free((void *) $3);
}</pre>
</div>
<p> All of the code for this example, as well as a sample Ruby program
 that uses the extension, can be found in the <tt>Examples/ruby/hashargs</tt>
 directory of the SWIG distribution.</p>
<h3><a name="Ruby_nn50">34.7.12 Pointer handling</a></h3>
<p> Occasionally, it might be necessary to convert pointer values that
 have been stored using the SWIG typed-pointer representation. Since
 there are several ways in which pointers can be represented, the
 following two functions are used to safely perform this conversion:</p>
<p><tt>int SWIG_ConvertPtr(VALUE obj, void **ptr, swig_type_info *ty,
 int flags)</tt></p>
<div class="indent">Converts a Ruby object<i> obj</i> to a C pointer
 whose address is<i> ptr</i> (i.e.<i> ptr</i> is a pointer to a
 pointer). The third argument,<i> ty</i>, is a pointer to a SWIG type
 descriptor structure. If<i> ty</i> is not <tt>NULL</tt>, that type
 information is used to validate type compatibility and other aspects of
 the type conversion. If<i> flags</i> is non-zero, any type errors
 encountered during this validation result in a Ruby <tt>TypeError</tt>
 exception being raised; if<i> flags</i> is zero, such type errors will
 cause <tt>SWIG_ConvertPtr()</tt> to return -1 but not raise an
 exception. If<i> ty</i> is <tt>NULL</tt>, no type-checking is
 performed.</div>
<p> <tt>VALUE SWIG_NewPointerObj(void *ptr, swig_type_info *ty, int own)</tt>
</p>
<div class="indent">Creates a new Ruby pointer object. Here,<i> ptr</i>
 is the pointer to convert,<i> ty</i> is the SWIG type descriptor
 structure that describes the type, and<i> own</i> is a flag that
 indicates whether or not Ruby should take ownership of the pointer
 (i.e. whether Ruby should free this data when the corresponding Ruby
 instance is garbage-collected).</div>
<p> Both of these functions require the use of a special SWIG
 type-descriptor structure. This structure contains information about
 the mangled name of the datatype, type-equivalence information, as well
 as information about converting pointer values under C++ inheritance.
 For a type of <tt>Foo *</tt>, the type descriptor structure is usually
 accessed as follows:</p>
<div class="indent code">
<pre>Foo *foo;
SWIG_ConvertPtr($input, (void **) &amp;foo, SWIGTYPE_p_Foo, 1);

VALUE obj;
obj = SWIG_NewPointerObj(f, SWIGTYPE_p_Foo, 0);</pre>
</div>
<p> In a typemap, the type descriptor should always be accessed using
 the special typemap variable <tt>$1_descriptor</tt>. For example:</p>
<div class="indent code">
<pre>%typemap(in) Foo * {
  SWIG_ConvertPtr($input, (void **) &amp;$1, $1_descriptor, 1);
}</pre>
</div>
<h4><a name="Ruby_nn51">34.7.12.1 Ruby Datatype Wrapping</a></h4>
<p> <tt>VALUE Data_Wrap_Struct(VALUE class, void (*mark)(void *), void
 (*free)(void *), void *ptr)</tt></p>
<div class="indent">Given a pointer<i> ptr</i> to some C data, and the
 two garbage collection routines for this data (<i>mark</i> and<i> free</i>
), return a <tt>VALUE</tt> for the Ruby object.</div>
<p><tt>VALUE Data_Make_Struct(VALUE class,<i> c-type</i>, void
 (*mark)(void *), void (*free)(void *),<i> c-type</i> *ptr)</tt></p>
<div class="indent">Allocates a new instance of a C data type<i> c-type</i>
, assigns it to the pointer<i> ptr</i>, then wraps that pointer with <tt>
Data_Wrap_Struct()</tt> as above.</div>
<p><tt>Data_Get_Struct(VALUE obj,<i> c-type</i>,<i> c-type</i> *ptr)</tt>
</p>
<div class="indent">Retrieves the original C pointer of type<i> c-type</i>
 from the data object<i> obj</i> and assigns that pointer to<i> ptr</i>.</div>
<h3><a name="Ruby_nn52">34.7.13 Example: STL Vector to Ruby Array</a></h3>
<p>Another use for macros and type maps is to create a Ruby array from a
 STL vector of pointers. In essence, copy of all the pointers in the
 vector into a Ruby array. The use of the macro is to make the typemap
 so generic that any vector with pointers can use the type map. The
 following is an example of how to construct this type of macro/typemap
 and should give insight into constructing similar typemaps for other
 STL structures:</p>
<div class="code">
<pre>%define PTR_VECTOR_TO_RUBY_ARRAY(vectorclassname, classname)
%typemap(out) vectorclassname &amp;, const vectorclassname &amp; {
  VALUE arr = rb_ary_new2($1-&gt;size());
  vectorclassname::iterator i = $1-&gt;begin(), iend = $1-&gt;end();
  for ( ; i!=iend; i++ )
    rb_ary_push(arr, Data_Wrap_Struct(c ## classname.klass, 0, 0, *i));
  $result = arr;
}
%typemap(out) vectorclassname, const vectorclassname {
  VALUE arr = rb_ary_new2($1.size());
  vectorclassname::iterator i = $1.begin(), iend = $1.end();
  for ( ; i!=iend; i++ )
    rb_ary_push(arr, Data_Wrap_Struct(c ## classname.klass, 0, 0, *i));
  $result = arr;
}
%enddef</pre>
</div>
<p> Note, that the &quot;<tt>c ## classname.klass&quot;</tt> is used in the
 preprocessor step to determine the actual object from the class name.</p>
<p>To use the macro with a class Foo, the following is used:</p>
<div class="code">
<pre>PTR_VECTOR_TO_RUBY_ARRAY(vector&lt;foo *=&quot;&quot;&gt;, Foo)</pre>
</div>
<p> It is also possible to create a STL vector of Ruby objects:</p>
<div class="code">
<pre>%define RUBY_ARRAY_TO_PTR_VECTOR(vectorclassname, classname)
%typemap(in) vectorclassname &amp;, const vectorclassname &amp; {
  Check_Type($input, T_ARRAY);
  vectorclassname *vec = new vectorclassname;
  int len = RARRAY($input)-&gt;len;
  for (int i=0; i!=len; i++) {
    VALUE inst = rb_ary_entry($input, i);
    //The following _should_ work but doesn't on HPUX
    // Check_Type(inst, T_DATA);
    classname *element = NULL;
    Data_Get_Struct(inst, classname, element);
    vec-&gt;push_back(element);
  }
  $1 = vec;
}

%typemap(freearg) vectorclassname &amp;, const vectorclassname &amp; {
  delete $1;
}
%enddef</pre>
</div>
<p> It is also possible to create a Ruby array from a vector of static
 data types:</p>
<div class="code">
<pre>%define VECTOR_TO_RUBY_ARRAY(vectorclassname, classname)
%typemap(out) vectorclassname &amp;, const vectorclassname &amp; {
  VALUE arr = rb_ary_new2($1-&gt;size()); 
  vectorclassname::iterator i = $1-&gt;begin(), iend = $1-&gt;end();
  for ( ; i!=iend; i++ )
    rb_ary_push(arr, Data_Wrap_Struct(c ## classname.klass, 0, 0, &amp;(*i)));
  $result = arr;
}
%typemap(out) vectorclassname, const vectorclassname {
  VALUE arr = rb_ary_new2($1.size()); 
  vectorclassname::iterator i = $1.begin(), iend = $1.end();
  for ( ; i!=iend; i++ )
    rb_ary_push(arr, Data_Wrap_Struct(c ## classname.klass, 0, 0, &amp;(*i)));
  $result = arr;
}
%enddef</pre>
</div> Note that this is mostly an example of typemaps. If you want to
 use the STL with ruby, you are advised to use the standard swig STL
 library, which does much more than this. Refer to the section called
 the<a href="#Ruby_nn23_1"> C++ Standard Template Library</a>.
<h2><a name="Ruby_nn65">34.8 Docstring Features</a></h2>
<p> Using ri and rdoc web pages in Ruby libraries is a common practice.
 Given the way that SWIG generates the extensions by default, your users
 will normally not get any documentation for it, even if they run 'rdoc'
 on the resulting .c or .cxx file.</p>
<p>The features described in this section make it easy for you to add
 rdoc strings to your modules, functions and methods that can then be
 read by Ruby's rdoc tool to generate html web pages, ri documentation,
 Windows chm file and an .xml description.</p>
<p>rdoc can then be run from a console or shell window on a swig
 generated file.</p>
<p>For example, to generate html web pages from a C++ file, you'd do:</p>
<div class="code shell">
<pre>
$ rdoc -E cxx=c -f html file_wrap.cxx
</pre>
</div>
<p>To generate ri documentation from a c wrap file, you could do:</p>
<div class="code shell">
<pre>
$ rdoc -r file_wrap.c
</pre>
</div>
<h3><a name="Ruby_nn66">34.8.1 Module docstring</a></h3>
<p> Ruby allows a docstring at the beginning of the file before any
 other statements, and it is typically used to give a general
 description of the entire module. SWIG supports this by setting an
 option of the <tt>%module</tt> directive. For example:</p>
<div class="code">
<pre>%module(docstring=&quot;This is the example module's docstring&quot;) example</pre>
</div>
<p> When you have more than just a line or so then you can retain the
 easy readability of the <tt>%module</tt> directive by using a macro.
 For example:</p>
<div class="code">
<pre>%define DOCSTRING
&quot;The `XmlResource` class allows program resources defining menus, 
layout of controls on a panel, etc. to be loaded from an XML file.&quot;
%enddef

%module(docstring=DOCSTRING) xrc</pre>
</div>
<h3><a name="Ruby_nn67">34.8.2 %feature(&quot;autodoc&quot;)</a></h3>
<p>Since SWIG does know everything about the function it wraps, it is
 possible to generate an rdoc containing the parameter types, names and
 default values. Since Ruby ships with one of the best documentation
 systems of any language, it makes sense to take advantage of it.</p>
<p>SWIG's Ruby module provides support for the &quot;autodoc&quot; feature, which
 when attached to a node in the parse tree will cause an rdoc comment to
 be generated in the wrapper file that includes the name of the
 function, parameter names, default values if any, and return type if
 any. There are also several options for autodoc controlled by the value
 given to the feature, described below.</p>
<h4><a name="Ruby_nn68">34.8.2.1 %feature(&quot;autodoc&quot;, &quot;0&quot;)</a></h4>
<p> When the &quot;0&quot; option is given then the types of the parameters will<em>
 not</em> be included in the autodoc string. For example, given this
 function prototype:</p>
<div class="code">
<pre>%feature(&quot;autodoc&quot;, &quot;0&quot;);
bool function_name(int x, int y, Foo* foo=NULL, Bar* bar=NULL);</pre>
</div>
<p> Then Ruby code like this will be generated:</p>
<div class="targetlang">
<pre>function_name(x, y, foo=nil, bar=nil) -&gt; bool
  ...</pre>
</div>
<h4><a name="Ruby_autodoc1">34.8.2.2 %feature(&quot;autodoc&quot;, &quot;1&quot;)</a></h4>
<p> When the &quot;1&quot; option is used then the parameter types<em> will</em>
 be used in the rdoc string. In addition, an attempt is made to simplify
 the type name such that it makes more sense to the Ruby user. Pointer,
 reference and const info is removed, <tt>%rename</tt>'s are evaluated,
 etc. (This is not always successful, but works most of the time. See
 the next section for what to do when it doesn't.) Given the example
 above, then turning on the parameter types with the &quot;1&quot; option will
 result in rdoc code like this:</p>
<div class="targetlang">
<pre>function_name(int x, int y, Foo foo=nil, Bar bar=nil) -&gt; bool
  ...</pre>
</div>
<h4><a name="Ruby_autodoc2">34.8.2.3 %feature(&quot;autodoc&quot;, &quot;2&quot;)</a></h4>
<p> When the &quot;2&quot; option is used then the parameter types will not be
 used in the rdoc string. However, they will be listed in full after the
 function. Given the example above, then turning on the parameter types
 with the &quot;2&quot; option will result in Ruby code like this:</p>
<h4><a name="Ruby_feature_autodoc3">34.8.2.4 %feature(&quot;autodoc&quot;, &quot;3&quot;)</a>
</h4>
<p> When the &quot;3&quot; option is used then the function will be documented
 using a combination of &quot;1&quot; and &quot;2&quot; above. Given the example above, then
 turning on the parameter types with the &quot;2&quot; option will result in Ruby
 code like this:</p>
<div class="targetlang">
<pre>function_name(int x, int y, Foo foo=nil, Bar bar=nil) -&gt; bool

Parameters:
        x - int
        y - int
        foo - Foo
        bar - Bar</pre>
</div>
<h4><a name="Ruby_nn70">34.8.2.5 %feature(&quot;autodoc&quot;, &quot;docstring&quot;)</a></h4>
<p> Finally, there are times when the automatically generated autodoc
 string will make no sense for a Ruby programmer, particularly when a
 typemap is involved. So if you give an explicit value for the autodoc
 feature then that string will be used in place of the automatically
 generated string. For example:</p>
<div class="code">
<pre>%feature(&quot;autodoc&quot;, &quot;GetPosition() -&gt; (x, y)&quot;) GetPosition;
void GetPosition(int* OUTPUT, int* OUTPUT);</pre>
</div>
<h3><a name="Ruby_nn71">34.8.3 %feature(&quot;docstring&quot;)</a></h3>
<p> In addition to the autodoc strings described above, you can also
 attach any arbitrary descriptive text to a node in the parse tree with
 the &quot;docstring&quot; feature. When the proxy module is generated then any
 docstring associated with classes, function or methods are output. If
 an item already has an autodoc string then it is combined with the
 docstring and they are output together.</p>
<h2><a name="Ruby_nn53">34.9 Advanced Topics</a></h2>
<h3><a name="Ruby_operator_overloading">34.9.1 Operator overloading</a></h3>
<p> SWIG allows operator overloading with, by using the <tt>%extend</tt>
 or <tt>%rename</tt> commands in SWIG and the following operator names
 (derived from Python):</p>
<div class="code diagram">
<table border="1" cellpadding="2" cellspacing="2" style="width: 100%; font-family: monospace;"
summary="operator names"><tbody>
<tr><td><b> General</b></td></tr>
<tr><td>__repr__</td><td> inspect</td></tr>
<tr><td>__str__</td><td> to_s</td></tr>
<tr><td>__cmp__</td><td> &lt;=&gt;</td></tr>
<tr><td>__hash__</td><td> hash</td></tr>
<tr><td>__nonzero__</td><td> nonzero?</td></tr>
<tr><td></td></tr>
<tr><td><b> Callable</b></td></tr>
<tr><td>__call__</td><td> call</td></tr>
<tr><td></td></tr>
<tr><td><b> Collection</b></td></tr>
<tr><td>__len__</td><td> length</td></tr>
<tr><td>__getitem__</td><td> []</td></tr>
<tr><td>__setitem__</td><td> []=</td></tr>
<tr><td></td></tr>
<tr><td><b> Numeric</b></td></tr>
<tr><td>__add__</td><td> +</td></tr>
<tr><td>__sub__</td><td> -</td><td></td></tr>
<tr><td>__mul__</td><td> *</td></tr>
<tr><td>__div__</td><td> /</td></tr>
<tr><td>__mod__</td><td> %</td></tr>
<tr><td>__divmod__</td><td> divmod</td></tr>
<tr><td>__pow__</td><td> **</td></tr>
<tr><td>__lshift__</td><td> &lt;&lt;</td></tr>
<tr><td>__rshift__</td><td> &gt;&gt;</td></tr>
<tr><td>__and__</td><td> &amp;</td></tr>
<tr><td>__xor__</td><td> ^</td></tr>
<tr><td>__or__</td><td> |</td></tr>
<tr><td>__neg__</td><td> -@</td><td></td></tr>
<tr><td>__pos__</td><td> +@</td></tr>
<tr><td>__abs__</td><td> abs</td></tr>
<tr><td>__invert__</td><td> ~</td></tr>
<tr><td>__int__</td><td> to_i</td></tr>
<tr><td>__float__</td><td> to_f</td></tr>
<tr><td>__coerce__</td><td> coerce</td></tr>
<tr><td></td></tr>
<tr><td><b>Additions in 1.3.13</b></td></tr>
<tr><td>__lt__</td><td> &lt;</td></tr>
<tr><td>__le__</td><td> &lt;=</td></tr>
<tr><td>__eq__</td><td> ==</td></tr>
<tr><td>__gt__</td><td> &gt;</td></tr>
<tr><td>__ge__</td><td> &gt;=</td></tr>
</tbody></table>
</div>
<p> Note that although SWIG supports the <tt>__eq__</tt> magic method
 name for defining an equivalence operator, there is no separate method
 for handling<i> inequality</i> since Ruby parses the expression<i> a !=
 b</i> as<i> !(a == b)</i>.</p>
<h3><a name="Ruby_nn55">34.9.2 Creating Multi-Module Packages</a></h3>
<p> The chapter on <a href="#Modules">Working with Modules</a> discusses
 the basics of creating multi-module extensions with SWIG, and in
 particular the considerations for sharing runtime type information
 among the different modules.</p>
<p>As an example, consider one module's interface file (<tt>shape.i</tt>
) that defines our base class:</p>
<div class="code">
<pre>%module shape

%{
#include &quot;Shape.h&quot;
%}

class Shape {
protected:
  double xpos;
  double ypos;
protected:
  Shape(double x, double y);
public:
  double getX() const;
  double getY() const;
};</pre>
</div>
<p> We also have a separate interface file (<tt>circle.i</tt>) that
 defines a derived class:</p>
<div class="code">
<pre>%module circle

%{
#include &quot;Shape.h&quot;
#include &quot;Circle.h&quot;
%}

// Import the base class definition from Shape module
%import shape.i

class Circle : public Shape {
protected:
  double radius;
public:
  Circle(double x, double y, double r);
  double getRadius() const;
};</pre>
</div>
<p> We'll start by building the<b> Shape</b> extension module:</p>
<div class="code shell">
<pre>$ swig -c++ -ruby shape.i
</pre>
</div>
<p> SWIG generates a wrapper file named <tt>shape_wrap.cxx</tt>. To
 compile this into a dynamically loadable extension for Ruby, prepare an
 <tt>extconf.rb</tt> script using this template:</p>
<div class="code targetlang">
<pre>require 'mkmf'

# Since the SWIG runtime support library for Ruby
# depends on the Ruby library, make sure it's in the list
# of libraries.
$libs = append_library($libs, Config::CONFIG['RUBY_INSTALL_NAME'])

# Create the makefile
create_makefile('shape')</pre>
</div>
<p> Run this script to create a <tt>Makefile</tt> and then type <tt>make</tt>
 to build the shared library:</p>
<div class="code targetlang">
<pre>$ <b>ruby extconf.rb</b>
creating Makefile
$ <b>make</b>
g++ -fPIC -g -O2 -I. -I/usr/include/ruby-2.1.0 \
-I. -c shape_wrap.cxx
gcc -shared -L/usr/local/lib -o shape.so shape_wrap.o -L. \
-lruby -lruby -lc</pre>
</div>
<p> Note that depending on your installation, the outputs may be
 slightly different; these outputs are those for a Linux-based
 development environment. The end result should be a shared library
 (here, <tt>shape.so</tt>) containing the extension module code. Now
 repeat this process in a separate directory for the<b> Circle</b>
 module:</p>
<ol>
<li> Run SWIG to generate the wrapper code (<tt>circle_wrap.cxx</tt>);</li>
<li> Write an <tt>extconf.rb</tt> script that your end-users can use to
 create a platform-specific <tt>Makefile</tt> for the extension;</li>
<li> Build the shared library for this extension by typing <tt>make</tt>
.</li>
</ol>
<p> Once you've built both of these extension modules, you can test them
 interactively in IRB to confirm that the <tt>Shape</tt> and <tt>Circle</tt>
 modules are properly loaded and initialized:</p>
<div class="code targetlang">
<pre>$ <b>irb</b>
irb(main):001:0&gt; <b>require 'shape'</b>
true
irb(main):002:0&gt; <b>require 'circle'</b>
true
irb(main):003:0&gt; <b>c = Circle::Circle.new(5, 5, 20)</b>
#&lt;Circle::Circle:0xa097208&gt;
irb(main):004:0&gt; <b>c.kind_of? Shape::Shape</b>
true
irb(main):005:0&gt; <b>c.getX()</b>
5.0</pre>
</div>
<h3><a name="Ruby_nn56">34.9.3 Specifying Mixin Modules</a></h3>
<p> The Ruby language doesn't support multiple inheritance, but it does
 allow you to mix one or more modules into a class using Ruby's <tt>
include</tt> method. For example, if you have a Ruby class that defines
 an<em> each</em> instance method, e.g.</p>
<div class="code targetlang">
<pre>class Set
  def initialize
  @members = []
  end
 
  def each
  @members.each { |m| yield m }
  end
end</pre>
</div>
<p> then you can mix-in Ruby's <tt>Enumerable</tt> module to easily add
 a lot of functionality to your class:</p>
<div class="code targetlang">
<pre>class Set
  <b>include Enumerable</b>
  def initialize
    @members = []
  end
  def each
    @members.each { |m| yield m }
  end
end</pre>
</div>
<p> To get the same benefit for your SWIG-wrapped classes, you can use
 the <tt>%mixin</tt> directive to specify the names of one or more
 modules that should be mixed-in to a class. For the above example, the
 SWIG interface specification might look like this:</p>
<div class="code">
<pre>%mixin Set &quot;Enumerable&quot;;

class Set {
public:
  // Constructor
  Set();
 
  // Iterates through set members
  void each();
};</pre>
</div>
<p> Multiple modules can be mixed into a class by providing a
 comma-separated list of module names to the <tt>%mixin</tt> directive,
 e.g.</p>
<div class="code">
<pre>%mixin Set &quot;Fee, Fi, Fo, Fum&quot;;</pre>
</div>
<p> Note that the <tt>%mixin</tt> directive is implemented using SWIG's
 &quot;features&quot; mechanism and so the same name matching rules used for other
 kinds of features apply (see the chapter on <a href="#Customization">
&quot;Customization Features&quot;</a>) for more details).</p>
<h2><a name="Ruby_nn57">34.10 Memory Management</a></h2>
<p>One of the most common issues in generating SWIG bindings for Ruby is
 proper memory management. The key to proper memory management is
 clearly defining whether a wrapper Ruby object owns the underlying C
 struct or C++ class. There are two possibilities:</p>
<ul>
<li> The Ruby object is responsible for freeing the C struct or C++
 object</li>
<li> The Ruby object should not free the C struct or C++ object because
 it will be freed by the underlying C or C++ code</li>
</ul>
<p>To complicate matters, object ownership may transfer from Ruby to C++
 (or vice versa) depending on what function or methods are invoked.
 Clearly, developing a SWIG wrapper requires a thorough understanding of
 how the underlying library manages memory.</p>
<h3><a name="Ruby_nn58">34.10.1 Mark and Sweep Garbage Collector</a></h3>
<p>Ruby uses a mark and sweep garbage collector. When the garbage
 collector runs, it finds all the &quot;root&quot; objects, including local
 variables, global variables, global constants, hardware registers and
 the C stack. For each root object, the garbage collector sets its mark
 flag to true and calls <tt>rb_gc_mark</tt> on the object. The job of <tt>
rb_gc_mark</tt> is to recursively mark all the objects that a Ruby
 object has a reference to (ignoring those objects that have already
 been marked). Those objects, in turn, may reference other objects. This
 process will continue until all active objects have been &quot;marked.&quot;
 After the mark phase comes the sweep phase. In the sweep phase, all
 objects that have not been marked will be garbage collected.</p>
<p>The Ruby C/API provides extension developers two hooks into the
 garbage collector - a &quot;mark&quot; function and a &quot;sweep&quot; function. By
 default these functions are set to NULL.</p>
<p>If a C struct or C++ class references any other Ruby objects, then it
 must provide a &quot;mark&quot; function. The &quot;mark&quot; function should identify any
 referenced Ruby objects by calling the rb_gc_mark function for each
 one. Unsurprisingly, this function will be called by the Ruby garbage
 during the &quot;mark&quot; phase.</p>
<p>During the sweep phase, Ruby destroys any unused objects. If any
 memory has been allocated in creating the underlying C struct or C++
 struct, then a &quot;free&quot; function must be defined that deallocates this
 memory.</p>
<h3><a name="Ruby_nn59">34.10.2 Object Ownership</a></h3>
<p>As described above, memory management depends on clearly defining who
 is responsible for freeing the underlying C struct or C++ class. If the
 Ruby object is responsible for freeing the C++ object, then a &quot;free&quot;
 function must be registered for the object. If the Ruby object is not
 responsible for freeing the underlying memory, then a &quot;free&quot; function
 must not be registered for the object.</p>
<p>For the most part, SWIG takes care of memory management issues. The
 rules it uses are:</p>
<ul>
<li> When calling a C++ object's constructor from Ruby, SWIG will assign
 a &quot;free&quot; function thereby making the Ruby object responsible for
 freeing the C++ object</li>
<li> When calling a C++ member function that returns a pointer, SWIG
 will not assign a &quot;free&quot; function thereby making the underlying library
 responsible for freeing the object.</li>
</ul>
<p>To make this clearer, let's look at an example. Assume we have a Foo
 and a Bar class.</p>
<div class="code">
<pre>/* File &quot;RubyOwernshipExample.h&quot; */

class Foo
{
public:
  Foo() {}
  ~Foo() {}
};

class Bar
{
  Foo *foo_;
public:
  Bar(): foo_(new Foo) {}
  ~Bar() { delete foo_; }
  Foo* get_foo() { return foo_; }
  Foo* get_new_foo() { return new Foo; }
  void set_foo(Foo *foo) { delete foo_; foo_ = foo; }
};</pre>
</div>
<p>First, consider this Ruby code:</p>
<div class="code targetlang">
<pre>foo = Foo.new</pre>
</div>
<p>In this case, the Ruby code calls the underlying <tt>Foo</tt> C++
 constructor, thus creating a new <tt>foo</tt> object. By default, SWIG
 will assign the new Ruby object a &quot;free&quot; function. When the Ruby object
 is garbage collected, the &quot;free&quot; function will be called. It in turn
 will call <tt>Foo</tt>'s destructor.</p>
<p>Next, consider this code:</p>
<div class="code targetlang">
<pre>bar = Bar.new
foo = bar.get_foo()</pre>
</div>
<p>In this case, the Ruby code calls a C++ member function, <tt>get_foo</tt>
. By default, SWIG will not assign the Ruby object a &quot;free&quot; function.
 Thus, when the Ruby object is garbage collected the underlying C++ <tt>
foo</tt> object is not affected.</p>
<p>Unfortunately, the real world is not as simple as the examples above.
 For example:</p>
<div class="code targetlang">
<pre>bar = Bar.new
foo = bar.get_new_foo()</pre>
</div>
<p>In this case, the default SWIG behavior for calling member functions
 is incorrect. The Ruby object should assume ownership of the returned
 object. This can be done by using the %newobject directive. See <a href="#Customization_ownership">
 Object ownership and %newobject</a> for more information.</p>
<p>The SWIG default mappings are also incorrect in this case:</p>
<div class="code targetlang">
<pre>foo = Foo.new
bar = Bar.new
bar.set_foo(foo)</pre>
</div>
<p>Without modification, this code will cause a segmentation fault. When
 the Ruby <tt>foo</tt> object goes out of scope, it will free the
 underlying C++ <tt>foo</tt> object. However, when the Ruby bar object
 goes out of scope, it will call the C++ bar destructor which will also
 free the C++ <tt>foo</tt> object. The problem is that object ownership
 is transferred from the Ruby object to the C++ object when the <tt>
set_foo</tt> method is called. This can be done by using the special
 DISOWN type map, which was added to the Ruby bindings in SWIG-1.3.26.</p>
<p>Thus, a correct SWIG interface file correct mapping for these classes
 is:</p>
<div class="code">
<pre>/* File RubyOwnershipExample.i */

%module RubyOwnershipExample

%{
#include &quot;RubyOwnershipExample.h&quot;
%}

class Foo
{
public:
  Foo();
  ~Foo();
};

class Bar
{
  Foo *foo_;
public:
  Bar();
  ~Bar();
  Foo* get_foo();

<b>  %newobject get_new_foo;</b>
  Foo* get_new_foo();

<b>  %apply SWIGTYPE *DISOWN {Foo *foo};</b>
  void set_foo(Foo *foo);
<b>  %clear Foo *foo;</b>
};
</pre>
</div>
<p> This code can be seen in swig/examples/ruby/tracking.</p>
<h3><a name="Ruby_nn60">34.10.3 Object Tracking</a></h3>
<p>The remaining parts of this section will use the class library shown
 below to illustrate different memory management techniques. The class
 library models a zoo and the animals it contains.</p>
<div class="code">
<pre>%module zoo

%{
#include &lt;string&gt;
#include &lt;vector&gt;

#include &quot;zoo.h&quot;
%}

class Animal
{
private:
  typedef std::vector&lt;Animal*&gt; AnimalsType;
  typedef AnimalsType::iterator IterType;
protected:
  AnimalsType animals;
protected:
  std::string name_;
public:
  // Construct an animal with this name
  Animal(const char* name) : name_(name) {}
 
  // Return the animal's name
  const char* get_name() const { return name.c_str(); }
};

class Zoo
{
protected:
 std::vector&lt;Animal *&gt; animals;
 
public:
  // Construct an empty zoo
  Zoo() {}
  
  /* Create a new animal. */
  static Animal* Zoo::create_animal(const char* name) {
    return new Animal(name);
  }
 
  // Add a new animal to the zoo
  void add_animal(Animal* animal) {
    animals.push_back(animal); 
  }
 
  Animal* remove_animal(size_t i) {
    Animal* result = this-&gt;animals[i];
    IterType iter = this-&gt;animals.begin();
    std::advance(iter, i);
    this-&gt;animals.erase(iter);
   
    return result;
  }
  
  // Return the number of animals in the zoo
  size_t get_num_animals() const {
    return animals.size(); 
  }
  
  // Return a pointer to the ith animal
  Animal* get_animal(size_t i) const {
    return animals[i]; 
  }
};</pre>
</div>
<p>Let's say you SWIG this code and then run IRB:</p>
<div class="code targetlang">
<pre>$ <b>irb</b>
irb(main):001:0&gt; <b>require 'example'</b>
=&gt; true

irb(main):002:0&gt; <b>tiger1 = Example::Animal.new(&quot;tiger1&quot;)</b>
=&gt; #&lt;Example::Animal:0x2be3820&gt;

irb(main):004:0&gt; <b>tiger1.get_name()</b>
=&gt; &quot;tiger1&quot;

irb(main):003:0&gt; <b>zoo = Example::Zoo.new()</b>
=&gt; #&lt;Example::Zoo:0x2be0a60&gt;

irb(main):006:0&gt; <b>zoo.add_animal(tiger)</b>
=&gt; nil

irb(main):007:0&gt; <b>zoo.get_num_animals()</b>
=&gt; 1

irb(main):007:0&gt; <b>tiger2 = zoo.remove_animal(0)</b>
=&gt; #&lt;Example::Animal:0x2bd4a18&gt;

irb(main):008:0&gt; <b>tiger2.get_name()</b>
=&gt; &quot;tiger1&quot;

irb(main):009:0&gt; <b>tiger1.equal?(tiger2)</b>
=&gt; false
</pre>
</div>
<p>Pay particular attention to the code <tt>tiger1.equal?(tiger2)</tt>.
 Note that the two Ruby objects are not the same - but they reference
 the same underlying C++ object. This can cause problems. For example:</p>
<div class="code targetlang">
<pre>irb(main):010:0&gt; <b>tiger1 = nil</b>
=&gt; nil

irb(main):011:0&gt; <b>GC.start</b>
=&gt; nil

irb(main):012:0&gt; <b>tiger2.get_name()</b>
(irb):12: [BUG] Segmentation fault
</pre>
</div>
<p>After the garbage collector runs, as a result of our call to <tt>
GC.start</tt>, calling<tt>tiger2.get_name()</tt> causes a segmentation
 fault. The problem is that when <tt>tiger1</tt> is garbage collected,
 it frees the underlying C++ object. Thus, when <tt>tiger2</tt> calls
 the <tt>get_name()</tt> method it invokes it on a destroyed object.</p>
<p>This problem can be avoided if SWIG enforces a one-to-one mapping
 between Ruby objects and C++ classes. This can be done via the use of
 the <tt>%trackobjects</tt> functionality available in SWIG-1.3.26. and
 later.</p>
<p>When the <tt>%trackobjects</tt> is turned on, SWIG automatically
 keeps track of mappings between C++ objects and Ruby objects. Note that
 enabling object tracking causes a slight performance degradation. Test
 results show this degradation to be about 3% to 5% when creating and
 destroying 100,000 animals in a row.</p>
<p>Since <tt>%trackobjects</tt> is implemented as a <tt>%feature</tt>,
 it uses the same name matching rules as other kinds of features (see
 the chapter on <a href="#Customization"> &quot;Customization Features&quot;</a>)
 . Thus it can be applied on a class-by-class basis if needed. To fix
 the example above:</p>
<div class="code">
<pre>%module example

%{
#include &quot;example.h&quot;
%}

<b>/* Tell SWIG that create_animal creates a new object */</b>
<b>%newobject Zoo::create_animal;</b>

<b>/* Tell SWIG to keep track of mappings between C/C++ structs/classes. */</b>
<b>%trackobjects;</b>

%include &quot;example.h&quot;</pre>
</div>
<p>When this code runs we see:</p>
<div class="code targetlang">
<pre>$ <b>irb</b>
irb(main):001:0&gt; <b>require 'example'</b>
=&gt; true

irb(main):002:0&gt; <b>tiger1 = Example::Animal.new(&quot;tiger1&quot;)</b>
=&gt; #&lt;Example::Animal:0x2be37d8&gt;

irb(main):003:0&gt; <b>zoo = Example::Zoo.new()</b>
=&gt; #&lt;Example::Zoo:0x2be0a18&gt;

irb(main):004:0&gt; <b>zoo.add_animal(tiger1)</b>
=&gt; nil

irb(main):006:0&gt; <b>tiger2 = zoo.remove_animal(0)</b>
=&gt; #&lt;Example::Animal:0x2be37d8&gt;

irb(main):007:0&gt; <b>tiger1.equal?(tiger2)</b>
=&gt; true

irb(main):008:0&gt; <b>tiger1 = nil</b>
=&gt; nil

irb(main):009:0&gt; <b>GC.start</b>
=&gt; nil

irb(main):010:0&gt; <b>tiger.get_name()</b>
=&gt; &quot;tiger1&quot;
irb(main):011:0&gt;</pre>
</div>
<p>For those who are interested, object tracking is implemented by
 storing Ruby objects in a hash table and keying them on C++ pointers.
 The underlying API is:</p>
<div class="code">
<pre>static void SWIG_RubyAddTracking(void* ptr, VALUE object);
static VALUE SWIG_RubyInstanceFor(void* ptr) ;
static void SWIG_RubyRemoveTracking(void* ptr);
static void SWIG_RubyUnlinkObjects(void* ptr);</pre>
</div>
<p>When an object is created, SWIG will automatically call the <tt>
SWIG_RubyAddTracking</tt> method. Similarly, when an object is deleted,
 SWIG will call the <tt>SWIG_RubyRemoveTracking</tt>. When an object is
 returned to Ruby from C++, SWIG will use the <tt>SWIG_RubyInstanceFor</tt>
 method to ensure a one-to-one mapping from Ruby to C++ objects. Last,
 the <tt>RubyUnlinkObjects</tt> method unlinks a Ruby object from its
 underlying C++ object.</p>
<p>In general, you will only need to use the <tt>SWIG_RubyInstanceFor</tt>
, which is required for implementing mark functions as shown below.
 However, if you implement your own free functions (see below) you may
 also have to call the <tt>SWIG_RubyRemoveTracking</tt> and <tt>
RubyUnlinkObjects</tt> methods.</p>
<h3><a name="Ruby_nn61">34.10.4 Mark Functions</a></h3>
<p>With a bit more testing, we see that our class library still has
 problems. For example:</p>
<div class="targetlang">
<pre>$ <b>irb</b>
irb(main):001:0&gt; <b>require 'example'</b>
=&gt; true

irb(main):002:0&gt; tiger1 = <b>Example::Animal.new(&quot;tiger1&quot;)</b>
=&gt; #&lt;Example::Animal:0x2bea6a8&gt;

irb(main):003:0&gt; zoo = <b>Example::Zoo.new()</b>
=&gt; #&lt;Example::Zoo:0x2be7960&gt;

irb(main):004:0&gt; <b>zoo.add_animal(tiger1)</b>
=&gt; nil

irb(main):007:0&gt; <b>tiger1 = nil</b>
=&gt; nil

irb(main):007:0&gt; <b>GC.start</b>
=&gt; nil

irb(main):005:0&gt; <b>tiger2 = zoo.get_animal(0)</b>
(irb):12: [BUG] Segmentation fault</pre>
</div>
<p>The problem is that Ruby does not know that the <tt>zoo</tt> object
 contains a reference to a Ruby object. Thus, when Ruby garbage collects
 <tt>tiger1</tt> it frees the underlying C++ object.</p>
<p>This can be fixed by implementing a <tt>mark</tt> function as
 described above in the <a href="#Ruby_nn52">Mark and Sweep Garbage
 Collector</a> section. You can specify a mark function by using the <tt>
%markfunc</tt> directive. Since the <tt>%markfunc</tt> directive is
 implemented using SWIG's' &quot;features&quot; mechanism it uses the same name
 matching rules as other kinds of features (see the chapter on <a href="#Customization">
&quot;Customization Features&quot;</a> for more details).</p>
<p>A <tt>mark</tt> function takes a single argument, which is a pointer
 to the C++ object being marked; it should, in turn, call <tt>
rb_gc_mark()</tt> for any instances that are reachable from the current
 object. The mark function for our <tt>Zoo</tt> class should therefore
 loop over all of the C++ animal objects in the zoo object, look up
 their Ruby object equivalent, and then call <tt>rb_gc_mark()</tt>. One
 possible implementation is:</p>
<div class="code">
<pre>%module example

%{
#include &quot;example.h&quot;
%}

/* Keep track of mappings between C/C++ structs/classes
 and Ruby objects so we can implement a mark function. */
<b>%trackobjects;</b>

/* Specify the mark function */
<b>%markfunc Zoo &quot;mark_Zoo&quot;;</b>

%include &quot;example.h&quot;

%header %{

static void mark_Zoo(void* ptr) {
  Zoo* zoo = (Zoo*) ptr;
 
  /* Loop over each object and tell the garbage collector
  that we are holding a reference to them. */
  int count = zoo-&gt;get_num_animals();
 
  for(int i = 0; i &lt; count; ++i) {
    Animal* animal = zoo-&gt;get_animal(i);
    VALUE object = SWIG_RubyInstanceFor(animal);
 
    if (object != Qnil) {
      rb_gc_mark(object);
    }
  }
}
%}</pre>
</div>
<p> Note the <tt>mark</tt> function is dependent on the <tt>
SWIG_RUBY_InstanceFor</tt> method, and thus requires that <tt>
%trackobjects</tt> is enabled. For more information, please refer to the
 ruby_track_objects.i test case in the SWIG test suite.</p>
<p>When this code is compiled we now see:</p>
<div class="targetlang">
<pre>$ <b>irb
</b>irb(main):002:0&gt; <b>tiger1=Example::Animal.new(&quot;tiger1&quot;)</b>
=&gt; #&lt;Example::Animal:0x2be3bf8&gt;

irb(main):003:0&gt; <b>Example::Zoo.new()</b>
=&gt; #&lt;Example::Zoo:0x2be1780&gt;

irb(main):004:0&gt; <b>zoo = Example::Zoo.new()</b>
=&gt; #&lt;Example::Zoo:0x2bde9c0&gt;

irb(main):005:0&gt; <b>zoo.add_animal(tiger1)</b>
=&gt; nil

irb(main):009:0&gt; <b>tiger1 = nil</b>
=&gt; nil

irb(main):010:0&gt; <b>GC.start</b>
=&gt; nil
irb(main):014:0&gt; <b>tiger2 = zoo.get_animal(0)</b>
=&gt; #&lt;Example::Animal:0x2be3bf8&gt;

irb(main):015:0&gt; <b>tiger2.get_name()</b>
=&gt; &quot;tiger1&quot;
irb(main):016:0&gt;</pre>
</div>
<p>This code can be seen in swig/examples/ruby/mark_function.</p>
<h3><a name="Ruby_nn62">34.10.5 Free Functions</a></h3>
<p>By default, SWIG creates a &quot;free&quot; function that is called when a Ruby
 object is garbage collected. The free function simply calls the C++
 object's destructor.</p>
<p>However, sometimes an appropriate destructor does not exist or
 special processing needs to be performed before the destructor is
 called. Therefore, SWIG allows you to manually specify a &quot;free&quot;
 function via the use of the <tt>%freefunc</tt> directive. The <tt>
%freefunc</tt> directive is implemented using SWIG's' &quot;features&quot;
 mechanism and so the same name matching rules used for other kinds of
 features apply (see the chapter on <a href="#Customization">
&quot;Customization Features&quot;</a>) for more details).</p>
<p>IMPORTANT ! - If you define your own free function, then you must
 ensure that you call the underlying C++ object's destructor. In
 addition, if object tracking is activated for the object's class, you
 must also call the <tt>SWIG_RubyRemoveTracking</tt> function (of course
 call this before you destroy the C++ object). Note that it is harmless
 to call this method if object tracking if off so it is advised to
 always call it.</p>
<p>Note there is a subtle interaction between object ownership and free
 functions. A custom defined free function will only be called if the
 Ruby object owns the underlying C++ object. This also to Ruby objects
 which are created, but then transfer ownership to C++ objects via the
 use of the <tt>disown</tt> typemap described above.</p>
<p>To show how to use the <tt>%freefunc</tt> directive, let's slightly
 change our example. Assume that the zoo object is responsible for
 freeing any animal that it contains. This means that the <tt>
Zoo::add_animal</tt> function should be marked with a <tt>DISOWN</tt>
 typemap and the destructor should be updated as below:</p>
<div class="code">
<pre>
Zoo::~Zoo() {
  IterType iter = this-&gt;animals.begin();
  IterType end = this-&gt;animals.end();
 
  for(iter; iter != end; ++iter) {
    Animal* animal = *iter;
    delete animal;
  }
}
</pre>
</div>
<p>When we use these objects in IRB we see:</p>
<div class="code targetlang">
<pre class="targetlang"><b>$irb</b>
irb(main):002:0&gt; <b>require 'example'</b>
=&gt; true

irb(main):003:0&gt; <b>zoo = Example::Zoo.new()</b>
=&gt; #&lt;Example::Zoo:0x2be0fe8&gt;

irb(main):005:0&gt; <b>tiger1 = Example::Animal.new(&quot;tiger1&quot;)</b>
=&gt; #&lt;Example::Animal:0x2bda760&gt;

irb(main):006:0&gt; <b>zoo.add_animal(tiger1)</b>
=&gt; nil

irb(main):007:0&gt; <b>zoo = nil</b>
=&gt; nil

irb(main):008:0&gt; <b>GC.start</b>
=&gt; nil

irb(main):009:0&gt; <b>tiger1.get_name()</b>
(irb):12: [BUG] Segmentation fault
</pre>
</div>
<p>The error happens because the C++ <tt>animal</tt> object is freed
 when the <tt>zoo</tt> object is freed. Although this error is
 unavoidable, we can at least prevent the segmentation fault. To do this
 requires enabling object tracking and implementing a custom free
 function that calls the <tt>SWIG_RubyUnlinkObjects</tt> function for
 each animal object that is destroyed. The <tt>SWIG_RubyUnlinkObjects</tt>
 function notifies SWIG that a Ruby object's underlying C++ object is no
 longer valid. Once notified, SWIG will intercept any calls from the
 existing Ruby object to the destroyed C++ object and raise an
 exception.</p>
<div class="code">
<pre>%module example

%{
#include &quot;example.h&quot;
%}

/* Specify that ownership is transferred to the zoo when calling add_animal */
%apply SWIGTYPE *DISOWN { Animal* animal };

/* Track objects */
%trackobjects;

/* Specify the mark function */
%freefunc Zoo &quot;free_Zoo&quot;;

%include &quot;example.h&quot;

%header %{
  static void free_Zoo(void* ptr) {
    Zoo* zoo = (Zoo*) ptr;

    /* Loop over each animal */
    int count = zoo-&gt;get_num_animals();

    for(int i = 0; i &lt; count; ++i) {
      /* Get an animal */
      Animal* animal = zoo-&gt;get_animal(i);

      /* Unlink the Ruby object from the C++ object */
      SWIG_RubyUnlinkObjects(animal);

      /* Now remove the tracking for this animal */
      SWIG_RubyRemoveTracking(animal);
    }

    /* Now call SWIG_RubyRemoveTracking for the zoo */
    SWIG_RubyRemoveTracking(ptr);
    /* Now free the zoo which will free the animals it contains */
    delete zoo;
  }
%} </pre>
</div>
<p>Now when we use these objects in IRB we see:</p>
<div class="code targetlang">
<pre><b>$irb</b>
irb(main):002:0&gt; <b>require 'example'</b>
=&gt; true

irb(main):003:0&gt; <b>zoo = Example::Zoo.new()</b>
=&gt; #&lt;Example::Zoo:0x2be0fe8&gt;

irb(main):005:0&gt; <b>tiger1 = Example::Animal.new(&quot;tiger1&quot;)</b>
=&gt; #&lt;Example::Animal:0x2bda760&gt;

irb(main):006:0&gt; <b>zoo.add_animal(tiger1)</b>
=&gt; nil

irb(main):007:0&gt; <b>zoo = nil</b>
=&gt; nil

irb(main):008:0&gt; <b>GC.start</b>
=&gt; nil

irb(main):009:0&gt; <b>tiger1.get_name()</b>
RuntimeError: This Animal * already released
 from (irb):10:in `get_name'
 from (irb):10
irb(main):011:0&gt;</pre>
</div>
<p>Notice that SWIG can now detect the underlying C++ object has been
 freed, and thus raises a runtime exception.</p>
<p>This code can be seen in swig/examples/ruby/free_function.</p>
<h3><a name="Ruby_nn63">34.10.6 Embedded Ruby and the C++ Stack</a></h3>
<p>As has been said, the Ruby GC runs and marks objects before its sweep
 phase. When the garbage collector is called, it will also try to mark
 any Ruby objects (VALUE) it finds in the machine registers and in the
 C++ stack.</p>
<p>The stack is basically the history of the functions that have been
 called and also contains local variables, such as the ones you define
 whenever you do inside a function:</p>
<div class="diagram">VALUE obj;</div>
<p>For ruby to determine where its stack space begins, during
 initialization a normal Ruby interpreter will call the ruby_init()
 function which in turn will call a function called Init_stack or
 similar. This function will store a pointer to the location where the
 stack points at that point in time.</p>
<p>ruby_init() is presumed to always be called within the main()
 function of your program and whenever the GC is called, ruby will
 assume that the memory between the current location in memory and the
 pointer that was stored previously represents the stack, which may
 contain local (and temporary) VALUE ruby objects. Ruby will then be
 careful not to remove any of those objects in that location.</p>
<p>So far so good. For a normal Ruby session, all the above is
 completely transparent and magic to the extensions developer.</p>
<p>However, with an embedded Ruby, it may not always be possible to
 modify main() to make sure ruby_init() is called there. As such,
 ruby_init() will likely end up being called from within some other
 function. This can lead Ruby to measure incorrectly where the stack
 begins and can result in Ruby incorrectly collecting those temporary
 VALUE objects that are created once another function is called. The end
 result: random crashes and segmentation faults.</p>
<p>This problem will often be seen in director functions that are used
 for callbacks, for example.</p>
<p>To solve the problem, SWIG can now generate code with director
 functions containing the optional macros SWIG_INIT_STACK and
 SWIG_RELEASE_STACK. These macros will try to force Ruby to reinitialize
 the beginning of the stack the first time a director function is
 called. This will lead Ruby to measure and not collect any VALUE
 objects defined from that point on.</p>
<p>To mark functions to either reset the ruby stack or not, you can use:</p>
<div class="code">
<pre>
%initstack Class::memberfunction;   // only re-init the stack in this director method
%ignorestack Class::memberfunction; // do not re-init the stack in this director method
%initstack Class;                   // init the stack on all the methods of this class
%initstack;                         // all director functions will re-init the stack
</pre>
</div><HR NOSHADE>
<h1><a name="Scilab">35 SWIG and Scilab</a></h1>

<!-- INDEX -->
<div class="sectiontoc">
<ul>
<li><a href="#Scilab_preliminaries">Preliminaries</a></li>
<li><a href="#Scilab_running_swig">Running SWIG</a>
<ul>
<li><a href="#Scilab_running_swig_generating_module">Generating the
 module</a></li>
<li><a href="#Scilab_running_swig_building_module">Building the module</a>
</li>
<li><a href="#Scilab_running_swig_loading_module">Loading the module</a></li>
<li><a href="#Scilab_running_swig_using_module">Using the module</a></li>
<li><a href="#Scilab_running_swig_options">Scilab command line options</a>
</li>
</ul>
</li>
<li><a href="#Scilab_wrapping">A basic tour of C/C++ wrapping</a>
<ul>
<li><a href="#Scilab_wrapping_overview">Overview</a></li>
<li><a href="#Scilab_wrapping_identifiers">Identifiers</a></li>
<li><a href="#Scilab_wrapping_functions">Functions</a>
<ul>
<li><a href="#Scilab_nn13">Argument passing</a></li>
<li><a href="#Scilab_nn14">Multiple output arguments</a></li>
</ul>
</li>
<li><a href="#Scilab_wrapping_global_variables">Global variables</a></li>
<li><a href="#Scilab_wrapping_constants_and_enums">Constants and
 enumerations</a>
<ul>
<li><a href="#Scilab_wrapping_constants">Constants</a></li>
<li><a href="#Scilab_wrapping_enums">Enumerations</a></li>
</ul>
</li>
<li><a href="#Scilab_wrapping_pointers">Pointers</a>
<ul>
<li><a href="#Scilab_wrapping_pointers_utility_functions">Utility
 functions</a></li>
<li><a href="#Scilab_wrapping_pointers_null_pointers">Null pointers:</a></li>
</ul>
</li>
<li><a href="#Scilab_wrapping_structs">Structures</a></li>
<li><a href="#Scilab_wrapping_cpp_classes">C++ classes</a></li>
<li><a href="#Scilab_wrapping_cpp_inheritance">C++ inheritance</a></li>
<li><a href="#Scilab_wrapping_cpp_overloading">C++ overloading</a></li>
<li><a href="#Scilab_wrapping_pointers_references_values_arrays">
Pointers, references, values, and arrays</a></li>
<li><a href="#Scilab_wrapping_cpp_templates">C++ templates</a></li>
<li><a href="#Scilab_wrapping_cpp_operators">C++ operators</a></li>
<li><a href="#Scilab_wrapping_cpp_namespaces">C++ namespaces</a></li>
<li><a href="#Scilab_wrapping_cpp_exceptions">C++ exceptions</a></li>
<li><a href="#Scilab_wrapping_cpp_stl">C++ STL</a></li>
</ul>
</li>
<li><a href="#Scilab_typemaps">Type mappings and libraries</a>
<ul>
<li><a href="#Scilab_typemaps_primitive_types">Default primitive type
 mappings</a></li>
<li><a href="#Scilab_typemaps_arrays">Arrays</a></li>
<li><a href="#Scilab_typemaps_pointer-to-pointers">Pointer-to-pointers</a>
</li>
<li><a href="#Scilab_typemaps_matrices">Matrices</a></li>
<li><a href="#Scilab_typemaps_stl">STL</a></li>
</ul>
</li>
<li><a href="#Scilab_module_initialization">Module initialization</a></li>
<li><a href="#Scilab_building_modes">Building modes</a>
<ul>
<li><a href="#Scilab_building_modes_nobuilder_mode">No-builder mode</a></li>
<li><a href="#Scilab_building_modes_builder_mode">Builder mode</a></li>
</ul>
</li>
<li><a href="#Scilab_generated_scripts">Generated scripts</a>
<ul>
<li><a href="#Scilab_generated_scripts_builder_script">Builder script</a>
</li>
<li><a href="#Scilab_generated_scripts_loader_script">Loader script</a></li>
</ul>
</li>
<li><a href="#Scilab_other_resources">Other resources</a></li>
</ul>
</div>
<!-- INDEX -->
<p> Scilab is a scientific software package for numerical computations
 providing a powerful open computing environment for engineering and
 scientific applications that is mostly compatible with MATLAB. More
 information can be found at <a href="http://www.scilab.org">
www.scilab.org</a>.</p>
<p> This chapter explains how to use SWIG for Scilab. After this
 introduction, you should be able to generate with SWIG a Scilab
 external module from a C/C++ library.</p>
<h2><a name="Scilab_preliminaries">35.1 Preliminaries</a></h2>
<p> SWIG for Scilab supports Linux. Other operating systems haven't been
 tested.</p>
<p> Scilab is supported from version 5.3.3 onwards. The forthcoming
 version 6, as of January 2015, is also supported.</p>
<p> SWIG for Scilab supports C language. C++ is partially supported. See
 <a href="#Scilab_wrapping">A basic tour of C/C++ wrapping</a> for
 further details.</p>
<h2><a name="Scilab_running_swig">35.2 Running SWIG</a></h2>
<p> Let's see how to use SWIG for Scilab on a small example.
<br> In this example we bind from C a function and a global variable
 into Scilab. The SWIG interface (stored in a file named <tt>example.i</tt>
), is the following:</p>
<div class="code">
<pre>
%module example

%inline %{
double Foo = 3.0;

int fact(int n) {
  if (n &lt; 0) {
    return 0;
  }
  else if (n == 0) {
    return 1;
  }
  else {
    return n * fact(n-1);
  }
}
%}
</pre>
</div>
<p> Note: a code in an <tt>%inline</tt> section is both parsed and
 wrapped by SWIG, and inserted as is in the wrapper source file.</p>
<h3><a name="Scilab_running_swig_generating_module">35.2.1 Generating
 the module</a></h3>
<p> The module is generated using the <tt>swig</tt> executable and its <tt>
-scilab</tt> option.</p>
<div class="shell">
<pre>
$ swig -scilab example.i
</pre>
</div>
<p> This command generates two files:</p>
<ul>
<li><tt>example_wrap.c</tt>: a C source file containing the wrapping
 code and also here the wrapped code (the <tt>fact()</tt> and <tt>Foo</tt>
 definitions)</li>
<li><tt>loader.sce</tt>: a Scilab script used to load the module into
 Scilab</li>
</ul>
<p> Note: if the following error is returned:</p>
<div class="shell">
<pre>
:1: Error: Unable to find 'swig.swg'
:3: Error: Unable to find 'scilab.swg'
</pre>
</div>
<p> it may be because the SWIG library is not found. Check the <tt>
SWIG_LIB</tt> environment variable or your SWIG installation.</p>
<p> Note: SWIG for Scilab can work in two modes related to the way the
 module is built, see the <a href="#Scilab_building_modes">Building
 modes</a> section for details. This example uses the <tt>builder</tt>
 mode.</p>
<p> The <tt>swig</tt> executable has several other command line options
 you can use. See <a href="#Scilab_running_swig_options">Scilab command
 line options</a> for further details.</p>
<h3><a name="Scilab_running_swig_building_module">35.2.2 Building the
 module</a></h3>
<p> To be loaded in Scilab, the wrapper has to be built into a dynamic
 module (or shared library).</p>
<p> The commands to compile and link the wrapper (with <tt>gcc</tt>)
 into the shared library <tt>libexample.so</tt> are:</p>
<div class="shell">
<pre>
$ gcc -fPIC -c -I/usr/local/include/scilab example_wrap.c
$ gcc -shared example_wrap.o -o libexample.so
</pre>
</div>
<p> Note: we supposed in this example that the path to the Scilab
 include directory is <tt>/usr/local/include/scilab</tt> (which is the
 case in a Debian environment), this should be changed for another
 environment.</p>
<h3><a name="Scilab_running_swig_loading_module">35.2.3 Loading the
 module</a></h3>
<p> Loading a module is done by running the loader script in Scilab:</p>
<div class="targetlang">
<pre>
--&gt; exec loader.sce
</pre>
</div>
<p> Scilab should output the following messages:</p>
<div class="targetlang">
<pre>
Shared archive loaded.
Link done.
</pre>
</div>
<p> which means that Scilab has successfully loaded the shared library.
 The module functions and other symbols are now available in Scilab.</p>
<h3><a name="Scilab_running_swig_using_module">35.2.4 Using the module</a>
</h3>
<p> In Scilab, the function <tt>fact()</tt> is simply called as
 following:</p>
<div class="targetlang">
<pre>
--&gt; fact(5)
ans  =

    120.
</pre>
</div>
<p>For the <tt>Foo</tt> global variable, the accessors need to be used:<div
class="targetlang">
<pre>
--&gt; Foo_get
ans  =

    3.

--&gt; Foo_set(4);

--&gt; Foo_get
ans  =

    4.
</pre>
</div></p>
<p> Note: for conciseness, we assume in the subsequent Scilab code
 examples that the modules have been beforehand built and loaded in
 Scilab.</p>
<h3><a name="Scilab_running_swig_options">35.2.5 Scilab command line
 options</a></h3>
<p> The following table lists the Scilab specific command line options
 in addition to the generic SWIG options:</p>
<table summary="Scilab specific options">
<tr><td><tt>-builder</tt></td><td>Generate the Scilab builder script</td>
</tr>
<tr><td><tt>-buildercflags &lt;cflags&gt;</tt></td><td>Add &lt;cflags&gt; to the
 builder compiler flags</td></tr>
<tr><td><tt>-builderldflags &lt;ldflags&gt;</tt></td><td>Add &lt;ldlags&gt; to the
 builder linker flags</td></tr>
<tr><td><tt>-buildersources &lt;files&gt;</tt></td><td>Add the (comma
 separated) files &lt;files&gt; to the builder sources</td></tr>
<tr><td><tt>-builderverbositylevel &lt;level&gt;</tt></td><td>Set the build
 verbosity level to &lt;level&gt; (default 0: off, 2: high)</td></tr>
<tr><td><tt>-builderflagscript &lt;file&gt;</tt></td><td>Use the Scilab script
 &lt;file&gt; to configure the compiler and linker flags</td></tr>
<tr><td><tt>-gatewayxml &lt;gateway_id&gt;</tt></td><td>Generate the gateway
 XML with the given &lt;gateway_id&gt;</td></tr>
<tr><td><tt>-targetversion</tt></td><td>Generate for Scilab target
 (major) version</td></tr>
</table>
<p> These options can be displayed with:</p>
<div class="shell">
<pre>
$ swig -scilab -help
</pre>
</div>
<h2><a name="Scilab_wrapping">35.3 A basic tour of C/C++ wrapping</a></h2>
<h3><a name="Scilab_wrapping_overview">35.3.1 Overview</a></h3>
<p> SWIG for Scilab provides only a low-level C interface for Scilab
 (see <a href="#Scripting">Scripting Languages</a> for the general
 approach to wrapping). This means that functions, structs, classes,
 variables, etc... are interfaced through C functions. These C functions
 are mapped as Scilab functions. There are a few exceptions, such as
 constants and enumerations, which can be wrapped directly as Scilab
 variables.</p>
<h3><a name="Scilab_wrapping_identifiers">35.3.2 Identifiers</a></h3>
<p> In Scilab 5.x, identifier names are composed of 24 characters
 maximum (this limitation disappears from Scilab 6.0 onwards).
<br> By default, variable, member, and function names longer than 24
 characters are truncated, and a warning is produced for each
 truncation.</p>
<p>This can cause ambiguities, especially when wrapping structs/classes,
 for which the wrapped function name is composed of the struct/class
 name and field names. In these cases, the <a href="#SWIG_rename_ignore">
%rename directive</a> can be used to choose a different Scilab name.</p>
<p> Note: truncations can be disabled by specifying the target version 6
 of Scilab in the <tt>targetversion</tt> argument (i.e. <tt>
-targetversion 6</tt>).</p>
<h3><a name="Scilab_wrapping_functions">35.3.3 Functions</a></h3>
<p> Functions are wrapped as new Scilab built-in functions. For example:</p>
<div class="code">
<pre>
%module example

%inline %{
int fact(int n) {
  if (n &gt; 1)
    return n * fact(n - 1);
  else
    return 1;
}
%}
</pre>
</div>
<p> creates a built-in function <tt>fact(n)</tt> in Scilab:</p>
<div class="targetlang">
<pre>
--&gt; fact(4)
ans  =

    24.
</pre>
</div>
<h4><a name="Scilab_nn13">35.3.3.1 Argument passing</a></h4>
<p> In the above example, the function parameter is a primitive type and
 is marshalled by value. So this function is wrapped without any
 additional customization. Argument values are converted between C types
 and Scilab types through type mappings. There are several default type
 mappings for primitive and complex types, described later in the <a href="#Scilab_typemaps">
Scilab typemaps</a> section.</p>
<p> When a parameter is not passed by value, such as a pointer or
 reference, SWIG does not know if it is an input, output (or both)
 parameter. The INPUT, OUTPUT, INOUT typemaps defined in the <tt>
typemaps.i</tt> library can be used to specify this.</p>
<p> Let's see this on two simple functions: <tt>sub()</tt> which has an
 output parameter, and <tt>inc()</tt>, which as input/output parameter:</p>
<div class="code">
<pre>
%module example

%include &lt;typemaps.i&gt;

extern void sub(int *INPUT, int *INPUT, int *OUTPUT);
extern void inc(int *INOUT, int *INPUT);

%{
void sub(int *x, int *y, int *result) {
  *result = *x - *y;
}
void inc(int *x, int *delta) {
  *x = *x + *delta;
}
%}
</pre>
</div>
<p> In Scilab, parameters are passed by value. The output (and inout)
 parameters are returned as the result of the functions:</p>
<div class="targetlang">
<pre>
--&gt; sub(5, 3)
 ans  =

    2.

--&gt; inc(4, 3)
 ans  =

    7.
</pre>
</div>
<h4><a name="Scilab_nn14">35.3.3.2 Multiple output arguments</a></h4>
<p> A C function can have several output parameters. They can all be
 returned as results of the wrapped function as Scilab supports multiple
 return values from a function when using the <tt>typemaps.i</tt>
 library. If the C function itself returns a result, this is returned
 first before the parameter outputs.</p>
<p> The example below shows this for a C function returning 2 values and
 a result:</p>
<div class="code">
<pre>
%module example

%include &lt;typemaps.i&gt;

int divide(int n, int d, int *OUTPUT, int *OUTPUT);

%{
  int divide(int n, int d, int q*, int *r) {
    if (d != 0) {
      *q = n / d;
      *r = n % d;
      return 1;
    } else {
      return 0;
    }
  }
%}
</pre>
</div>
<br><div class="targetlang">
<pre>
--&gt; [ret, q, r] = divide(20, 6)
 r  =

    2.
 q  =

    3.
 ret  =

    1.
</pre>
</div>
<h3><a name="Scilab_wrapping_global_variables">35.3.4 Global variables</a>
</h3>
<p> Global variables are manipulated through generated accessor
 functions. For example, for a given <tt>Foo</tt> global variable, SWIG
 actually generates two functions: <tt>Foo_get()</tt> to get the value
 of <tt>Foo</tt>, and <tt>Foo_set()</tt> to set the value. These
 functions are used as following:</p>
<div class="targetlang">
<pre>
--&gt; exec loader.sce;
--&gt; c = Foo_get();

--&gt; Foo_set(4);

--&gt; c
c =

    3.

--&gt; Foo_get()
ans  =

    4.
</pre>
</div>
<p> It works for variables of primitive type, but also for non-primitive
 types: arrays, and structs/classes which are described later. For now,
 an example with two global primitive arrays x and y is shown:</p>
<div class="code">
<pre>
%module example

%inline %{
int x[10];
double y[7];

void initArrays()
{
  int i;
  for (i = 0; i &lt; 10; i++)
    x[i] = 1;
  for (i = 0; i &lt; 7; i++)
    y[i] = 1.0f;
}
%}
</pre>
</div>
<p> It works the same:</p>
<div class="targetlang">
<pre>
--&gt; exec loader.sce

--&gt; initArrays();
--&gt; x_get()
 ans  =

    1.    1.    1.    1.    1.    1.    1.    1.    1.    1.

--&gt; y_set([0:6] / 10);
--&gt; y_get()
 ans  =

    0.    0.1    0.2    0.3    0.4    0.5    0.6
</pre>
</div>
<h3><a name="Scilab_wrapping_constants_and_enums">35.3.5 Constants and
 enumerations</a></h3>
<h4><a name="Scilab_wrapping_constants">35.3.5.1 Constants</a></h4>
<p> There is not any constant in Scilab. By default, C/C++ constants are
 wrapped as getter functions. For example, for the following constants:</p>
<div class="code">
<pre>
%module example
#define    ICONST      42
#define    FCONST      2.1828
#define    CCONST      'x'
#define    CCONST2     '\n'
#define    SCONST      &quot;Hello World&quot;
#define    SCONST2     &quot;\&quot;Hello World\&quot;&quot;
</pre>
</div>
<p> the following getter functions are generated:</p>
<div class="targetlang">
<pre>
--&gt; exec loader.sce;
--&gt; ICONST_get();
 ans  =

    42.

--&gt; FCONST_get();
 ans  =

    2.1828

--&gt; CCONST_get();
 ans  =

    x

--&gt; CCONST2_get();
 ans  =

--&gt; SCONST_get();
 ans  =

    Hello World

--&gt; SCONST2_get();
 ans  =

    &quot;Hello World&quot;

--&gt; EXPR_get();
 ans  =

    48.5484

--&gt; iconst_get();
 ans  =

    37.

--&gt; fconst_get();
 ans  =

    3.14
</pre>
</div>
<p> There is another mode in which constants are wrapped as Scilab
 variables. The variables are easier to use than functions, but the
 drawback is that variables are not constant and so can be modified.</p>
<p> This mode can be enabled/disabled at any time in the interface file
 with <tt>%scilabconst()</tt>, which works like all the other <a href="#Customization_features">
%feature directives</a>. Use the argument value &quot;1&quot; to enable and &quot;0&quot; to
 disable this mode. For example in this mode the previous constants:</p>
<div class="code">
<pre>
%module example

%scilabconst(1);
#define    ICONST      42
#define    FCONST      2.1828
#define    CCONST      'x'
#define    CCONST2     '\n'
#define    SCONST      &quot;Hello World&quot;
#define    SCONST2     &quot;\&quot;Hello World\&quot;&quot;
</pre>
</div>
<p> are mapped to Scilab variables, with the same name:</p>
<div class="targetlang">
<pre>
--&gt; exec loader.sce;
--&gt; ICONST
 ans  =

    42

--&gt; FCONST
 ans  =

    2.1828

--&gt; CCONST
 ans  =

    x

--&gt; CCONST2
 ans  =

--&gt; SCONST
 ans  =

    Hello World

--&gt; SCONST2
 ans  =

    &quot;Hello World&quot;

--&gt; EXPR
 ans  =

    48.5484

--&gt; iconst
 ans  =

    37

--&gt; fconst
 ans  =

    3.14
</pre>
</div>
<h4><a name="Scilab_wrapping_enums">35.3.5.2 Enumerations</a></h4>
<p> The wrapping of enums is the same as for constants. By default,
 enums are wrapped as getter functions. For example, with the following
 enumeration:</p>
<div class="code">
<pre>%module example
typedef enum { RED, BLUE, GREEN } color;
</pre>
</div>
<p> a getter function will be generated for each value of the
 enumeration:</p>
<div class="targetlang">
<pre>
--&gt; exec loader.sce;
--&gt; RED_get()
 ans  =

    0.

--&gt; BLUE_get()
 ans  =

    1.

--&gt; GREEN_get()
 ans  =

    2.
</pre>
</div>
<p> The <tt>%scilabconst()</tt> feature is also available for
 enumerations:</p>
<div class="code">
<pre>%module example
%scilabconst(1) color;
typedef enum { RED, BLUE, GREEN } color;
</pre>
</div>
<br><div class="targetlang">
<pre>
--&gt; exec loader.sce;
--&gt; RED
 ans  =

    0.

--&gt; BLUE
 ans  =

    1.

--&gt; GREEN
 ans  =

    2.

</pre>
</div>
<h3><a name="Scilab_wrapping_pointers">35.3.6 Pointers</a></h3>
<p> Pointers are supported by SWIG. A pointer can be returned from a
 wrapped C/C++ function, stored in a Scilab variable, and used in input
 argument of another C/C++ function.</p>
<p> Also, thanks to the SWIG runtime which stores information about
 types, pointer types are tracked between exchanges Scilab and the
 native code. Indeed pointer types are stored alongside the pointer
 address. A pointer is mapped to a Scilab structure (<a href="https://help.scilab.org/docs/5.5.2/en_US/tlist.html">
tlist</a>), which contains as fields the pointer address and the pointer
 type (in fact a pointer to the type information structure in the SWIG
 runtime).
<br> Why a native pointer is not mapped to a Scilab pointer (type name:
 &quot;pointer&quot;, type ID: 128) ? The big advantage of mapping to a <tt>tlist</tt>
 is that it exposes a new type for the pointer in Scilab, type which can
 be acessed in Scilab with the <a href="https://help.scilab.org/docs/5.5.2/en_US/typeof.html">
typeof</a> function, and manipulated using the <a href="https://help.scilab.org/docs/5.5.2/en_US/overloading.html">
overloading</a> mechanism.</p>
<p> Notes:</p>
<ul>
<li>type tracking needs the SWIG runtime to be first initialized with
 the appropriate function (see the <a href="#Scilab_module_initialization">
Module initialization</a> section).</li>
<li>for any reason, if a wrapped pointer type is unknown (or if the SWIG
 runtime is not initialized), SWIG maps it to a Scilab pointer. Also, a
 Scilab pointer is always accepted as a pointer argument of a wrapped
 function. The drawaback is that pointer type is lost.</li>
</ul>
<p> Following is an example of the wrapping of the C <tt>FILE*</tt>
 pointer:</p>
<div class="code">
<pre>
%module example

%{
#include &lt;stdio.h&gt;
%}

FILE *fopen(const char *filename, const char *mode);
int fputs(const char *, FILE *);
int fclose(FILE *);
</pre>
</div>
<p> These functions can be used the same way as in C from Scilab:</p>
<div class="targetlang">
<pre>
--&gt; example_Init();

--&gt; f = fopen(&quot;junk&quot;, &quot;w&quot;);
--&gt; typeof(f)
 ans  =

  _p_FILE

--&gt; fputs(&quot;Hello World&quot;, f);
--&gt; fclose(f);
</pre>
</div>
<p> Note: the type name <tt>_p_FILE</tt> which means &quot;pointer to FILE&quot;.</p>
<p> The user of a pointer is responsible for freeing it or, like in the
 example, closing any resources associated with it (just as is required
 in a C program).</p>
<h4><a name="Scilab_wrapping_pointers_utility_functions">35.3.6.1
 Utility functions</a></h4>
<p> As a scripting language, Scilab does not provide functions to
 manipulate pointers. However, in some cases it can be useful, such as
 for testing or debugging.</p>
<p> SWIG comes with two pointer utility functions:</p>
<ul>
<li><tt>SWIG_this()</tt>: returns the address value of a pointer</li>
<li><tt>SWIG_ptr()</tt>: creates a pointer from an address value</li>
</ul>
<p> Note: a pointer created by <tt>SWIG_ptr()</tt> does not have any
 type and is mapped as a Scilab pointer.</p>
<p>Following we use the utility functions on the previous example:</p>
<div class="targetlang">
<pre>
--&gt; f = fopen(&quot;junk&quot;, &quot;w&quot;);
--&gt; fputs(&quot;Hello&quot;, f);
--&gt; addr = SWIG_this(f)
 ans  =

    8219088.

--&gt; p = SWIG_ptr(addr);
--&gt; typeof(p)
ans  =

  pointer

--&gt; fputs(&quot; World&quot;, p);
--&gt; fclose(f);
</pre>
</div>
<h4><a name="Scilab_wrapping_pointers_null_pointers">35.3.6.2 Null
 pointers:</a></h4>
<p> Using the previous <tt>SWIG_this()</tt> and <tt>SWIG_ptr()</tt>, it
 is possible to create and check null pointers:</p>
<div class="targetlang">
<pre>
--&gt; p = SWIG_ptr(0);
--&gt; SWIG_this(p) == 0
 ans  =

    T
</pre>
</div>
<h3><a name="Scilab_wrapping_structs">35.3.7 Structures</a></h3>
<p> Structs exist in Scilab, but C structs are not (at least in this
 version of SWIG) mapped to Scilab structs. A C structure is wrapped
 through low-level accessor functions, i.e. functions that give access
 to the member variables of this structure. In Scilab, a structure is
 manipulated through a pointer which is passed as an argument to the
 accessor functions.</p>
<p> Let's see it on an example of a struct with two members:</p>
<div class="code">
<pre>
%module example

%inline %{

typedef struct {
  int x;
  int arr[4];
} Foo;

%}
</pre>
</div>
<p> Several functions are generated:</p>
<ul>
<li>a constructor function <tt>new_Foo()</tt> which returns a pointer to
 a newly created struct <tt>Foo</tt>.</li>
<li>two member getter functions <tt>Foo_x_get()</tt>, <tt>Foo_arr_get()</tt>
, to get the values of <tt>x</tt> and <tt>y</tt> for the struct pointer
 (provided as the first parameter to these functions)</li>
<li>two member setter functions <tt>Foo_x_set()</tt>, <tt>Foo_arr_set()</tt>
, to set the values of <tt>x</tt> and <tt>y</tt> for the struct pointer
 (provided as the first parameter to these functions).</li>
<li>a destructor function <tt>delete_Foo()</tt> to release the struct
 pointer.</li>
</ul>
<p> Usage example:</p>
<div class="targetlang">
<pre>
--&gt; f = new_Foo();
--&gt; Foo_x_set(f, 100);
--&gt; Foo_x_get(f)
ans  =

    100.

--&gt; Foo_arr_set(f, [0:3]);
--&gt; Foo_arr_get(f)
ans  =

    0.    1.    2.    3.

--&gt; delete_Foo(f);
</pre>
</div>
<p> Members of a structure that are also structures are also accepted
 and wrapped as a pointer:</p>
<div class="code">
<pre>
%module example

%inline %{

typedef struct {
  int x;
} Bar;

typedef struct {
  Bar b;
} Foo;

%}
</pre>
</div>
<br><div class="targetlang">
<pre>
--&gt; b = new_Bar();
--&gt; Bar_x_set(b, 20.);

--&gt; f = new_Foo();
--&gt; Foo_b_set(f, b);

--&gt; b2 = Foo_b_get(f);
--&gt; Bar_x_get(b2);
ans  =

    20.
</pre>
</div>
<p> Note: the pointer to the struct works as described in <a href="#Scilab_wrapping_pointers">
Pointers</a>. For example, the type of the struct pointer can be get
 with <tt>typeof</tt>, as following:</p>
<div class="targetlang">
<pre>
--&gt; example_Init();
--&gt; b = new_Bar();
--&gt; typeof(b)
 ans  =

    _p_Bar
--&gt; delete_Bar(b);
</pre>
</div>
<h3><a name="Scilab_wrapping_cpp_classes">35.3.8 C++ classes</a></h3>
<p> Classes do not exist in Scilab. The classes are wrapped the same way
 as structs. Low-level accessor functions are generated for class
 members. Also, constructor and destructor functions are generated to
 create and destroy an instance of the class.</p>
<p> For example, the following class:</p>
<div class="code">
<pre>
%module example

%inline %{

class Point {
public:
  int x, y;
  Point(int _x, int _y) : x(_x), y(_y) {}
  double distance(const Point&amp; rhs) {
    return sqrt(pow(x-rhs.x, 2) + pow(y-rhs.y, 2));
  }
  void set(int _x, int _y) {
    x=_x;
    y=_y;
  }
};

%}
</pre>
</div>
<p> can be used in Scilab like this:</p>
<div class="targetlang">
<pre>
--&gt; p1 = Point_new(3, 5);
--&gt; p2 = Point_new(1, 2);
--&gt; p1.distance(p2)
ans  =

    3.6056

--&gt; delete_Point(p1);
--&gt; delete_Point(p2);
</pre>
</div>
<p> Note: like structs, class pointers are mapped as described in <a href="#Scilab_wrapping_pointers">
Pointers</a>. Let's give an example which shows that each class pointer
 type is a new type in Scilab that can be used for example (through <a href="https://help.scilab.org/docs/5.5.2/en_US/overloading.html">
overloading</a>) to implement a custom print for the <tt>Point</tt>
 class:</p>
<div class="targetlang">
<pre>
--&gt; function %_p_Point_p(p)
--&gt;     mprintf('[%d, %d]\n', Point_x_get(p), Point_y_get(p));
--&gt; endfunction

--&gt; example_Init();
--&gt; p = new_Point(1, 2)
 p  =

[1, 2]

--&gt; delete_Point(p);
</pre>
</div>
<h3><a name="Scilab_wrapping_cpp_inheritance">35.3.9 C++ inheritance</a></h3>
<p> Inheritance is supported. SWIG knows the inheritance relationship
 between classes.</p>
<p> A function is only generated for the class in which it is actually
 declared. But if one of its parameters is a class, any instance of a
 derived class is accepted as the argument.</p>
<p> This mechanism also applies for accessor functions: they are
 generated only in the class in which they are defined. But any instance
 of a derived class can be used as the argument to these accessor
 functions.</p>
<p> For example, let's take a base class <tt>Shape</tt> and two derived
 classes <tt>Circle</tt> and <tt>Square</tt>:</p>
<div class="code">
<pre>
%module example

%inline %{

class Shape {
public:
  double x, y;
  void set_location(double _x, double _y) { x = _x; y = _y; }
  virtual double get_perimeter() { return 0; };
};

class Circle : public Shape {
public:
  int radius;
  Circle(int _radius): radius(_radius) {};
  virtual double get_perimeter() { return 6.28 * radius; }
};

class Square : public Shape {
public:
  int size;
  Square(int _size): size(_size) {};
  virtual double get_perimeter() { return 4 * size; }
};

%}
</pre>
</div>
<p> To set the location of the <tt>Circle</tt>, we have to use the
 function <tt>set_location()</tt> of the parent <tt>Shape</tt>. But we
 can use either use the <tt>get_perimeter()</tt> function of the parent
 class or the derived class:</p>
<div class="targetlang">
<pre>
--&gt; c = new_Circle(3);

--&gt; Shape_set_location(c, 2, 3);
--&gt; Shape_x_get(c)
 ans  =

    2.

--&gt; Circle_get_perimeter(c)
 ans  =

    18.84

--&gt; Shape_get_perimeter(c)
 ans  =

    18.84
</pre>
</div>
<h3><a name="Scilab_wrapping_cpp_overloading">35.3.10 C++ overloading</a>
</h3>
<p> As explained in <a href="#SWIGPlus_overloaded_methods">Overloaded
 functions and methods</a> SWIG provides support for overloaded
 functions and constructors.</p>
<p>As SWIG knows pointer types, the overloading works also with pointer
 types, here is an example with a function <tt>magnify</tt> overloaded
 for the previous classes <tt>Shape</tt> and <tt>Circle</tt>:</p>
<div class="code">
<pre>
%module example

void magnify(Square *square, double factor) {
  square-&gt;size *= factor;
};

void magnify(Circle *circle, double factor) {
  square-&gt;radius *= factor;
};
</pre>
</div><div class="targetlang">
<pre>
--&gt; example_Init();
--&gt; c = new_Circle(3);
--&gt; s = new_Square(2);

--&gt; magnify(c, 10);
--&gt; Circle_get_radius(c)
 ans  =

   30;
--&gt; magnify(s, 10);
--&gt; Square_get_size(s)
 ans  =

   20;
</pre>
</div>
<h3><a name="Scilab_wrapping_pointers_references_values_arrays">35.3.11
 Pointers, references, values, and arrays</a></h3>
<p> In C++ objects can be passed by value, pointer, reference, or by an
 array:</p>
<div class="code">
<pre>
%module example

%{
#include &lt;sciprint.h&gt;
%}

%inline %{

class Foo {
public:
  Foo(int _x) : x(_x) {}
  int x;
};

void spam1(Foo *f)  { sciprint(&quot;%d\n&quot;, f-&gt;x); }   // Pass by pointer
void spam2(Foo &amp;f)  { sciprint(&quot;%d\n&quot;, f.x); }    // Pass by reference
void spam3(Foo f)   { sciprint(&quot;%d\n&quot;, f.x); }    // Pass by value
void spam4(Foo f[]) { sciprint(&quot;%d\n&quot;, f[0].x); } // Array of objects

%}
</pre>
</div>
<p> In SWIG, there is no real distinction between these. So in Scilab,
 it is perfectly legal to do this:</p>
<div class="targetlang">
<pre>
--&gt; f = new_Foo()
--&gt; spam1(f)
3
--&gt; spam2(f)
3
--&gt; spam3(f)
3
--&gt; spam4(f)
3
</pre>
</div>
<p> Similar behaviour occurs for return values. For example, if you had
 functions like this:</p>
<div class="code">
<pre>
Foo *spam5();
Foo &amp;spam6();
Foo  spam7();
</pre>
</div>
<p> All these functions will return a pointer to an instance of <tt>Foo</tt>
. As the function <tt>spam7</tt> returns a value, new instance of <tt>
Foo</tt> has to be allocated, and a pointer on this instance is
 returned.</p>
<h3><a name="Scilab_wrapping_cpp_templates">35.3.12 C++ templates</a></h3>
<p> As in other languages, function and class templates are supported in
 SWIG Scilab.</p>
<p> You have to tell SWIG to create wrappers for a particular template
 instantiation. The <tt>%template</tt> directive is used for this
 purpose. For example:</p>
<div class="code">
<pre>
%module example

template&lt;class T1, class T2, class T3&gt;
struct triplet {
  T1 first;
  T2 second;
  T3 third;
  triplet(const T1&amp; a, const T2&amp; b, const T3&amp; c) {
    third = a; second = b; third = c;
  }
};

%template(IntTriplet) triplet&lt;int, int, int&gt;;
</pre>
</div>
<p> Then in Scilab:</p>
<div class="targetlang">
<pre>
--&gt; t = new_IntTriplet(3, 4, 1);

--&gt; IntTriplet_first_get(t)
 ans  =

    3.

--&gt; IntTriplet_second_get(t)
 ans  =

    4.

--&gt; IntTriplet_third_get(t)
 ans  =

    1.

--&gt; delete_IntTriplet(t);
</pre>
</div>
<p> More details on template support can be found in the <a href="#SWIGPlus_nn30">
templates</a> documentation.</p>
<h3><a name="Scilab_wrapping_cpp_operators">35.3.13 C++ operators</a></h3>
<p> C++ operators are partially supported. Operator overloading exists
 in Scilab, but a C++ operator is not (in this version) wrapped by SWIG
 as a Scilab operator, but as a function. It is not automatic, you have
 to rename each operator (with the instruction <tt>%rename</tt>) with
 the suitable wrapper name.</p>
<p> Let's see it with an example of class with two operators <tt>+</tt>
 and <tt>double()</tt>:</p>
<div class="code">
<pre>
%module example

%rename(plus) operator +;
%rename(toDouble) operator double();

%inline %{

class Complex {
public:
  Complex(double re, double im) : real(re), imag(im) {};

  Complex operator+(const Complex&amp; other) {
    double result_real = real + other.real;
    double result_imaginary = imag + other.imag;
    return Complex(result_real, result_imaginary);
  }
  operator double() { return real; }
private:
  double real;
  double imag;
};

%}
</pre>
</div>
<br><div class="targetlang">
<pre>
--&gt; c1 = new_Complex(3, 7);

--&gt; c2 = Complex_plus(c, new_Complex(1, 1));

--&gt; Complex_toDouble(c2)
 ans  =

    4.
</pre>
</div>
<h3><a name="Scilab_wrapping_cpp_namespaces">35.3.14 C++ namespaces</a></h3>
<p> SWIG is aware of C++ namespaces, but does not use it for wrappers.
 The module is not broken into submodules, nor do namespace appear in
 functions names. All the namespaces are all flattened in the module.
 For example with one namespace <tt>Foo</tt>:</p>
<div class="code">
<pre>
%module example

%inline %{

namespace foo {
  int fact(int n) {
    if (n &gt; 1)
      return n * fact(n-1);
    else
      return 1;
  }

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

%}

</pre>
</div>
<p> In Scilab, there is no need to the specify the <tt>Foo</tt>
 namespace:</p>
<div class="targetlang">
<pre>
--&gt; fact(3)
 ans  =

   6.

--&gt; v = new_Vector();
--&gt; Vector_x_set(v, 3.4);
--&gt; Vector_y_get(v)
 ans  =

   0.
</pre>
</div>
<p> If your program has more than one namespace, name conflicts can be
 resolved using <tt>%rename</tt>. For example:</p>
<div class="code">
<pre>
%rename(Bar_spam) Bar::spam;

namespace Foo {
  int spam();
}

namespace Bar {
  int spam();
}
</pre>
</div>
<p> Note: the <a href="#SWIGPlus_nspace">nspace</a> feature is not
 supported.</p>
<h3><a name="Scilab_wrapping_cpp_exceptions">35.3.15 C++ exceptions</a></h3>
<p> Scilab does not natively support exceptions, but has errors. When an
 exception is thrown, SWIG catches it, and sets a Scilab error. An error
 message is displayed in Scilab. For example:</p>
<div class="code">
<pre>
%module example

%inline %{
void throw_exception() throw(char const *) {
  throw &quot;Bye world !&quot;;
}
%}
</pre>
</div>
<br><div class="targetlang">
<pre>
--&gt;throw_exception()
  !--error 999
SWIG/Scilab: Exception (char const *) occurred: Bye world !
</pre>
</div>
<p> Scilab has a <tt>try-catch</tt> mechanism (and a similar instruction
 <tt>execstr()</tt>) to handle exceptions. It can be used with the <tt>
lasterror()</tt> function as following:</p>
<div class="targetlang">
<pre>
--&gt; execstr('throw_exception()', 'errcatch');
 ans  =

    999.

--&gt; lasterror()
 ans  =

    SWIG/Scilab: Exception (char const *) occurred: Bye world !
</pre>
</div>
<p> If the function has a <tt>throw</tt> exception specification, SWIG
 can automatically map the exception type and set an appropriate Scilab
 error message. It works for a few primitive types, and also for STL
 exceptions (the library <tt>std_except.i</tt> has to be included to get
 the STL exception support):</p>
<div class="code">
<pre>
%module example

%include &lt;std_except.i&gt;

%inline %{
void throw_int() throw(int) {
  throw 12;
}

void throw_stl_invalid_arg(int i) throw(std::invalid_argument) {
  if (i &lt; 0)
    throw std::invalid_argument(&quot;argument is negative.&quot;);
}
%}
</pre>
</div>
<br><div class="targetlang">
<pre>
--&gt; throw_int();
            !--error 999
SWIG/Scilab: Exception (int) occurred: 12

--&gt;throw_stl_invalid_arg(-1);
                          !--error 999
SWIG/Scilab: ValueError: argument is negative.
</pre>
</div>
<p> More complex or custom exception types require specific exception
 typemaps to be implemented in order to specifically handle a thrown
 type. See the <a href="#SWIGPlus">SWIG C++ documentation</a> for more
 details.</p>
<h3><a name="Scilab_wrapping_cpp_stl">35.3.16 C++ STL</a></h3>
<p> The Standard Template Library (STL) is partially supported. See <a href="#Scilab_typemaps_stl">
STL</a> for more details.</p>
<h2><a name="Scilab_typemaps">35.4 Type mappings and libraries</a></h2>
<h3><a name="Scilab_typemaps_primitive_types">35.4.1 Default primitive
 type mappings</a></h3>
<p> The following table provides the equivalent Scilab type for C/C++
 primitive types.</p>
<div class="table">
<table border="1" summary="Scilab default primitive type mappings">
<tr><td><b>C/C++ type</b></td><td><b>Scilab type</b></td></tr>
<tr><td>bool</td><td>boolean</td></tr>
<tr><td>char</td><td>string</td></tr>
<tr><td>signed char</td><td>double or int8</td></tr>
<tr><td>unsigned char</td><td>double or uint8</td></tr>
<tr><td>short</td><td>double or int16</td></tr>
<tr><td>unsigned short</td><td>double or uint16</td></tr>
<tr><td>int</td><td>double or int32</td></tr>
<tr><td>unsigned int</td><td>double or uint32</td></tr>
<tr><td>long</td><td>double or int32</td></tr>
<tr><td>unsigned long</td><td>double or uint32</td></tr>
<tr><td>signed long long</td><td>not supported in Scilab 5.x</td></tr>
<tr><td>unsigned long long</td><td>not supported in Scilab 5.x</td></tr>
<tr><td>float</td><td>double</td></tr>
<tr><td>double</td><td>double</td></tr>
<tr><td>char * or char[]</td><td>string</td></tr>
</table>
</div>
<p> Notes:</p>
<ul>
<li>In Scilab the <tt>double</tt> type is far more used than any integer
 type. This is why integer values (<tt>int32</tt>, <tt>uint32</tt>, ...)
 are automatically converted to Scilab <tt>double</tt> values when
 marshalled from C into Scilab. Additionally on input to a C function,
 Scilab <tt>double</tt> values are converted into the related integer
 type.</li>
<li> When an integer is expected, if the input is a double, the value
 must be an integer, i.e. it must not have any decimal part, otherwise a
 SWIG value error occurs.</li>
<li> In SWIG for Scilab 5.x, the <tt>long long</tt> type is not
 supported, since Scilab 5.x does not have a 64-bit integer type. The
 default behaviour is for SWIG to generate code that will give a runtime
 error if <tt>long long</tt> type arguments are used from Scilab.</li>
</ul>
<h3><a name="Scilab_typemaps_arrays">35.4.2 Arrays</a></h3>
<p> Typemaps are available by default for arrays. Primitive type arrays
 are automatically converted to/from Scilab matrices. Typemaps are also
 provided to handle members of a struct or class that are arrays.</p>
<p> In input, the matrix is usually one-dimensional (it can be either a
 row or column vector). But it can also be a two-dimensional matrix.
 Warning: in Scilab, the values are column-major ordered, unlike in C,
 which is row-major ordered.</p>
<p> The type mappings used for arrays is the same for primitive types,
 described <a href="#Scilab_typemaps_primitive_types">earlier</a>. This
 means that, if needed, a Scilab <tt>double</tt> vector is converted in
 input into the related C integer array and this C integer array is
 automatically converted on output into a Scilab <tt>double</tt> vector.
 Note that unlike scalars, no control is done for arrays when a <tt>
double</tt> is converted into an integer.</p>
<p> The following example illustrates all this:</p>
<div class="code">
<pre>
%module example

%#include &lt;stdio.h&gt;

%inline %{

void printArray(int values[], int len) {
  int i = 0;
  for (i = 0; i &lt; len; i++) {
    printf(&quot;%s %d %s&quot;, i==0?&quot;[&quot;:&quot;&quot;, values[i], i==len-1?&quot;]\n&quot;:&quot;&quot;);
  }
}
%}
</pre>
</div>
<br><div class="targetlang">
<pre>
--&gt; printArray([0 1 2 3], 4)
[ 0  1  2  3 ]

--&gt; printArray([0.2; -1.8; 2; 3.7], 4)
[ 0  -1  2  3 ]

--&gt; printArray([0 1; 2 3], 4)
[ 0  2  1  3 ]

--&gt; printArray([0; 1; 2; 3], 4)
[ 0  1  2  3 ]
</pre>
</div>
<h3><a name="Scilab_typemaps_pointer-to-pointers">35.4.3
 Pointer-to-pointers</a></h3>
<p> There are no specific typemaps for pointer-to-pointers, they are
 mapped as pointers in Scilab.</p>
<p> Pointer-to-pointers are sometimes used to implement matrices in C.
 The following is an example of this:</p>
<div class="code">
<pre>
%module example
%inline %{

// Returns the matrix [1 2; 3 4];
double **create_matrix() {
  double **M;
  int i;
  M = (double **) malloc(2 * sizeof(double *));
  for (i = 0; i &lt; 2; i++) {
    M[i] = (double *) malloc(2 * sizeof(double));
    M[i][0] = 2 * i + 1;
    M[i][1] = 2 * i + 2;
  }
  return M;
}

// Gets the item M(i, j) value
double get_matrix(double **M, int i, int j) {
  return M[i][j];
}

// Sets the item M(i, j) value to be val
void set_matrix(double **M, int i, int j, double val) {
  M[i][j] = val;
}

// Prints a matrix (2, 2) to console
void print_matrix(double **M, int nbRows, int nbCols) {
  int i, j;
  for (i = 0; i &lt; 2; i++) {
    for (j = 0; j &lt; 2; j++) {
      printf(&quot;%3g &quot;, M[i][j]);
    }
    printf(&quot;\n&quot;);
  }
}

%}
</pre>
</div>
<p> These functions are used like this in Scilab:</p>
<div class="targetlang">
<pre>
--&gt; m = create_matrix();

--&gt; print_matrix(m);
   1.   2.
   3.   4.

--&gt; set_matrix(m, 1, 1, 5.);

--&gt; get_matrix(m, 1, 1)
 ans  =

    5.
</pre>
</div>
<h3><a name="Scilab_typemaps_matrices">35.4.4 Matrices</a></h3>
<p> The <tt>matrix.i</tt> library provides a set of typemaps which can
 be useful when working with one-dimensional and two-dimensional
 matrices.</p>
<p> In order to use this library, just include it in the interface file:</p>
<div class="code">
<pre>
  %include &lt;matrix.i&gt;
</pre>
</div>
<p> Several typemaps are available for the common Scilab matrix types:</p>
<ul>
<li><tt>double</tt></li>
<li><tt>int</tt></li>
<li><tt>char *</tt></li>
<li><tt>bool</tt></li>
</ul>
<p> For example: for a matrix of <tt>int</tt>, we have the typemaps, for
 input:</p>
<ul>
<li><tt>(int *IN, int IN_ROWCOUNT, int IN_COLCOUNT)</tt></li>
<li><tt>(int IN_ROWCOUNT, int IN_COLCOUNT, int *IN)</tt></li>
<li><tt>(int *IN, int IN_SIZE)</tt></li>
<li><tt>(int IN_SIZE, int *IN)</tt></li>
</ul>
<p> and output:</p>
<ul>
<li><tt>(int **OUT, int *OUT_ROWCOUNT, int *OUT_COLCOUNT)</tt></li>
<li><tt>(int *OUT_ROWCOUNT, int *OUT_COLCOUNT, int **OUT)</tt></li>
<li><tt>(int **OUT, int *OUT_SIZE)</tt></li>
<li><tt>(int *OUT_SIZE, int **OUT)</tt></li>
</ul>
<p> They marshall a Scilab matrix type into the appropriate 2 or 3 C
 parameters. The following is an example using the typemaps in this
 library:</p>
<div class="code">
<pre>
%module example

%include &lt;matrix.i&gt;

%apply (int *IN, int IN_ROWCOUNT, int IN_COLCOUNT) { (int *matrix, int matrixNbRow, int matrixNbCol) };
%apply (int **OUT, int *OUT_ROWCOUNT, int *OUT_COLCOUNT) { (int **outMatrix, int *outMatrixNbRow, int *outMatrixNbCol) };

%inline %{

void absolute(int *matrix, int matrixNbRow, int matrixNbCol,
  int **outMatrix, int *outMatrixNbRow, int *outMatrixNbCol) {
  int i, j;
  *outMatrixNbRow = matrixNbRow;
  *outMatrixNbCol = matrixNbCol;
  *outMatrix = malloc(matrixNbRow * matrixNbCol * sizeof(int));
  for (i=0; i &lt; matrixNbRow * matrixNbCol; i++) {
    (*outMatrix)[i] = matrix[i] &gt; 0 ? matrix[i]:-matrix[i];
  }
}

%}
</pre>
</div>
<br><div class="targetlang">
<pre>
--&gt; absolute([-0 1 -2; 3 4 -5])
 ans  =

    0.    1.    2.
    3.    4.    5.
</pre>
</div>
<p> The remarks made earlier for arrays also apply here:</p>
<ul>
<li>The values of matrices in Scilab are column-major orderered,</li>
<li>There is no control while converting <tt>double</tt> values to
 integers, <tt>double</tt> values are truncated without any checking or
 warning.</li>
</ul>
<h3><a name="Scilab_typemaps_stl">35.4.5 STL</a></h3>
<p> The STL library wraps some containers defined in the STL (Standard
 Template Library), so that they can be manipulated in Scilab. This
 library also provides the appropriate typemaps to use the containers in
 functions and variables.</p>
<p> The list of wrapped sequence containers are:</p>
<ul>
<li><tt>std::vector</tt></li>
<li><tt>std::list</tt></li>
<li><tt>std::deque</tt></li>
</ul>
<p> And associative containers are:</p>
<ul>
<li><tt>std::set</tt></li>
<li><tt>std::multiset</tt></li>
</ul>
<p> Typemaps are available for the following container types:</p>
<ul>
<li><tt>double</tt></li>
<li><tt>float</tt></li>
<li><tt>int</tt></li>
<li><tt>string</tt></li>
<li><tt>bool</tt></li>
<li><tt>pointer</tt></li>
</ul>
<p> Containers of other item types are not supported. Using them does
 not break compilation, but provokes a runtime error. Containers of enum
 are not supported yet.</p>
<p> In order to use the STL, the library must first be included in the
 SWIG interface file:</p>
<div class="code">
<pre>
%include &lt;stl.i&gt;
</pre>
</div>
<p>Then for each container used, the appropriate template must be
 instantiated, in the <tt>std</tt> namespace:<div class="code">
<pre>
namespace std {
    %template(IntVector)    vector&lt;int&gt;;
    %template(DoubleVector) vector&lt;double&gt;;
}
</pre>
</div></p>
<p> Additionally, the module initialization function has to be executed
 first in Scilab, so that all the types are known to Scilab. See the <a href="#Scilab_module_initialization">
Module initialization</a> section for more details.</p>
<p> Because in Scilab matrices exist for basic types only, a sequence
 container of pointers is mapped to a Scilab list. For other item types
 (double, int, string...) the sequence container is mapped to a Scilab
 matrix.</p>
<p> The first example below shows how to create a vector (of <tt>int</tt>
) in Scilab, add some values to the vector and pass it as an argument of
 a function. It also shows, thanks to the typemaps, that we can also
 pass a Scilab matrix of values directly into the function:</p>
<div class="code">
<pre>
%module example

%include &lt;stl.i&gt;

namespace std {
  %template(IntVector) vector&lt;int&gt;;
}

%{
#include &lt;numeric&gt;
%}

%inline %{

double average(std::vector&lt;int&gt; v) {
  return std::accumulate(v.begin(), v.end(), 0.0) / v.size();
}

%}
</pre>
</div>
<br><div class="targetlang">
<pre>
--&gt; example_Init();

--&gt; v = new_IntVector();

--&gt; for i = 1:4
--&gt;     IntVector_push_back(v, i);
--&gt; end;

--&gt; average(v)
 ans  =

    2.5

--&gt; average([0 1 2 3])
 ans  =

    2.5

--&gt; delete_IntVector();
</pre>
</div>
<p> In the second example, a set of struct (<tt>Person</tt>) is wrapped.
 A function performs a search in this set, and returns a subset. As one
 can see, the result in Scilab is a list of pointers:</p>
<div class="code">
<pre>
%module example

%include &lt;stl.i&gt;

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

%inline %{

struct Person {
  Person(std::string _name, int _age) : name(_name), age(_age) {};
  std::string name;
  int age;
};
typedef Person * PersonPtr;

%}

namespace std {
  %template(PersonPtrSet) set&lt;PersonPtr&gt;;
}

%inline %{

std::set&lt;PersonPtr&gt; findPersonsByAge(std::set&lt;PersonPtr&gt; persons, int minAge, int maxAge) {
  std::set&lt;PersonPtr&gt; foundPersons;
  for (std::set&lt;PersonPtr&gt;::iterator it = persons.begin(); it != persons.end(); it++) {
    if (((*it)-&gt;age &gt;= minAge) &amp;&amp; ((*it)-&gt;age &lt;= maxAge)) {
      foundPersons.insert(*it);
    }
  }
  return foundPersons;
}

%}
</pre>
</div>
<br><div class="targetlang">
<pre>
--&gt; example_Init();

--&gt; joe = new_Person(&quot;Joe&quot;, 25);
--&gt; susan = new_Person(&quot;Susan&quot;, 32);
--&gt; bill = new_Person(&quot;Bill&quot;, 50);

--&gt; p = new_PersonPtrSet();
--&gt; PersonPtrSet_insert(p, susan);
--&gt; PersonPtrSet_insert(p, joe);
--&gt; PersonPtrSet_insert(p, bill);

--&gt; l = findPersonsByAge(p, 20, 40);

--&gt; size(l)
 ans  =

    2.

--&gt; Person_name_get(l(1))
ans  =

    Susan

--&gt; Person_name_get(l(2))
 ans  =

    Joe

--&gt; delete_PersonPtrSet(p);
</pre>
</div>
<h2><a name="Scilab_module_initialization">35.5 Module initialization</a>
</h2>
<p> The wrapped module contains an initialization function to:</p>
<ul>
<li>initialize the SWIG runtime, needed for pointer type tracking or
 when working with the STL</li>
<li>initialize the module constants and enumerations declared with <tt>
%scilabconst()</tt></li>
</ul>
<p> This initialization function should be executed at the start of a
 script, before the wrapped library has to be used.</p>
<p> The function has the name of the module suffixed by <tt>_Init</tt>.
 For example, to initialize the module <tt>example</tt>:</p>
<div class="targetlang">
<pre>
--&gt; example_Init();
</pre>
</div>
<h2><a name="Scilab_building_modes">35.6 Building modes</a></h2>
<p> The mechanism to load an external module in Scilab is called<i>
 Dynamic Link</i> and works with dynamic modules (or shared libraries, <tt>
.so</tt> files).</p>
<p> To produce a dynamic module, when generating the wrapper, there are
 two possibilities, or build modes:</p>
<ul>
<li>the <tt>nobuilder</tt> mode, this is the default mode in SWIG. The
 user is responsible of the build.</li>
<li>the <tt>builder</tt> mode. In this mode, Scilab is responsible of
 building.</li>
</ul>
<h3><a name="Scilab_building_modes_nobuilder_mode">35.6.1 No-builder
 mode</a></h3>
<p> In this mode, used by default, SWIG generates the wrapper sources,
 which have to be manually compiled and linked. A loader script <tt>
loader.sce</tt> is also produced, this one is executed further in Scilab
 to load the module.</p>
<p> This mode is the best option to use when you have to integrate the
 module build into a larger build process.</p>
<h3><a name="Scilab_building_modes_builder_mode">35.6.2 Builder mode</a></h3>
<p> In this mode, in addition to the wrapper sources, SWIG produces a
 builder Scilab script (<tt>builder.sce</tt>), which is executed in
 Scilab to build the module. In a few words, the Scilab <tt>ilib_build()</tt>
 command is used, which produces the shared library file, and the loader
 script <tt>loader.sce</tt> (and also a cleaner script <tt>cleaner.sce</tt>
).</p>
<p> An advantage of this mode is that it hides all the complexity of the
 build and other platform issues. Also it allows the module to conform
 to a Scilab external module convention which is that an external module
 should be simply built by calling a builder script.</p>
<p> The builder mode is activated with the <tt>-builder</tt> SWIG
 option. In this mode, the following SWIG options may be used to setup
 the build:</p>
<ul>
<li><tt><b>-buildersources</b></tt>: to add sources to the build
 (several files must be separated by a comma)</li>
<li><tt><b>-buildercflags</b></tt>: to add flags to the builder compiler
 flags, for example to set library dependencies include paths</li>
<li><tt><b>-builderldflags</b></tt>: to add flags to the linker flags,
 for example to set library dependency names and paths</li>
</ul>
<p> Let's give an example how to build a module <tt>example</tt>,
 composed of two sources, and using a library dependency:</p>
<ul>
<li>the sources are <tt>baa1.c</tt> and <tt>baa2.c</tt> (and are stored
 in the current directory)</li>
<li>the library is <tt>libfoo</tt> in <tt>/opt/foo</tt> (headers stored
 in <tt>/opt/foo/include</tt>, and shared library in <tt>/opt/foo/lib</tt>
)</li>
</ul>
<p> The command is:</p>
<div class="shell">
<pre>
$ swig -scilab -builder -buildercflags -I/opt/foo/include -builderldflags &quot;-L/opt/foo/lib -lfoo&quot; -buildersources baa1.cxx, baa2.cxx example.i
</pre>
</div>
<h2><a name="Scilab_generated_scripts">35.7 Generated scripts</a></h2>
<p> In this part we give some details about the generated Scilab
 scripts.</p>
<h3><a name="Scilab_generated_scripts_builder_script">35.7.1 Builder
 script</a></h3>
<p> <tt>builder.sce</tt> is the name of the builder script generated by
 SWIG in <tt>builder</tt> mode. It contains code like this:</p>
<div class="code">
<pre>
ilib_name = &quot;examplelib&quot;;
files = [&quot;example_wrap.c&quot;];
libs = [];
table = [&quot;fact&quot;, &quot;_wrap_fact&quot;;&quot;Foo_set&quot;, &quot;_wrap_Foo_set&quot;;&quot;Foo_get&quot;, &quot;_wrap_Foo_get&quot;;];
ilib_build(ilib_name, table, files, libs);
</pre>
</div>
<p> <tt>ilib_build(lib_name, table, files, libs)</tt> is used to create
 shared libraries, and to generate a loader file used to dynamically
 load the shared library into Scilab.</p>
<ul>
<li><tt><b>ilib_name</b></tt>: a character string, the generic name of
 the library without path and extension.</li>
<li><tt><b>files</b></tt>: string matrix containing objects files needed
 for shared library creation.</li>
<li><tt><b>libs</b></tt>: string matrix containing extra libraries
 needed for shared library creation.</li>
<li><tt><b>table</b></tt>: two column string matrix containing a table
 of pairs of 'scilab function name', 'C function name'.</li>
</ul>
<h3><a name="Scilab_generated_scripts_loader_script">35.7.2 Loader
 script</a></h3>
<p> The loader script is used to load in Scilab all the module
 functions. When loaded, these functions can be used as other Scilab
 functions.</p>
<p> The loader script <tt>loader.sce</tt> contains code similar to:</p>
<div class="code">
<pre>
// ------------------------------------------------------
// generated by builder.sce: Please do not edit this file
// ------------------------------------------------------

libexamplelib_path = get_file_path('loader.sce');
list_functions = [             'fact';
            'Foo_set';
            'Foo_get';
];
addinter(libexamplelib_path+'/libexamplelib.so', 'libexamplelib', list_functions);
// remove temp. variables on stack
clear libexamplelib_path;
clear list_functions;
clear get_file_path;
// ------------------------------------------------------
</pre>
</div>
<p> <tt>addinter(files, spname, fcts)</tt> performs dynamic linking of a
 compiled C interface function.</p>
<ul>
<li><tt><b>files</b></tt>: a character string or a vector of character
 strings defining the object files (containing the C interface
 functions) to link with.</li>
<li><tt><b>spname</b></tt>: a character string. Name of interface
 routine entry point.</li>
<li><tt><b>fcts</b></tt>: vector of character strings. The name of new
 Scilab function.</li>
</ul>
<h2><a name="Scilab_other_resources">35.8 Other resources</a></h2>
<ul>
<li>Example use cases can be found in the <tt>Examples/scilab</tt>
 directory.</li>
<li>The test suite in the <tt>Examples/test-suite/scilab</tt> can be
 another source of useful use cases.</li>
<li>The <a href="http://help.scilab.org/docs/5.5.0/en_US/api_scilab.html">
Scilab API</a> is used in the generated code and is a useful reference
 when examining the output.</li>
<li>This <a href="http://wiki.scilab.org/howto/Create%20a%20toolbox">
guide</a> describes the Scilab external modules structure and files, in
 particular the files that are generated by SWIG for Scilab.</li>
</ul>
<HR NOSHADE>
<h1><a name="Tcl">36 SWIG and Tcl</a></h1>

<!-- INDEX -->
<div class="sectiontoc">
<ul>
<li><a href="#Tcl_nn2">Preliminaries</a>
<ul>
<li><a href="#Tcl_nn3">Getting the right header files</a></li>
<li><a href="#Tcl_nn4">Compiling a dynamic module</a></li>
<li><a href="#Tcl_nn5">Static linking</a></li>
<li><a href="#Tcl_nn6">Using your module</a></li>
<li><a href="#Tcl_nn7">Compilation of C++ extensions</a></li>
<li><a href="#Tcl_nn8">Compiling for 64-bit platforms</a></li>
<li><a href="#Tcl_nn9">Setting a package prefix</a></li>
<li><a href="#Tcl_nn10">Using namespaces</a></li>
</ul>
</li>
<li><a href="#Tcl_nn11">Building Tcl/Tk Extensions under Windows 95/NT</a>
<ul>
<li><a href="#Tcl_nn12">Running SWIG from Developer Studio</a></li>
<li><a href="#Tcl_nn13">Using NMAKE</a></li>
</ul>
</li>
<li><a href="#Tcl_nn14">A tour of basic C/C++ wrapping</a>
<ul>
<li><a href="#Tcl_nn15">Modules</a></li>
<li><a href="#Tcl_nn16">Functions</a></li>
<li><a href="#Tcl_nn17">Global variables</a></li>
<li><a href="#Tcl_nn18">Constants and enums</a></li>
<li><a href="#Tcl_nn19">Pointers</a></li>
<li><a href="#Tcl_nn20">Structures</a></li>
<li><a href="#Tcl_nn21">C++ classes</a></li>
<li><a href="#Tcl_nn22">C++ inheritance</a></li>
<li><a href="#Tcl_nn23">Pointers, references, values, and arrays</a></li>
<li><a href="#Tcl_nn24">C++ overloaded functions</a></li>
<li><a href="#Tcl_nn25">C++ operators</a></li>
<li><a href="#Tcl_nn26">C++ namespaces</a></li>
<li><a href="#Tcl_nn27">C++ templates</a></li>
<li><a href="#Tcl_nn28">C++ Smart Pointers</a></li>
</ul>
</li>
<li><a href="#Tcl_nn29">Further details on the Tcl class interface</a>
<ul>
<li><a href="#Tcl_nn30">Proxy classes</a></li>
<li><a href="#Tcl_nn31">Memory management</a></li>
</ul>
</li>
<li><a href="#Tcl_nn32">Input and output parameters</a></li>
<li><a href="#Tcl_nn33">Exception handling</a></li>
<li><a href="#Tcl_nn34">Typemaps</a>
<ul>
<li><a href="#Tcl_nn35">What is a typemap?</a></li>
<li><a href="#Tcl_nn36">Tcl typemaps</a></li>
<li><a href="#Tcl_nn37">Typemap variables</a></li>
<li><a href="#Tcl_nn38">Converting a Tcl list to a char **</a></li>
<li><a href="#Tcl_nn39">Returning values in arguments</a></li>
<li><a href="#Tcl_nn40">Useful functions</a></li>
<li><a href="#Tcl_nn41">Standard typemaps</a></li>
<li><a href="#Tcl_nn42">Pointer handling</a></li>
</ul>
</li>
<li><a href="#Tcl_nn43">Turning a SWIG module into a Tcl Package.</a></li>
<li><a href="#Tcl_nn44">Building new kinds of Tcl interfaces (in Tcl)</a>
<ul>
<li><a href="#Tcl_nn45">Proxy classes</a></li>
</ul>
</li>
<li><a href="#Tcl_nn46">Tcl/Tk Stubs</a></li>
</ul>
</div>
<!-- INDEX -->
<p><b> Caution: This chapter is under repair!</b></p>
<p> This chapter discusses SWIG's support of Tcl. SWIG currently
 requires Tcl 8.0 or a later release. Earlier releases of SWIG supported
 Tcl 7.x, but this is no longer supported.</p>
<h2><a name="Tcl_nn2">36.1 Preliminaries</a></h2>
<p> To build a Tcl module, run SWIG using the <tt>-tcl</tt> or <tt>-tcl8</tt>
 option :</p>
<div class="code">
<pre>
$ swig -tcl example.i
</pre>
</div>
<p> If building a C++ extension, add the <tt>-c++</tt> option:</p>
<div class="code">
<pre>
$ swig -c++ -tcl example.i
</pre>
</div>
<p> This creates a file <tt>example_wrap.c</tt> or <tt>example_wrap.cxx</tt>
 that contains all of the code needed to build a Tcl extension module.
 To finish building the module, you need to compile this file and link
 it with the rest of your program.</p>
<h3><a name="Tcl_nn3">36.1.1 Getting the right header files</a></h3>
<p> In order to compile the wrapper code, the compiler needs the <tt>
tcl.h</tt> header file. This file is usually contained in the directory</p>
<div class="code">
<pre>
/usr/local/include
</pre>
</div>
<p> Be aware that some Tcl versions install this header file with a
 version number attached to it. If this is the case, you should probably
 make a symbolic link so that <tt>tcl.h</tt> points to the correct
 header file.</p>
<h3><a name="Tcl_nn4">36.1.2 Compiling a dynamic module</a></h3>
<p> The preferred approach to building an extension module is to compile
 it into a shared object file or DLL. Assuming you have code you need to
 link to in a file called <tt>example.c</tt>, you will need to compile
 your program using commands like this (shown for Linux):</p>
<div class="code">
<pre>
$ swig -tcl example.i
$ gcc -fPIC -c example.c
$ gcc -fPIC -c example_wrap.c -I/usr/local/include
$ gcc -shared example.o example_wrap.o -o example.so
</pre>
</div>
<p> The exact commands for doing this vary from platform to platform.
 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>
SWIG/Examples/tcl</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="https://github.com/swig/swig/wiki">
SWIG Wiki</a> for additional information.</p>
<p> When linking the module, the name of the output file has to match
 the name of the module. If the name of your SWIG module is &quot;<tt>example</tt>
&quot;, the name of the corresponding object file should be &quot;<tt>example.so</tt>
&quot;. The name of the module is specified using the <tt>%module</tt>
 directive or the <tt>-module</tt> command line option.</p>
<h3><a name="Tcl_nn5">36.1.3 Static linking</a></h3>
<p> An alternative approach to dynamic linking is to rebuild the Tcl
 interpreter with your extension module added to it. In the past, this
 approach was sometimes necessary due to limitations in dynamic loading
 support on certain machines. However, the situation has improved
 greatly over the last few years and you should not consider this
 approach unless there is really no other option.</p>
<p> The usual procedure for adding a new module to Tcl involves writing
 a special function <tt>Tcl_AppInit()</tt> and using it to initialize
 the interpreter and your module. With SWIG, the <tt>tclsh.i</tt> and <tt>
wish.i</tt> library files can be used to rebuild the <tt>tclsh</tt> and <tt>
wish</tt> interpreters respectively. For example:</p>
<div class="code">
<pre>
%module example

%inline %{
extern int fact(int);
extern int mod(int, int);
extern double My_variable;
%}

%include &quot;tclsh.i&quot;       // Include code for rebuilding tclsh

</pre>
</div>
<p> The <tt>tclsh.i</tt> library file includes supporting code that
 contains everything needed to rebuild tclsh. To rebuild the
 interpreter, you simply do something like this:</p>
<div class="code">
<pre>
$ swig -tcl example.i
$ gcc example.c example_wrap.c \
        -Xlinker -export-dynamic \
        -DHAVE_CONFIG_H -I/usr/local/include/ \
        -L/usr/local/lib -ltcl -lm -ldl \
        -o mytclsh

</pre>
</div>
<p> You will need to supply the same libraries that were used to build
 Tcl the first time. This may include system libraries such as <tt>
-lsocket</tt>, <tt>-lnsl</tt>, and <tt>-lpthread</tt>. If this actually
 works, the new version of Tcl should be identical to the default
 version except that your extension module will be a built-in part of
 the interpreter.</p>
<p><b> Comment:</b> In practice, you should probably try to avoid static
 linking if possible. Some programmers may be inclined to use static
 linking in the interest of getting better performance. However, the
 performance gained by static linking tends to be rather minimal in most
 situations (and quite frankly not worth the extra hassle in the opinion
 of this author).</p>
<h3><a name="Tcl_nn6">36.1.4 Using your module</a></h3>
<p> To use your module, simply use the Tcl <tt>load</tt> command. If all
 goes well, you will be able to this:</p>
<div class="code">
<pre>
$ tclsh
% load ./example.so
% fact 4
24
%
</pre>
</div>
<p> A common error received by first-time users is the following:</p>
<div class="code">
<pre>
% load ./example.so
couldn't find procedure Example_Init
% 
</pre>
</div>
<p> This error is almost always caused when the name of the shared
 object file doesn't match the name of the module supplied using the
 SWIG <tt>%module</tt> directive. Double-check the interface to make
 sure the module name and the shared object file match. Another possible
 cause of this error is forgetting to link the SWIG-generated wrapper
 code with the rest of your application when creating the extension
 module.</p>
<p> Another common error is something similar to the following:</p>
<div class="code">
<pre>
% load ./example.so
couldn't load file &quot;./example.so&quot;: ./example.so: undefined symbol: fact
% 
</pre>
</div>
<p> This error usually indicates that you forgot to include some object
 files or libraries in the linking of the shared library file. Make sure
 you compile both the SWIG wrapper file and your original program into a
 shared library file. Make sure you pass all of the required libraries
 to the linker.</p>
<p> Sometimes unresolved symbols occur because a wrapper has been
 created for a function that doesn't actually exist in a library. This
 usually occurs when a header file includes a declaration for a function
 that was never actually implemented or it was removed from a library
 without updating the header file. To fix this, you can either edit the
 SWIG input file to remove the offending declaration or you can use the <tt>
%ignore</tt> directive to ignore the declaration.</p>
<p> Finally, suppose that your extension module is linked with another
 library like this:</p>
<div class="code">
<pre>
$ gcc -shared example.o example_wrap.o -L/home/beazley/projects/lib -lfoo \
      -o example.so
</pre>
</div>
<p> If the <tt>foo</tt> library is compiled as a shared library, you
 might get the following problem when you try to use your module:</p>
<div class="code">
<pre>
% load ./example.so
couldn't load file &quot;./example.so&quot;: libfoo.so: cannot open shared object file:
No such file or directory
%        
</pre>
</div>
<p> This error is generated because the dynamic linker can't locate the <tt>
libfoo.so</tt> library. When shared libraries are loaded, the system
 normally only checks a few standard locations such as <tt>/usr/lib</tt>
 and <tt>/usr/local/lib</tt>. To fix this problem, there are several
 things you can do. First, you can recompile your extension module with
 extra path information. For example, on Linux you can do this:</p>
<div class="code">
<pre>
$ gcc -shared example.o example_wrap.o -L/home/beazley/projects/lib -lfoo \
      -Xlinker -rpath /home/beazley/projects/lib \
      -o example.so
</pre>
</div>
<p> Alternatively, you can set the <tt>LD_LIBRARY_PATH</tt> environment
 variable to include the directory with your shared libraries. If
 setting <tt>LD_LIBRARY_PATH</tt>, be aware that setting this variable
 can introduce a noticeable performance impact on all other applications
 that you run. To set it only for Tcl, you might want to do this
 instead:</p>
<div class="code">
<pre>
$ env LD_LIBRARY_PATH=/home/beazley/projects/lib tclsh
</pre>
</div>
<p> Finally, you can use a command such as <tt>ldconfig</tt> to add
 additional search paths to the default system configuration (this
 requires root access and you will need to read the man pages).</p>
<h3><a name="Tcl_nn7">36.1.5 Compilation of C++ extensions</a></h3>
<p> Compilation of C++ extensions has traditionally been a tricky
 problem. Since the Tcl interpreter is written in C, you need to take
 steps to make sure C++ is properly initialized and that modules are
 compiled correctly.</p>
<p> On most machines, C++ extension modules should be linked using the
 C++ compiler. For example:</p>
<div class="code">
<pre>
% swig -c++ -tcl example.i
% g++ -fPIC -c example.cxx
% g++ -fPIC -c example_wrap.cxx -I/usr/local/include
% g++ -shared example.o example_wrap.o -o example.so
</pre>
</div>
<p> In addition to this, you may need to include additional library
 files to make it work. For example, if you are using the Sun C++
 compiler on Solaris, you often need to add an extra library <tt>-lCrun</tt>
 like this:</p>
<div class="code">
<pre>
% swig -c++ -tcl example.i
% CC -KPIC -c example.cxx
% CC -KPIC -c example_wrap.cxx -I/usr/local/include
% CC -G example.o example_wrap.o -L/opt/SUNWspro/lib -o example.so -lCrun
</pre>
</div>
<p> Of course, the extra libraries to use are completely
 non-portable---you will probably need to do some experimentation.</p>
<p> Sometimes people have suggested that it is necessary to relink the
 Tcl interpreter using the C++ compiler to make C++ extension modules
 work. In the experience of this author, this has never actually
 appeared to be necessary. Relinking the interpreter with C++ really
 only includes the special run-time libraries described above---as long
 as you link your extension modules with these libraries, it should not
 be necessary to rebuild Tcl.</p>
<p> If you aren't entirely sure about the linking of a C++ extension,
 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
 extension module. For example:</p>
<div class="code">
<pre>
$ ldd swig
        libstdc++-libc6.1-1.so.2 =&gt; /usr/lib/libstdc++-libc6.1-1.so.2 (0x40019000)
        libm.so.6 =&gt; /lib/libm.so.6 (0x4005b000)
        libc.so.6 =&gt; /lib/libc.so.6 (0x40077000)
        /lib/ld-linux.so.2 =&gt; /lib/ld-linux.so.2 (0x40000000)
$
</pre>
</div>
<p> As a final complication, a major weakness of C++ is that it does not
 define any sort of standard for binary linking of libraries. This means
 that C++ code compiled by different compilers will not link together
 properly as libraries nor is the memory layout of classes and data
 structures implemented in any kind of portable manner. In a monolithic
 C++ program, this problem may be unnoticed. However, in Tcl, it is
 possible for different extension modules to be compiled with different
 C++ compilers. As long as these modules are self-contained, this
 probably won't matter. However, if these modules start sharing data,
 you will need to take steps to avoid segmentation faults and other
 erratic program behavior. If working with lots of software components,
 you might want to investigate using a more formal standard such as COM.</p>
<h3><a name="Tcl_nn8">36.1.6 Compiling for 64-bit platforms</a></h3>
<p> On platforms that support 64-bit applications (Solaris, Irix, etc.),
 special care is required when building extension modules. On these
 machines, 64-bit applications are compiled and linked using a different
 set of compiler/linker options. In addition, it is not generally
 possible to mix 32-bit and 64-bit code together in the same
 application.</p>
<p> To utilize 64-bits, the Tcl executable will need to be recompiled as
 a 64-bit application. In addition, all libraries, wrapper code, and
 every other part of your application will need to be compiled for
 64-bits. If you plan to use other third-party extension modules, they
 will also have to be recompiled as 64-bit extensions.</p>
<p> If you are wrapping commercial software for which you have no source
 code, you will be forced to use the same linking standard as used by
 that software. This may prevent the use of 64-bit extensions. It may
 also introduce problems on platforms that support more than one linking
 standard (e.g., -o32 and -n32 on Irix).</p>
<h3><a name="Tcl_nn9">36.1.7 Setting a package prefix</a></h3>
<p> To avoid namespace problems, you can instruct SWIG to append a
 package prefix to all of your functions and variables. This is done
 using the -prefix option as follows :</p>
<div class="code">
<pre>
swig -tcl -prefix Foo example.i
</pre>
</div>
<p> If you have a function &quot;<tt>bar</tt>&quot; in the SWIG file, the prefix
 option will append the prefix to the name when creating a command and
 call it &quot;<tt>Foo_bar</tt>&quot;.</p>
<h3><a name="Tcl_nn10">36.1.8 Using namespaces</a></h3>
<p> Alternatively, you can have SWIG install your module into a Tcl
 namespace by specifying the <tt>-namespace</tt> option :</p>
<div class="code">
<pre>
swig -tcl -namespace example.i
</pre>
</div>
<p> By default, the name of the namespace will be the same as the module
 name, but you can override it using the <tt>-prefix</tt> option.</p>
<p> When the <tt>-namespace</tt> option is used, objects in the module
 are always accessed with the namespace name such as <tt>Foo::bar</tt>.</p>
<h2><a name="Tcl_nn11">36.2 Building Tcl/Tk Extensions under Windows
 95/NT</a></h2>
<p> Building a SWIG extension to Tcl/Tk under Windows 95/NT is roughly
 similar to the process used with Unix. Normally, you will want to
 produce a DLL that can be loaded into tclsh or wish. This section
 covers the process of using SWIG with Microsoft Visual C++. although
 the procedure may be similar with other compilers.</p>
<h3><a name="Tcl_nn12">36.2.1 Running SWIG from Developer Studio</a></h3>
<p> If you are developing your application within Microsoft developer
 studio, SWIG can be invoked as a custom build option. The process
 roughly follows these steps :</p>
<ul>
<li>Open up a new workspace and use the AppWizard to select a DLL
 project.</li>
<li>Add both the SWIG interface file (the .i file), any supporting C
 files, and the name of the wrapper file that will be created by SWIG
 (ie. <tt>example_wrap.c</tt>). Note : If using C++, choose a different
 suffix for the wrapper file such as <tt>example_wrap.cxx</tt>. Don't
 worry if the wrapper file doesn't exist yet--Developer studio will keep
 a reference to it around.</li>
<li>Select the SWIG interface file and go to the settings menu. Under
 settings, select the &quot;Custom Build&quot; option.</li>
<li>Enter &quot;SWIG&quot; in the description field.</li>
<li>Enter &quot;<tt>swig -tcl -o $(ProjDir)\$(InputName)_wrap.c $(InputPath)</tt>
&quot; in the &quot;Build command(s) field&quot;</li>
<li>Enter &quot;<tt>$(ProjDir)\$(InputName)_wrap.c</tt>&quot; in the &quot;Output
 files(s) field&quot;.</li>
<li>Next, select the settings for the entire project and go to
 &quot;C++:Preprocessor&quot;. Add the include directories for your Tcl
 installation under &quot;Additional include directories&quot;.</li>
<li>Finally, select the settings for the entire project and go to &quot;Link
 Options&quot;. Add the Tcl library file to your link libraries. For example
 &quot;<tt>tcl80.lib</tt>&quot;. Also, set the name of the output file to match
 the name of your Tcl module (ie. example.dll).</li>
<li>Build your project.</li>
</ul>
<p> Now, assuming all went well, SWIG will be automatically invoked when
 you build your project. Any changes made to the interface file will
 result in SWIG being automatically invoked to produce a new version of
 the wrapper file. To run your new Tcl extension, simply run <tt>tclsh</tt>
 or <tt>wish</tt> and use the <tt>load</tt> command. For example :</p>
<div class="code">
<pre>
MSDOS &gt; tclsh80
% load example.dll
% fact 4
24
%
</pre>
</div>
<h3><a name="Tcl_nn13">36.2.2 Using NMAKE</a></h3>
<p> Alternatively, SWIG extensions can be built by writing a Makefile
 for NMAKE. To do this, make sure the environment variables for MSVC++
 are available and the MSVC++ tools are in your path. Now, just write a
 short Makefile like this :</p>
<div class="code">
<pre>
# Makefile for building various SWIG generated extensions

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
TCL_INCLUDES  = -Id:\tcl8.0a2\generic -Id:\tcl8.0a2\win
TCLLIB        = d:\tcl8.0a2\win\tcl80.lib

tcl:
        ..\..\swig -tcl -o $(WRAPFILE) $(INTERFACE)
        $(CC) $(CFLAGS) $(TCL_INCLUDES) $(SRCS) $(WRAPFILE)
        set LIB=$(TOOLS)\lib
        $(LINK) $(LOPT) -out:example.dll $(LIBS) $(TCLLIB) example.obj example_wrap.obj

</pre>
</div>
<p> To build the extension, run NMAKE (you may need to run vcvars32
 first). This is a pretty minimal Makefile, but hopefully its enough to
 get you started. With a little practice, you'll be making lots of Tcl
 extensions.</p>
<h2><a name="Tcl_nn14">36.3 A tour of basic C/C++ wrapping</a></h2>
<p> By default, SWIG tries to build a very natural Tcl interface to your
 C/C++ code. Functions are wrapped as functions, classes are wrapped in
 an interface that mimics the style of Tk widgets and [incr Tcl]
 classes. This section briefly covers the essential aspects of this
 wrapping.</p>
<h3><a name="Tcl_nn15">36.3.1 Modules</a></h3>
<p> The SWIG <tt>%module</tt> directive specifies the name of the Tcl
 module. If you specify `<tt>%module example</tt>', then everything is
 compiled into an extension module <tt>example.so</tt>. When choosing a
 module name, make sure you don't use the same name as a built-in Tcl
 command.</p>
<p> One pitfall to watch out for is module names involving numbers. If
 you specify a module name like <tt>%module md5</tt>, you'll find that
 the load command no longer seems to work:</p>
<div class="code">
<pre>
% load ./md5.so
couldn't find procedure Md_Init
</pre>
</div>
<p> To fix this, supply an extra argument to <tt>load</tt> like this:</p>
<div class="code">
<pre>
% load ./md5.so md5
</pre>
</div>
<h3><a name="Tcl_nn16">36.3.2 Functions</a></h3>
<p> Global functions are wrapped as new Tcl built-in commands. For
 example,</p>
<div class="code">
<pre>
%module example
int fact(int n);
</pre>
</div>
<p> creates a built-in function <tt>fact</tt> that works exactly like
 you think it does:</p>
<div class="code">
<pre>
% load ./example.so
% fact 4
24
% set x [fact 6]
%
</pre>
</div>
<h3><a name="Tcl_nn17">36.3.3 Global variables</a></h3>
<p> C/C++ global variables are wrapped by Tcl global variables. For
 example:</p>
<div class="code">
<pre>
// SWIG interface file with global variables
%module example
...
%inline %{
extern double density;
%}
...
</pre>
</div>
<p> Now look at the Tcl interface:</p>
<div class="code">
<pre>
% puts $density          # Output value of C global variable
1.0
% set density 0.95       # Change value
</pre>
</div>
<p> If you make an error in variable assignment, you will get an error
 message. For example:</p>
<div class="code">
<pre>
% set density &quot;hello&quot;
can't set &quot;density&quot;: Type error. expected a double.
%
</pre>
</div>
<p> If a variable is declared as <tt>const</tt>, it is wrapped as a
 read-only variable. Attempts to modify its value will result in an
 error.</p>
<p> To make ordinary variables read-only, you can use the <tt>%immutable</tt>
 directive. For example:</p>
<div class="code">
<pre>
%{
extern char *path;
%}
%immutable;
extern char *path;
%mutable;
</pre>
</div>
<p> The <tt>%immutable</tt> directive stays in effect until it is
 explicitly disabled or cleared using <tt>%mutable</tt>. See the <a href="#SWIG_readonly_variables">
Creating read-only variables</a> section for further details.</p>
<p> If you just want to make a specific variable immutable, supply a
 declaration name. For example:</p>
<div class="code">
<pre>
%{
extern char *path;
%}
%immutable path;
...
extern char *path;      // Read-only (due to %immutable)
</pre>
</div>
<h3><a name="Tcl_nn18">36.3.4 Constants and enums</a></h3>
<p> C/C++ constants are installed as global Tcl variables containing the
 appropriate value. To create a constant, use <tt>#define</tt>, <tt>enum</tt>
, or the <tt>%constant</tt> directive. For example:</p>
<div class="code">
<pre>
#define PI 3.14159
#define VERSION &quot;1.0&quot;

enum Beverage { ALE, LAGER, STOUT, PILSNER };

%constant int FOO = 42;
%constant const char *path = &quot;/usr/local&quot;;
</pre>
</div>
<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
 stick an enum in a SWIG interface without also telling the C compiler
 about it, the wrapper code won't compile.</p>
<p> Note: declarations declared as <tt>const</tt> are wrapped as
 read-only variables and will be accessed using the <tt>cvar</tt> object
 described in the previous section. They are not wrapped as constants.
 For further discussion about this, see the <a href="#SWIG">SWIG Basics</a>
 chapter.</p>
<p> Constants are not guaranteed to remain constant in Tcl---the value
 of the constant could be accidentally reassigned.You will just have to
 be careful.</p>
<p> A peculiarity of installing constants as variables is that it is
 necessary to use the Tcl <tt>global</tt> statement to access constants
 in procedure bodies. For example:</p>
<div class="code">
<pre>
proc blah {} {
  global FOO
  bar $FOO
}
</pre>
</div>
<p> If a program relies on a lot of constants, this can be extremely
 annoying. To fix the problem, consider using the following typemap
 rule:</p>
<div class="code">
<pre>
%apply int CONSTANT { int x };
#define FOO 42
...
void bar(int x);
</pre>
</div>
<p> When applied to an input argument, the <tt>CONSTANT</tt> rule allows
 a constant to be passed to a function using its actual value or a
 symbolic identifier name. For example:</p>
<div class="code">
<pre>
proc blah {} {
  bar FOO
}
</pre>
</div>
<p> When an identifier name is given, it is used to perform an implicit
 hash-table lookup of the value during argument conversion. This allows
 the <tt>global</tt> statement to be omitted.</p>
<h3><a name="Tcl_nn19">36.3.5 Pointers</a></h3>
<p> C/C++ pointers are fully supported by SWIG. Furthermore, SWIG has no
 problem working with incomplete type information. Here is a rather
 simple interface:</p>
<div class="code">
<pre>
%module example

FILE *fopen(const char *filename, const char *mode);
int fputs(const char *, FILE *);
int fclose(FILE *);
</pre>
</div>
<p> When wrapped, you will be able to use the functions in a natural way
 from Tcl. For example:</p>
<div class="code">
<pre>
% load ./example.so
% set f [fopen junk w]
% fputs &quot;Hello World\n&quot; $f
% fclose $f
</pre>
</div>
<p> If this makes you uneasy, rest assured that there is no deep magic
 involved. Underneath the covers, pointers to C/C++ objects are simply
 represented as opaque values--normally an encoded character string like
 this:</p>
<div class="code">
<pre>
% puts $f
_c0671108_p_FILE
% 
</pre>
</div>
<p> This pointer value can be freely passed around to different C
 functions that expect to receive an object of type <tt>FILE *</tt>. The
 only thing you can't do is dereference the pointer from Tcl.</p>
<p> The NULL pointer is represented by the string <tt>NULL</tt>.</p>
<p> As much as you might be inclined to modify a pointer value directly
 from Tcl, don't. The hexadecimal encoding is not necessarily the same
 as the logical memory address of the underlying object. Instead it is
 the raw byte encoding of the pointer value. The encoding will vary
 depending on the native byte-ordering of the platform (i.e., big-endian
 vs. little-endian). Similarly, don't try to manually cast a pointer to
 a new type by simply replacing the type-string. This may not work like
 you expect and it is particularly dangerous when casting C++ objects.
 If you need to cast a pointer or change its value, consider writing
 some helper functions instead. For example:</p>
<div class="code">
<pre>
%inline %{
/* C-style cast */
Bar *FooToBar(Foo *f) {
  return (Bar *) f;
}

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

Foo *IncrFoo(Foo *f, int i) {
  return f+i;
}
%}
</pre>
</div>
<p> Also, if working with C++, you should always try to use the new C++
 style casts. For example, in the above code, the C-style cast may
 return a bogus result whereas as the C++-style cast will return <tt>
None</tt> if the conversion can't be performed.</p>
<h3><a name="Tcl_nn20">36.3.6 Structures</a></h3>
<p> If you wrap a C structure, it is wrapped by a Tcl interface that
 somewhat resembles a Tk widget. This provides a very natural interface.
 For example,</p>
<div class="code">
<pre>
struct Vector {
  double x, y, z;
};

</pre>
</div>
<p> is used as follows:</p>
<div class="code">
<pre>
% Vector v
% v configure -x 3.5 -y 7.2
% puts &quot;[v cget -x] [v cget -y] [v cget -z]&quot;
3.5 7.2 0.0
% 
</pre>
</div>
<p> Similar access is provided for unions and the data members of C++
 classes.</p>
<p> In the above example, <tt>v</tt> is a name that's used for the
 object. However, underneath the covers, there's a pointer to a raw C
 structure. This can be obtained by looking at the <tt>-this</tt>
 attribute. For example:</p>
<div class="code">
<pre>
% puts [v cget -this]
_88e31408_p_Vector
</pre>
</div>
<p> Further details about the relationship between the Tcl and the
 underlying C structure are covered a little later.</p>
<p> <tt>const</tt> members of a structure are read-only. Data members
 can also be forced to be read-only using the <tt>%immutable</tt>
 directive. For example:</p>
<div class="code">
<pre>
struct Foo {
  ...
  %immutable;
  int x;        /* Read-only members */
  char *name;
  %mutable;
  ...
};
</pre>
</div>
<p> When <tt>char *</tt> members of a structure are wrapped, the
 contents are assumed to be dynamically allocated using <tt>malloc</tt>
 or <tt>new</tt> (depending on whether or not SWIG is run with the -c++
 option). When the structure member is set, the old contents will be
 released and a new value created. If this is not the behavior you want,
 you will have to use a typemap (described later).</p>
<p> If a structure contains arrays, access to those arrays is managed
 through pointers. For example, consider this:</p>
<div class="code">
<pre>
struct Bar {
  int  x[16];
};
</pre>
</div>
<p> If accessed in Tcl, you will see behavior like this:</p>
<div class="code">
<pre>
% Bar b
% puts [b cget -x]
_801861a4_p_int
% 
</pre>
</div>
<p> This pointer can be passed around to functions that expect to
 receive an <tt>int *</tt> (just like C). You can also set the value of
 an array member using another pointer. For example:</p>
<div class="code">
<pre>
% Bar c
% c configure -x [b cget -x]   # Copy contents of b.x to c.x
</pre>
</div>
<p> For array assignment, 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.</p>
<p> When a member of a structure is itself a structure, it is handled as
 a pointer. For example, suppose you have two structures like this:</p>
<div class="code">
<pre>
struct Foo {
  int a;
};

struct Bar {
  Foo f;
};
</pre>
</div>
<p> Now, suppose that you access the <tt>f</tt> attribute of <tt>Bar</tt>
 like this:</p>
<div class="code">
<pre>
% Bar b
% set x [b cget -f]
</pre>
</div>
<p> In this case, <tt>x</tt> is a pointer that points to the <tt>Foo</tt>
 that is inside <tt>b</tt>. This is the same value as generated by this
 C code:</p>
<div class="code">
<pre>
Bar b;
Foo *x = &amp;b-&gt;f;       /* Points inside b */
</pre>
</div>
<p> However, one peculiarity of accessing a substructure like this is
 that the returned value does work quite like you might expect. For
 example:</p>
<div class="code">
<pre>
% Bar b
% set x [b cget -f]
% x cget -a
invalid command name &quot;x&quot;
</pre>
</div>
<p> This is because the returned value was not created in a normal way
 from the interpreter (x is not a command object). To make it function
 normally, just evaluate the variable like this:</p>
<div class="code">
<pre>
% Bar b
% set x [b cget -f]
% $x cget -a
0
%
</pre>
</div>
<p> In this example, <tt>x</tt> points inside the original structure.
 This means that modifications work just like you would expect. For
 example:</p>
<div class="code">
<pre>

% Bar b
% set x [b cget -f]
% $x configure -a 3            # Modifies contents of f (inside b)
% [b cget -f] -configure -a 3  # Same thing
</pre>
</div>
<p> In many of these structure examples, a simple name like &quot;v&quot; or &quot;b&quot;
 has been given to wrapped structures. If necessary, this name can be
 passed to functions that expect to receive an object. For example, if
 you have a function like this,</p>
<div class="code">
<pre>
void blah(Foo *f);
</pre>
</div>
<p> you can call the function in Tcl as follows:</p>
<div class="code">
<pre>
% Foo x            # Create a Foo object 
% blah x           # Pass the object to a function
</pre>
</div>
<p> It is also possible to call the function using the raw pointer
 value. For instance:</p>
<div class="code">
<pre>
% blah [x cget -this]   # Pass object to a function
</pre>
</div>
<p> It is also possible to create and use objects using variables. For
 example:</p>
<div class="code">
<pre>
% set b [Bar]            # Create a Bar
% $b cget -f             # Member access
% puts $b
_108fea88_p_Bar
%
</pre>
</div>
<p> Finally, to destroy objects created from Tcl, you can either let the
 object name go out of scope or you can explicitly delete the object.
 For example:</p>
<div class="code">
<pre>
% Foo f                 # Create object f
% rename f &quot;&quot;
</pre>
</div>
<p> or</p>
<div class="code">
<pre>
% Foo f                 # Create object f
% f -delete
</pre>
</div>
<p> Note: Tcl only destroys the underlying object if it has ownership.
 See the memory management section that appears shortly.</p>
<h3><a name="Tcl_nn21">36.3.7 C++ classes</a></h3>
<p> C++ classes are wrapped as an extension of structure wrapping. For
 example, if you have this class,</p>
<div class="code">
<pre>
class List {
public:
  List();
  ~List();
  int  search(char *item);
  void insert(char *item);
  void remove(char *item);
  char *get(int n);
  int  length;
};
</pre>
</div>
<p> you can use it in Tcl like this:</p>
<div class="code">
<pre>
% List x
% x insert Ale
% x insert Stout
% x insert Lager
% x get 1
Stout
% puts [x cget -length]
3
%
</pre>
</div>
<p> Class data members are accessed in the same manner as C structures.</p>
<p> Static class members are accessed as global functions or variables.
 To illustrate, suppose you have a class like this:</p>
<div class="code">
<pre>
class Spam {
public:
  static void foo();
  static int bar;
};
</pre>
</div>
<p> In Tcl, the static member is accessed as follows:</p>
<div class="code">
<pre>
% Spam_foo        # Spam::foo()
% puts $Spam_bar  # Spam::bar
</pre>
</div>
<h3><a name="Tcl_nn22">36.3.8 C++ inheritance</a></h3>
<p> SWIG is fully aware of issues related to C++ inheritance. Therefore,
 if you have classes like this</p>
<div class="code">
<pre>
class Foo {
...
};

class Bar : public Foo {
...
};
</pre>
</div>
<p> An object of type <tt>Bar</tt> can be used where a <tt>Foo</tt> is
 expected. For example, if you have this function:</p>
<div class="code">
<pre>
void spam(Foo *f);
</pre>
</div>
<p> then the function <tt>spam()</tt> accepts a <tt>Foo *</tt> or a
 pointer to any class derived from <tt>Foo</tt>. For instance:</p>
<div class="code">
<pre>
% Foo f      # Create a Foo
% Bar b      # Create a Bar
% spam f     # OK
% spam b     # OK
</pre>
</div>
<p> It is safe to use multiple inheritance with SWIG.</p>
<h3><a name="Tcl_nn23">36.3.9 Pointers, references, values, and arrays</a>
</h3>
<p> In C++, there are many different ways a function might receive and
 manipulate objects. For example:</p>
<div class="code">
<pre>
void spam1(Foo *x);      // Pass by pointer
void spam2(Foo &amp;x);      // Pass by reference
void spam3(Foo x);       // Pass by value
void spam4(Foo x[]);     // Array of objects
</pre>
</div>
<p> In Tcl, there is no detailed distinction like this. 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:</p>
<div class="code">
<pre>
% Foo f             # Create a Foo
% spam1 f           # Ok. Pointer
% spam2 f           # Ok. Reference
% spam3 f           # Ok. Value.
% spam4 f           # Ok. Array (1 element)
</pre>
</div>
<p> Similar behavior occurs for return values. For example, if you had
 functions like this,</p>
<div class="code">
<pre>
Foo *spam5();
Foo &amp;spam6();
Foo  spam7();
</pre>
</div>
<p> then all three functions will return a pointer to some <tt>Foo</tt>
 object. Since the third function (spam7) returns a value, newly
 allocated memory is used to hold the result and a pointer is returned
 (Tcl will release this memory when the return value is garbage
 collected).</p>
<h3><a name="Tcl_nn24">36.3.10 C++ overloaded functions</a></h3>
<p> C++ overloaded functions, methods, and constructors are mostly
 supported by SWIG. For example, if you have two functions like this:</p>
<div class="code">
<pre>
void foo(int);
void foo(char *c);
</pre>
</div>
<p> You can use them in Tcl in a straightforward manner:</p>
<div class="code">
<pre>
% foo 3            # foo(int)
% foo Hello        # foo(char *c)
</pre>
</div>
<p> Similarly, if you have a class like this,</p>
<div class="code">
<pre>
class Foo {
public:
  Foo();
  Foo(const Foo &amp;);
  ...
};
</pre>
</div>
<p> you can write Tcl code like this:</p>
<div class="code">
<pre>
% Foo f                # Create a Foo
% Foo g f              # Copy f
</pre>
</div>
<p> Overloading support is not quite as flexible as in C++. Sometimes
 there are methods that SWIG can't disambiguate. For example:</p>
<div class="code">
<pre>
void spam(int);
void spam(short);
</pre>
</div>
<p> or</p>
<div class="code">
<pre>
void foo(Bar *b);
void foo(Bar &amp;b);
</pre>
</div>
<p> If declarations such as these appear, you will get a warning message
 like this:</p>
<div class="code">
<pre>
example.i:12: Warning 509: Overloaded method spam(short) effectively ignored,
example.i:11: Warning 509: as it is shadowed by spam(int).
</pre>
</div>
<p> To fix this, you either need to ignore or rename one of the methods.
 For example:</p>
<div class="code">
<pre>
%rename(spam_short) spam(short);
...
void spam(int);    
void spam(short);   // Accessed as spam_short
</pre>
</div>
<p> or</p>
<div class="code">
<pre>
%ignore spam(short);
...
void spam(int);    
void spam(short);   // Ignored
</pre>
</div>
<p> SWIG resolves overloaded functions and methods using a
 disambiguation scheme that ranks and sorts declarations according to a
 set of type-precedence rules. The order in which declarations appear in
 the input does not matter except in situations where ambiguity
 arises--in this case, the first declaration takes precedence.</p>
<p> Please refer to the &quot;SWIG and C++&quot; chapter for more information
 about overloading.</p>
<h3><a name="Tcl_nn25">36.3.11 C++ operators</a></h3>
<p> Certain C++ overloaded operators can be handled automatically by
 SWIG. For example, consider a class like this:</p>
<div class="code">
<pre>
class Complex {
private:
  double rpart, ipart;
public:
  Complex(double r = 0, double i = 0) : rpart(r), ipart(i) { }
  Complex(const Complex &amp;c) : rpart(c.rpart), ipart(c.ipart) { }
  Complex &amp;operator=(const Complex &amp;c);
  Complex operator+(const Complex &amp;c) const;
  Complex operator-(const Complex &amp;c) const;
  Complex operator*(const Complex &amp;c) const;
  Complex operator-() const;
  
  double re() const { return rpart; }
  double im() const { return ipart; }
};
</pre>
</div>
<p> When wrapped, it works like this:</p>
<div class="code">
<pre>
% Complex c 3 4
% Complex d 7 8
% set e [c + d]
% $e re
10.0
% $e im
12.0
</pre>
</div>
<p> It should be stressed that operators in SWIG have no relationship to
 operators in Tcl. In fact, the only thing that's happening here is that
 an operator like <tt>operator +</tt> has been renamed to a method <tt>+</tt>
. Therefore, the statement <tt>[c + d]</tt> is really just invoking the <tt>
+</tt> method on <tt>c</tt>. When more than operator is defined (with
 different arguments), the standard method overloading facilities are
 used. Here is a rather odd looking example:</p>
<div class="code">
<pre>
% Complex c 3 4
% Complex d 7 8
% set e [c - d]       # operator-(const Complex &amp;)
% puts &quot;[$e re] [$e im]&quot;
10.0 12.0
% set f [c -]         # operator-()
% puts &quot;[$f re] [$f im]&quot;
-3.0 -4.0
%
</pre>
</div>
<p> One restriction with operator overloading support is that SWIG is
 not able to fully handle operators that aren't defined as part of the
 class. For example, if you had code like this</p>
<div class="code">
<pre>
class Complex {
...
friend Complex operator+(double, const Complex &amp;c);
...
};
</pre>
</div>
<p> then SWIG doesn't know what to do with the friend function--in fact,
 it simply ignores it and issues a warning. You can still wrap the
 operator, but you may have to encapsulate it in a special function. For
 example:</p>
<div class="code">
<pre>
%rename(Complex_add_dc) operator+(double, const Complex &amp;);
...
Complex operator+(double, const Complex &amp;c);
</pre>
</div>
<p> There are ways to make this operator appear as part of the class
 using the <tt>%extend</tt> directive. Keep reading.</p>
<h3><a name="Tcl_nn26">36.3.12 C++ namespaces</a></h3>
<p> 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,</p>
<div class="code">
<pre>
%module example

namespace foo {
  int fact(int n);
  struct Vector {
    double x, y, z;
  };
};
</pre>
</div>
<p> it works in Tcl as follows:</p>
<div class="code">
<pre>
% load ./example.so
% fact 3
6
% Vector v
% v configure -x 3.4
</pre>
</div>
<p> If your program has more than one namespace, name conflicts (if any)
 can be resolved using <tt>%rename</tt> For example:</p>
<div class="code">
<pre>
%rename(Bar_spam) Bar::spam;

namespace Foo {
  int spam();
}

namespace Bar {
  int spam();
}
</pre>
</div>
<p> If you have more than one namespace and your want to keep their
 symbols separate, consider wrapping them as separate SWIG modules. For
 example, make the module name the same as the namespace and create
 extension modules for each namespace separately. If your program
 utilizes thousands of small deeply nested namespaces each with
 identical symbol names, well, then you get what you deserve.</p>
<h3><a name="Tcl_nn27">36.3.13 C++ templates</a></h3>
<p> C++ templates don't present a huge problem for SWIG. However, in
 order to create wrappers, you have to tell SWIG to create wrappers for
 a particular template instantiation. To do this, you use the <tt>
%template</tt> directive. For example:</p>
<div class="code">
<pre>
%module example
%{
#include &quot;pair.h&quot;
%}

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

%template(pairii) pair&lt;int, int&gt;;
</pre>
</div>
<p> In Tcl:</p>
<div class="code">
<pre>
% pairii p 3 4
% p cget -first
3
% p cget -second
4
</pre>
</div>
<p> Obviously, there is more to template wrapping than shown in this
 example. More details can be found in the <a href="#SWIGPlus">SWIG and
 C++</a> chapter. Some more complicated examples will appear later.</p>
<h3><a name="Tcl_nn28">36.3.14 C++ Smart Pointers</a></h3>
<p> In certain C++ programs, it is common to use classes that have been
 wrapped by so-called &quot;smart pointers.&quot; Generally, this involves the use
 of a template class that implements <tt>operator-&gt;()</tt> like this:</p>
<div class="code">
<pre>
template&lt;class T&gt; class SmartPtr {
  ...
  T *operator-&gt;();
  ...
}
</pre>
</div>
<p> Then, if you have a class like this,</p>
<div class="code">
<pre>
class Foo {
public:
  int x;
  int bar();
};
</pre>
</div>
<p> A smart pointer would be used in C++ as follows:</p>
<div class="code">
<pre>
SmartPtr&lt;Foo&gt; p = CreateFoo();   // Created somehow (not shown)
...
p-&gt;x = 3;                        // Foo::x
int y = p-&gt;bar();                // Foo::bar
</pre>
</div>
<p> To wrap this in Tcl, simply tell SWIG about the <tt>SmartPtr</tt>
 class and the low-level <tt>Foo</tt> object. Make sure you instantiate <tt>
SmartPtr</tt> using <tt>%template</tt> if necessary. For example:</p>
<div class="code">
<pre>
%module example
...
%template(SmartPtrFoo) SmartPtr&lt;Foo&gt;;
...
</pre>
</div>
<p> Now, in Tcl, everything should just &quot;work&quot;:</p>
<div class="code">
<pre>
% set p [CreateFoo]                  # Create a smart-pointer somehow
% $p configure -x 3                  # Foo::x
% $p bar                             # Foo::bar
</pre>
</div>
<p> If you ever need to access the underlying pointer returned by <tt>
operator-&gt;()</tt> itself, simply use the <tt>__deref__()</tt> method.
 For example:</p>
<div class="code">
<pre>
% set f [$p __deref__]    # Returns underlying Foo *
</pre>
</div>
<h2><a name="Tcl_nn29">36.4 Further details on the Tcl class interface</a>
</h2>
<p> In the previous section, a high-level view of Tcl wrapping was
 presented. A key component of this wrapping is that structures and
 classes are wrapped by Tcl class-like objects. This provides a very
 natural Tcl interface and allows SWIG to support a number of advanced
 features such as operator overloading. However, a number of low-level
 details were omitted. This section provides a brief overview of how the
 proxy classes work.</p>
<h3><a name="Tcl_nn30">36.4.1 Proxy classes</a></h3>
<p> In the <a href="#SWIG">&quot;SWIG basics&quot;</a> and <a href="#SWIGPlus">
&quot;SWIG and C++&quot;</a> chapters, details of low-level structure and class
 wrapping are described. To summarize those chapters, if you have a
 class like this</p>
<div class="code">
<pre>
class Foo {
public:
  int x;
  int spam(int);
  ...
</pre>
</div>
<p> then SWIG transforms it into a set of low-level procedural wrappers.
 For example:</p>
<div class="code">
<pre>
Foo *new_Foo() {
  return new Foo();
}
void delete_Foo(Foo *f) {
  delete f;
}
int Foo_x_get(Foo *f) {
  return f-&gt;x;
}
void Foo_x_set(Foo *f, int value) {
  f-&gt;x = value;
}
int Foo_spam(Foo *f, int arg1) {
  return f-&gt;spam(arg1);
}
</pre>
</div>
<p> These wrappers are actually found in the Tcl extension module. For
 example, you can certainly do this:</p>
<div class="code">
<pre>
% load ./example.so
% set f [new_Foo]
% Foo_x_get $f
0
% Foo_spam $f 3
1
%
</pre>
</div>
<p> However, in addition to this, the classname <tt>Foo</tt> is used as
 an object constructor function. This allows objects to be encapsulated
 objects that look a lot like Tk widgets as shown in the last section.</p>
<h3><a name="Tcl_nn31">36.4.2 Memory management</a></h3>
<p> Associated with each wrapped object, is an ownership flag <tt>
thisown</tt> The value of this flag determines who is responsible for
 deleting the underlying C++ object. If set to 1, the Tcl interpreter
 destroys the C++ object when the proxy class is garbage collected. If
 set to 0 (or if the attribute is missing), then the destruction of the
 proxy class has no effect on the C++ object.</p>
<p> When an object is created by a constructor or returned by value, Tcl
 automatically takes ownership of the result. For example:</p>
<div class="code">
<pre>
class Foo {
public:
  Foo();
  Foo bar();
};
</pre>
</div>
<p> In Tcl:</p>
<div class="code">
<pre>
% Foo f
% f cget -thisown
1
% set g [f bar]
% $g cget -thisown
1
</pre>
</div>
<p> On the other hand, when pointers are returned to Tcl, there is often
 no way to know where they came from. Therefore, the ownership is set to
 zero. For example:</p>
<div class="code">
<pre>
class Foo {
public:
  ...
  Foo *spam();
  ...
};
</pre>
</div>
<br><div class="code">
<pre>
% Foo f
% set s [f spam]
% $s cget -thisown
0
% 
</pre>
</div>
<p> This behavior 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 Tcl
 to assume ownership and destroy it!</p>
<p> Related to containers, ownership issues can arise whenever an object
 is assigned to a member or global variable. For example, consider this
 interface:</p>
<div class="code">
<pre>
%module example

struct Foo {
  int  value;
  Foo  *next;
};

Foo *head = 0;
</pre>
</div>
<p> When wrapped in Tcl, careful observation will reveal that ownership
 changes whenever an object is assigned to a global variable. For
 example:</p>
<div class="code">
<pre>
% Foo f
% f cget -thisown
1
% set head f
% f cget -thisown
0
</pre>
</div>
<p> In this case, C is now holding a reference to the object---you
 probably don't want Tcl to destroy it. Similarly, this occurs for
 members. For example:</p>
<div class="code">
<pre>
% Foo f
% Foo g
% f cget -thisown
1
% g cget -thisown
1
% f configure -next g
% g cget -thisown 
0
%
</pre>
</div>
<p> For the most part, memory management issues remain hidden. However,
 there are occasionally situations where you might have to manually
 change the ownership of an object. For instance, consider code like
 this:</p>
<div class="code">
<pre>
class Node {
  Object *value;
public:
  void set_value(Object *v) { value = v; }
  ...
};
</pre>
</div>
<p> Now, consider the following Tcl code:</p>
<div class="code">
<pre>
% Object v                 # Create an object
% Node n                   # Create a node
% n setvalue v             # Set value
% v cget -thisown
1
% 
</pre>
</div>
<p> In this case, the object <tt>n</tt> is holding a reference to <tt>v</tt>
 internally. However, SWIG has no way to know that this has occurred.
 Therefore, Tcl still thinks that it has ownership of the object. Should
 the proxy object be destroyed, then the C++ destructor will be invoked
 and <tt>n</tt> will be holding a stale-pointer. If you're lucky, you
 will only get a segmentation fault.</p>
<p> To work around this, it is always possible to flip the ownership
 flag. For example,</p>
<div class="code">
<pre>
% v -disown              # Give ownership to C/C++
% v -acquire             # Acquire ownership
</pre>
</div>
<p> It is also possible to deal with situations like this using
 typemaps--an advanced topic discussed later.</p>
<h2><a name="Tcl_nn32">36.5 Input and output parameters</a></h2>
<p> A common problem in some C programs is handling parameters passed as
 simple pointers. For example:</p>
<div class="code">
<pre>
void add(int x, int y, int *result) {
  *result = x + y;
}
</pre>
</div>
<p> or perhaps</p>
<div class="code">
<pre>
int sub(int *x, int *y) {
  return *x+*y;
}
</pre>
</div>
<p> The easiest way to handle these situations is to use the <tt>
typemaps.i</tt> file. For example:</p>
<div class="code">
<pre>
%module example
%include &quot;typemaps.i&quot;

void add(int, int, int *OUTPUT);
int  sub(int *INPUT, int *INPUT);
</pre>
</div>
<p> In Tcl, this allows you to pass simple values instead of pointer.
 For example:</p>
<div class="code">
<pre>
set a [add 3 4]
puts $a
7
</pre>
</div>
<p> Notice how the <tt>INPUT</tt> parameters allow integer values to be
 passed instead of pointers and how the <tt>OUTPUT</tt> parameter
 creates a return result.</p>
<p> If you don't want to use the names <tt>INPUT</tt> or <tt>OUTPUT</tt>
, use the <tt>%apply</tt> directive. For example:</p>
<div class="code">
<pre>
%module example
%include &quot;typemaps.i&quot;

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

void add(int x, int y, int *result);
int  sub(int *x, int *y);
</pre>
</div>
<p> If a function mutates one of its parameters like this,</p>
<div class="code">
<pre>
void negate(int *x) {
  *x = -(*x);
}
</pre>
</div>
<p> you can use <tt>INOUT</tt> like this:</p>
<div class="code">
<pre>
%include &quot;typemaps.i&quot;
...
void negate(int *INOUT);
</pre>
</div>
<p> In Tcl, a mutated parameter shows up as a return value. For example:</p>
<div class="code">
<pre>
set a [negate 3]
puts $a
-3
</pre>
</div>
<p> The most common use of these special typemap rules is to handle
 functions that return more than one value. For example, sometimes a
 function returns a result as well as a special error code:</p>
<div class="code">
<pre>
/* send message, return number of bytes sent, along with success code */
int send_message(char *text, int len, int *success);
</pre>
</div>
<p> To wrap such a function, simply use the <tt>OUTPUT</tt> rule above.
 For example:</p>
<div class="code">
<pre>
%module example
%include &quot;typemaps.i&quot;
%apply int *OUTPUT { int *success };
...
int send_message(char *text, int *success);
</pre>
</div>
<p> When used in Tcl, the function will return multiple values as a
 list.</p>
<div class="code">
<pre>
set r [send_message &quot;Hello World&quot;]
set bytes [lindex $r 0]
set success [lindex $r 1]
</pre>
</div>
<p> Another common use of multiple return values are in query functions.
 For example:</p>
<div class="code">
<pre>
void get_dimensions(Matrix *m, int *rows, int *columns);
</pre>
</div>
<p> To wrap this, you might use the following:</p>
<div class="code">
<pre>
%module example
%include &quot;typemaps.i&quot;
%apply int *OUTPUT { int *rows, int *columns };
...
void get_dimensions(Matrix *m, int *rows, *columns);
</pre>
</div>
<p> Now, in Perl:</p>
<div class="code">
<pre>
set dim [get_dimensions $m]
set r  [lindex $dim 0]
set c  [lindex $dim 1]
</pre>
</div>
<h2><a name="Tcl_nn33">36.6 Exception handling</a></h2>
<p> The <tt>%exception</tt> directive can be used to create a
 user-definable exception handler in charge of converting exceptions in
 your C/C++ program into Tcl exceptions. The chapter on customization
 features contains more details, but suppose you extended the array
 example into a C++ class like the following :</p>
<div class="code">
<pre>
class RangeError {};   // Used for an exception

class DoubleArray {
  private:
    int n;
    double *ptr;
  public:
    // Create a new array of fixed size
    DoubleArray(int size) {
      ptr = new double[size];
      n = size;
    }
    // Destroy an array
    ~DoubleArray() {
      delete ptr;
    }
    // Return the length of the array
    int   length() {
      return n;
    }

    // Get an item from the array and perform bounds checking.
    double getitem(int i) {
      if ((i &gt;= 0) &amp;&amp; (i &lt; n))
        return ptr[i];
      else
        throw RangeError();
    }

    // Set an item in the array and perform bounds checking.
    void setitem(int i, double val) {
      if ((i &gt;= 0) &amp;&amp; (i &lt; n))
        ptr[i] = val;
      else {
        throw RangeError();
      }
    }
  };
</pre>
</div>
<p> The functions associated with this class can throw a C++ range
 exception for an out-of-bounds array access. We can catch this in our
 Tcl extension by specifying the following in an interface file :</p>
<div class="code">
<pre>
%exception {
  try {
    $action                // Gets substituted by actual function call
  }
  catch (RangeError) {
    Tcl_SetResult(interp, (char *)&quot;Array index out-of-bounds&quot;, TCL_STATIC);
    return TCL_ERROR;
  }
}
</pre>
</div>
<p> As shown, the exception handling code will be added to every wrapper
 function. Since this is somewhat inefficient. You might consider
 refining the exception handler to only apply to specific methods like
 this:</p>
<div class="code">
<pre>
%exception getitem {
  try {
    $action
  }
  catch (RangeError) {
    Tcl_SetResult(interp, (char *)&quot;Array index out-of-bounds&quot;, TCL_STATIC);
    return TCL_ERROR;
  }
}

%exception setitem {
  try {
    $action
  }
  catch (RangeError) {
    Tcl_SetResult(interp, (char *)&quot;Array index out-of-bounds&quot;, TCL_STATIC);
    return TCL_ERROR;
  }
}
</pre>
</div>
<p> In this case, the exception handler is only attached to methods and
 functions named <tt>getitem</tt> and <tt>setitem</tt>.</p>
<p> If you had a lot of different methods, you can avoid extra typing by
 using a macro. For example:</p>
<div class="code">
<pre>
%define RANGE_ERROR
{
  try {
    $action
  }
  catch (RangeError) {
    Tcl_SetResult(interp, (char *)&quot;Array index out-of-bounds&quot;, TCL_STATIC);
    return TCL_ERROR;
  }
}
%enddef

%exception getitem RANGE_ERROR;
%exception setitem RANGE_ERROR;
</pre>
</div>
<p> Since SWIG's exception handling is user-definable, you are not
 limited to C++ exception handling. See the chapter on &quot;<a href="#Customization">
Customization Features</a>&quot; for more examples.</p>
<h2><a name="Tcl_nn34">36.7 Typemaps</a></h2>
<p> This section describes how you can modify SWIG's default wrapping
 behavior for various C/C++ datatypes using the <tt>%typemap</tt>
 directive. This is an advanced topic that assumes familiarity with the
 Tcl C API as well as the material in the &quot;<a href="#Typemaps">Typemaps</a>
&quot; chapter.</p>
<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 primitive C-Tcl interface.</p>
<h3><a name="Tcl_nn35">36.7.1 What is a typemap?</a></h3>
<p> A typemap is nothing more than a code generation rule that is
 attached to a specific C datatype. For example, to convert integers
 from Tcl to C, you might define a typemap like this:</p>
<div class="code">
<pre>
%module example

%typemap(in) int {
  if (Tcl_GetIntFromObj(interp, $input, &amp;$1) == TCL_ERROR)
    return TCL_ERROR;
  printf(&quot;Received an integer : %d\n&quot;, $1);
}
%inline %{
extern int fact(int n);
%}
</pre>
</div>
<p> Typemaps are always associated with some specific aspect of code
 generation. In this case, the &quot;in&quot; 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 variable prefaced by a
 <tt>$</tt> are used. The <tt>$1</tt> variable is placeholder for a
 local variable of type <tt>int</tt>. The <tt>$input</tt> variable is
 the input object of type <tt>Tcl_Obj *</tt>.</p>
<p> When this example is compiled into a Tcl module, it operates as
 follows:</p>
<div class="code">
<pre>
% load ./example.so
% fact 6
Received an integer : 6
720
</pre>
</div>
<p> In this example, the typemap is applied to all occurrences of the <tt>
int</tt> datatype. You can refine this by supplying an optional
 parameter name. For example:</p>
<div class="code">
<pre>
%module example

%typemap(in) int n {
  if (Tcl_GetIntFromObj(interp, $input, &amp;$1) == TCL_ERROR)
    return TCL_ERROR;
  printf(&quot;n = %d\n&quot;, $1);
}
%inline %{
extern int fact(int n);
%}
</pre>
</div>
<p> In this case, the typemap code is only attached to arguments that
 exactly match <tt>int n</tt>.</p>
<p> The application of a typemap to specific datatypes and argument
 names involves more than simple text-matching--typemaps are fully
 integrated into the SWIG type-system. When you define a typemap for <tt>
int</tt>, that typemap applies to <tt>int</tt> and qualified variations
 such as <tt>const int</tt>. In addition, the typemap system follows <tt>
typedef</tt> declarations. For example:</p>
<div class="code">
<pre>
%typemap(in) int n {
  if (Tcl_GetIntFromObj(interp, $input, &amp;$1) == TCL_ERROR)
    return TCL_ERROR;
  printf(&quot;n = %d\n&quot;, $1);
}
%inline %{
typedef int Integer;
extern int fact(Integer n);    // Above typemap is applied
%}
</pre>
</div>
<p> However, the matching of <tt>typedef</tt> only occurs in one
 direction. If you defined a typemap for <tt>Integer</tt>, it is not
 applied to arguments of type <tt>int</tt>.</p>
<p> Typemaps can also be defined for groups of consecutive arguments.
 For example:</p>
<div class="code">
<pre>
%typemap(in) (char *str, int len) {
    $1 = Tcl_GetStringFromObj($input, &amp;$2);
};

int count(char c, char *str, int len);
</pre>
</div>
<p> When a multi-argument typemap is defined, the arguments are always
 handled as a single Tcl object. This allows the function to be used
 like this (notice how the length parameter is omitted):</p>
<div class="code">
<pre>
% count e &quot;Hello World&quot;
1
</pre>
</div>
<h3><a name="Tcl_nn36">36.7.2 Tcl typemaps</a></h3>
<p> The previous section illustrated an &quot;in&quot; typemap for converting Tcl
 objects to C. A variety of different typemap methods are defined by the
 Tcl module. For example, to convert a C integer back into a Tcl object,
 you might define an &quot;out&quot; typemap like this:</p>
<div class="code">
<pre>
%typemap(out) int {
  Tcl_SetObjResult(interp, Tcl_NewIntObj($1));
}
</pre>
</div>
<p> The following list details all of the typemap methods that can be
 used by the Tcl module:</p>
<p> <tt>%typemap(in)</tt></p>
<div class="indent"> Converts Tcl objects to input function arguments</div>
<p> <tt>%typemap(out)</tt></p>
<div class="indent"> Converts return value of a C function to a Tcl
 object</div>
<p> <tt>%typemap(varin)</tt></p>
<div class="indent"> Assigns a C global variable from a Tcl object</div>
<p> <tt>%typemap(varout)</tt></p>
<div class="indent"> Returns a C global variable as a Tcl object</div>
<p> <tt>%typemap(freearg)</tt></p>
<div class="indent"> Cleans up a function argument (if necessary)</div>
<p> <tt>%typemap(argout)</tt></p>
<div class="indent"> Output argument processing</div>
<p> <tt>%typemap(ret)</tt></p>
<div class="indent"> Cleanup of function return values</div>
<p> <tt>%typemap(consttab)</tt></p>
<div class="indent"> Creation of Tcl constants (constant table)</div>
<p> <tt>%typemap(constcode)</tt></p>
<div class="indent"> Creation of Tcl constants (init function)</div>
<p> <tt>%typemap(memberin)</tt></p>
<div class="indent"> Setting of structure/class member data</div>
<p> <tt>%typemap(globalin)</tt></p>
<div class="indent"> Setting of C global variables</div>
<p> <tt>%typemap(check)</tt></p>
<div class="indent"> Checks function input values.</div>
<p> <tt>%typemap(default)</tt></p>
<div class="indent"> Set a default value for an argument (making it
 optional).</div>
<p> <tt>%typemap(arginit)</tt></p>
<div class="indent"> Initialize an argument to a value before any
 conversions occur.</div>
<p> Examples of these methods will appear shortly.</p>
<h3><a name="Tcl_nn37">36.7.3 Typemap variables</a></h3>
<p> Within typemap code, a number of special variables prefaced with a <tt>
$</tt> may appear. A full list of variables can be found in the &quot;<a href="#Typemaps">
Typemaps</a>&quot; chapter. This is a list of the most common variables:</p>
<p> <tt>$1</tt></p>
<div class="indent"> A C local variable corresponding to the actual type
 specified in the <tt>%typemap</tt> directive. For input values, this is
 a C local variable that's supposed to hold an argument value. For
 output values, this is the raw result that's supposed to be returned to
 Tcl.</div>
<p> <tt>$input</tt></p>
<div class="indent"> A <tt>Tcl_Obj *</tt> holding a raw Tcl object with
 an argument or variable value.</div>
<p> <tt>$result</tt></p>
<div class="indent"> A <tt>Tcl_Obj *</tt> that holds the result to be
 returned to Tcl.</div>
<p> <tt>$1_name</tt></p>
<div class="indent"> The parameter name that was matched.</div>
<p> <tt>$1_type</tt></p>
<div class="indent"> The actual C datatype matched by the typemap.</div>
<p> <tt>$1_ltype</tt></p>
<div class="indent"> An assignable version of the datatype matched by
 the typemap (a type that can appear on the left-hand-side of a C
 assignment operation). This type is stripped of qualifiers and may be
 an altered version of <tt>$1_type</tt>. All arguments and local
 variables in wrapper functions are declared using this type so that
 their values can be properly assigned.</div>
<p> <tt>$symname</tt></p>
<div class="indent"> The Tcl name of the wrapper function being created.</div>
<h3><a name="Tcl_nn38">36.7.4 Converting a Tcl list to a char **</a></h3>
<p> A common problem in many C programs is the processing of command
 line arguments, which are usually passed in an array of NULL terminated
 strings. The following SWIG interface file allows a Tcl list to be used
 as a <tt>char **</tt> object.</p>
<div class="code">
<pre>
%module argv

// This tells SWIG to treat char ** as a special case
%typemap(in) char ** {
  Tcl_Obj **listobjv;
  int       nitems;
  int       i;
  if (Tcl_ListObjGetElements(interp, $input, &amp;nitems, &amp;listobjv) == TCL_ERROR) {
    return TCL_ERROR;
  }
  $1 = (char **) malloc((nitems+1)*sizeof(char *));
  for (i = 0; i &lt; nitems; i++) {
    $1[i] = Tcl_GetStringFromObj(listobjv[i], 0);
  }
  $1[i] = 0;
}

// This gives SWIG some cleanup code that will get called after the function call
%typemap(freearg) char ** {
  if ($1) {
    free($1);
  }
}

// Now a test functions
%inline %{
  int print_args(char **argv) {
    int i = 0;
    while (argv[i]) {
      printf(&quot;argv[%d] = %s\n&quot;, i, argv[i]);
      i++;
    }
    return i;
  }
%}
%include &quot;tclsh.i&quot;

</pre>
</div>
<p> In Tcl:</p>
<div class="code">
<pre>
% print_args {John Guido Larry}
argv[0] = John
argv[1] = Guido
argv[2] = Larry
3
</pre>
</div>
<h3><a name="Tcl_nn39">36.7.5 Returning values in arguments</a></h3>
<p> The &quot;argout&quot; typemap can be used to return a value originating from
 a function argument. For example :</p>
<div class="code">
<pre>
// A typemap defining how to return an argument by appending it to the result
%typemap(argout) double *outvalue {
  Tcl_Obj *o = Tcl_NewDoubleObj($1);
  Tcl_ListObjAppendElement(interp, $result, o);
}

// A typemap telling SWIG to ignore an argument for input
// However, we still need to pass a pointer to the C function
%typemap(in, numinputs=0) double *outvalue (double temp) {
  $1 = &amp;temp;
}

// Now a function returning two values
int mypow(double a, double b, double *outvalue) {
  if ((a &lt; 0) || (b &lt; 0)) return -1;
  *outvalue = pow(a, b);
  return 0;
};
</pre>
</div>
<p> When wrapped, SWIG matches the <tt>argout</tt> typemap to the &quot;<tt>
double *outvalue</tt>&quot; argument. The numinputs=0 specification tells
 SWIG to simply ignore this argument when generating wrapper code. As a
 result, a Tcl function using these typemaps will work like this :</p>
<div class="code">
<pre>
% mypow 2 3     # Returns two values, a status value and the result
0 8
%
</pre>
</div>
<h3><a name="Tcl_nn40">36.7.6 Useful functions</a></h3>
<p> The following tables provide some functions that may be useful in
 writing Tcl typemaps.</p>
<p><b> Integers</b></p>
<div class="code">
<pre>
Tcl_Obj   *Tcl_NewIntObj(int Value);
void       Tcl_SetIntObj(Tcl_Obj *obj, int Value);
int        Tcl_GetIntFromObj(Tcl_Interp *, Tcl_Obj *obj, int *ip);
</pre>
</div>
<p><b> Floating Point</b></p>
<div class="code">
<pre>
Tcl_Obj  *Tcl_NewDoubleObj(double Value);
void      Tcl_SetDoubleObj(Tcl_Obj *obj, double value);
int       Tcl_GetDoubleFromObj(Tcl_Interp *, Tcl_Obj *o, double *dp);
</pre>
</div>
<p><b> Strings</b></p>
<div class="code">
<pre>
Tcl_Obj  *Tcl_NewStringObj(char *str, int len);
char     *Tcl_GetStringFromObj(Tcl_Obj *obj, int *len);
void      Tcl_AppendToObj(Tcl_Obj *obj, char *str, int len);
</pre>
</div>
<p><b> Lists</b></p>
<div class="code">
<pre>
Tcl_Obj  *Tcl_NewListObj(int objc, Tcl_Obj *objv);
int       Tcl_ListObjAppendList(Tcl_Interp *, Tcl_Obj *listPtr, Tcl_Obj *elemListPtr);
int       Tcl_ListObjAppendElement(Tcl_Interp *, Tcl_Obj *listPtr, Tcl_Obj *element);
int       Tcl_ListObjGetElements(Tcl_Interp *, Tcl_Obj *listPtr, int *objcPtr,
                                 Tcl_Obj ***objvPtr);
int       Tcl_ListObjLength(Tcl_Interp *, Tcl_Obj *listPtr, int *intPtr);
int       Tcl_ListObjIndex(Tcl_Interp *, Tcl_Obj *listPtr, int index,
                           Tcl_Obj_Obj **objptr);
int       Tcl_ListObjReplace(Tcl_Interp *, Tcl_Obj *listPtr, int first, int count,
                             int objc, Tcl_Obj *objv);
</pre>
</div>
<p><b> Objects</b></p>
<div class="code">
<pre>
Tcl_Obj *Tcl_DuplicateObj(Tcl_Obj *obj);
void     Tcl_IncrRefCount(Tcl_Obj *obj);
void     Tcl_DecrRefCount(Tcl_Obj *obj);
int      Tcl_IsShared(Tcl_Obj *obj);
</pre>
</div>
<h3><a name="Tcl_nn41">36.7.7 Standard typemaps</a></h3>
<p> The following typemaps show how to convert a few common kinds of
 objects between Tcl and C (and to give a better idea of how typemaps
 work)</p>
<p><b> Integer conversion</b></p>
<div class="code">
<pre>
%typemap(in) int, short, long {
  int temp;
  if (Tcl_GetIntFromObj(interp, $input, &amp;temp) == TCL_ERROR)
    return TCL_ERROR;
  $1 = ($1_ltype) temp;
}
</pre>
</div>
<br><div class="code">
<pre>
%typemap(out) int, short, long {
  Tcl_SetIntObj($result, (int) $1);
}
</pre>
</div>
<p><b> Floating point conversion</b></p>
<div class="code">
<pre>
%typemap(in) float, double {
  double temp;
  if (Tcl_GetDoubleFromObj(interp, $input, &amp;temp) == TCL_ERROR)
    return TCL_ERROR;
  $1 = ($1_ltype) temp;
}
</pre>
</div>
<br><div class="code">
<pre>
%typemap(out) float, double {
  Tcl_SetDoubleObj($result, $1);
}
</pre>
</div>
<p><b> String Conversion</b></p>
<div class="code">
<pre>
%typemap(in) char * {
  int len;
  $1 = Tcl_GetStringFromObj(interp, &amp;len);
}
</pre>
</div>
<br><div class="code">
<pre>
%typemap(out, noblock=1, fragment=&quot;SWIG_FromCharPtr&quot;) char *, const char * {
  Tcl_SetObjResult(interp, SWIG_FromCharPtr((const char *)$1));
}

</pre>
</div>
<h3><a name="Tcl_nn42">36.7.8 Pointer handling</a></h3>
<p> SWIG pointers are mapped into Tcl strings containing the hexadecimal
 value and type. The following functions can be used to create and read
 pointer values.</p>
<p> <tt>int SWIG_ConvertPtr(Tcl_Obj *obj, void **ptr, swig_type_info
 *ty, int flags)</tt></p>
<div class="indent"> Converts a Tcl object <tt>obj</tt> to a C pointer.
 The result of the conversion is placed into the pointer located at <tt>
ptr</tt>. <tt>ty</tt> is a SWIG type descriptor structure. <tt>flags</tt>
 is used to handle error checking and other aspects of conversion. It is
 currently reserved for future expansion. Returns 0 on success and -1 on
 error.</div>
<p> <tt>Tcl_Obj *SWIG_NewPointerObj(void *ptr, swig_type_info *ty, int
 flags)</tt></p>
<div class="indent"> Creates a new Tcl pointer object. <tt>ptr</tt> is
 the pointer to convert, <tt>ty</tt> is the SWIG type descriptor
 structure that describes the type, and <tt>own</tt> is a flag reserved
 for future expansion.</div>
<p> Both of these functions require the use of a special SWIG
 type-descriptor structure. This structure contains information about
 the mangled name of the datatype, type-equivalence information, as well
 as information about converting pointer values under C++ inheritance.
 For a type of <tt>Foo *</tt>, the type descriptor structure is usually
 accessed as follows:</p>
<div class="indent">
<pre>
Foo *f;
if (!SWIG_IsOK(SWIG_ConvertPtr($input, (void **) &amp;f, SWIGTYPE_p_Foo, 0))) {
  SWIG_exception_fail(SWIG_TypeError, &quot;in method '$symname', expecting type Foo&quot;);
}

Tcl_Obj *;
obj = SWIG_NewPointerObj(f, SWIGTYPE_p_Foo, 0);
</pre>
</div>
<p> In a typemap, the type descriptor should always be accessed using
 the special typemap variable <tt>$1_descriptor</tt>. For example:</p>
<div class="indent">
<pre>
%typemap(in) Foo * {
  if (!SWIG_IsOK(SWIG_ConvertPtr($input, (void **) &amp;$1, $1_descriptor, 0))) {
    SWIG_exception_fail(SWIG_TypeError, &quot;in method '$symname', expecting type Foo&quot;);
  }
}
</pre>
</div>
<p> If necessary, the descriptor for any type can be obtained using the <tt>
$descriptor()</tt> macro in a typemap. For example:</p>
<div class="indent">
<pre>
%typemap(in) Foo * {
  if (!SWIG_IsOK(SWIG_ConvertPtr($input, (void **) &amp;$1, $descriptor(Foo *), 0))) {
    SWIG_exception_fail(SWIG_TypeError, &quot;in method '$symname', expecting type Foo&quot;);
  }
}
</pre>
</div>
<h2><a name="Tcl_nn43">36.8 Turning a SWIG module into a Tcl Package.</a>
</h2>
<p> Tcl 7.4 introduced the idea of an extension package. By default,
 SWIG generates all of the code necessary to create a package. To set
 the package version, simply use the <tt>-pkgversion</tt> option. For
 example:</p>
<div class="code">
<pre>
% swig -tcl -pkgversion 2.3 example.i
</pre>
</div>
<p> After building the SWIG generated module, you need to execute the &quot;<tt>
pkg_mkIndex</tt>&quot; command inside tclsh. For example :</p>
<div class="code">
<pre>
unix &gt; tclsh
% pkg_mkIndex . example.so
% exit
</pre>
</div>
<p> This creates a file &quot;<tt>pkgIndex.tcl</tt>&quot; with information about
 the package. To use your package, you now need to move it to its own
 subdirectory which has the same name as the package. For example :</p>
<div class="code">
<pre>
./example/
           pkgIndex.tcl           # The file created by pkg_mkIndex
           example.so             # The SWIG generated module
</pre>
</div>
<p> Finally, assuming that you're not entirely confused at this point,
 make sure that the example subdirectory is visible from the directories
 contained in either the <tt>tcl_library</tt> or <tt>auto_path</tt>
 variables. At this point you're ready to use the package as follows :</p>
<div class="code">
<pre>
unix &gt; tclsh
% package require example
% fact 4
24
%
</pre>
</div>
<p> If you're working with an example in the current directory and this
 doesn't work, do this instead :</p>
<div class="code">
<pre>
unix &gt; tclsh
% lappend auto_path .
% package require example
% fact 4
24
</pre>
</div>
<p> As a final note, most SWIG examples do not yet use the <tt>package</tt>
 commands. For simple extensions it may be easier just to use the <tt>
load</tt> command instead.</p>
<h2><a name="Tcl_nn44">36.9 Building new kinds of Tcl interfaces (in
 Tcl)</a></h2>
<p> One of the most interesting aspects of Tcl and SWIG is that you can
 create entirely new kinds of Tcl interfaces in Tcl using the low-level
 SWIG accessor functions. For example, suppose you had a library of
 helper functions to access arrays :</p>
<div class="code">
<pre>
/* File : array.i */
%module array

%inline %{
double *new_double(int size) {
  return (double *) malloc(size*sizeof(double));
}
void delete_double(double *a) {
  free(a);
}
double get_double(double *a, int index) {
  return a[index];
}
void set_double(double *a, int index, double val) {
  a[index] = val;
}
int *new_int(int size) {
  return (int *) malloc(size*sizeof(int));
}
void delete_int(int *a) {
  free(a);
}
int get_int(int *a, int index) {
  return a[index];
}
int set_int(int *a, int index, int val) {
  a[index] = val;
}
%}

</pre>
</div>
<p> While these could be called directly, we could also write a Tcl
 script like this :</p>
<div class="code">
<pre>
proc Array {type size} {
    set ptr [new_$type $size]
    set code {
        set method [lindex $args 0]
        set parms [concat $ptr [lrange $args 1 end]]
        switch $method {
            get {return [eval &quot;get_$type $parms&quot;]}
            set {return [eval &quot;set_$type $parms&quot;]}
            delete {eval &quot;delete_$type $ptr; rename $ptr {}&quot;}
        }
    }
    # Create a procedure
    uplevel &quot;proc $ptr args {set ptr $ptr; set type $type;$code}&quot;
    return $ptr
}
</pre>
</div>
<p> Our script allows easy array access as follows :</p>
<div class="code">
<pre>
set a [Array double 100]                   ;# Create a double [100]
for {set i 0} {$i &lt; 100} {incr i 1} {      ;# Clear the array
        $a set $i 0.0
}
$a set 3 3.1455                            ;# Set an individual element
set b [$a get 10]                          ;# Retrieve an element

set ia [Array int 50]                      ;# Create an int[50]
for {set i 0} {$i &lt; 50} {incr i 1} {       ;# Clear it
        $ia set $i 0
}
$ia set 3 7                                ;# Set an individual element
set ib [$ia get 10]                        ;# Get an individual element

$a delete                                  ;# Destroy a
$ia delete                                 ;# Destroy ia
</pre>
</div>
<p> The cool thing about this approach is that it makes a common
 interface for two different types of arrays. In fact, if we were to add
 more C datatypes to our wrapper file, the Tcl code would work with
 those as well--without modification. If an unsupported datatype was
 requested, the Tcl code would simply return with an error so there is
 very little danger of blowing something up (although it is easily
 accomplished with an out of bounds array access).</p>
<h3><a name="Tcl_nn45">36.9.1 Proxy classes</a></h3>
<p> A similar approach can be applied to proxy classes (also known as
 shadow classes). The following example is provided by Erik Bierwagen
 and Paul Saxe. To use it, run SWIG with the <tt>-noobject</tt> option
 (which disables the builtin object oriented interface). When running
 Tcl, simply source this file. Now, objects can be used in a more or
 less natural fashion.</p>
<div class="code">
<pre>
# swig_c++.tcl
# Provides a simple object oriented interface using
# SWIG's low level interface.
#

proc new {objectType handle_r args} {
    # Creates a new SWIG object of the given type,
    # returning a handle in the variable &quot;handle_r&quot;.
    #
    # Also creates a procedure for the object and a trace on
    # the handle variable that deletes the object when the
    # handle variable is overwritten or unset
    upvar $handle_r handle
    #
    # Create the new object
    #
    eval set handle \[new_$objectType $args\]
    #
    # Set up the object procedure
    #
    proc $handle {cmd args} &quot;eval ${objectType}_\$cmd $handle \$args&quot;
    #
    # And the trace ...
    #
    uplevel trace variable $handle_r uw &quot;{deleteObject $objectType $handle}&quot;
    #
    # Return the handle so that 'new' can be used as an argument to a procedure
    #
    return $handle
}

proc deleteObject {objectType handle name element op} {
    #
    # Check that the object handle has a reasonable form
    #
    if {![regexp {_[0-9a-f]*_(.+)_p} $handle]} {
        error &quot;deleteObject: not a valid object handle: $handle&quot;
    }
    #
    # Remove the object procedure
    #
    catch {rename $handle {}}
    #
    # Delete the object
    #
    delete_$objectType $handle
}

proc delete {handle_r} {
    #
    # A synonym for unset that is more familiar to C++ programmers
    #
    uplevel unset $handle_r
}
</pre>
</div>
<p> To use this file, we simply source it and execute commands such as
 &quot;new&quot; and &quot;delete&quot; to manipulate objects. For example :</p>
<div class="code">
<pre>
// list.i
%module List
%{
#include &quot;list.h&quot;
%}

// Very simple C++ example

class List {
public:
  List();  // Create a new list
  ~List(); // Destroy a list
  int  search(char *value);
  void insert(char *);  // Insert a new item into the list
  void remove(char *);  // Remove item from list
  char *get(int n);     // Get the nth item in the list
  int  length;          // The current length of the list
static void print(List *l);  // Print out the contents of the list
};
</pre>
</div>
<p> Now a Tcl script using the interface...</p>
<div class="code">
<pre>
load ./list.so list       ; # Load the module
source swig_c++.tcl       ; # Source the object file

new List l
$l insert Dave
$l insert John
$l insert Guido
$l remove Dave
puts $l length_get

delete l
</pre>
</div>
<p> The cool thing about this example is that it works with any C++
 object wrapped by SWIG and requires no special compilation. Proof that
 a short, but clever Tcl script can be combined with SWIG to do many
 interesting things.</p>
<h2><a name="Tcl_nn46">36.10 Tcl/Tk Stubs</a></h2>
<p> For background information about the Tcl Stubs feature, see <a href="http://www.tcl.tk/doc/howto/stubs.html">
http://www.tcl.tk/doc/howto/stubs.html</a>.</p>
<p> As of SWIG 1.3.10, the generated C/C++ wrapper will use the Tcl
 Stubs feature if compiled with <tt>-DUSE_TCL_STUBS</tt>.</p>
<p> As of SWIG 1.3.40, the generated C/C++ wrapper will use the Tk Stubs
 feature if compiled with <tt>-DUSE_TK_STUBS</tt>. Also, you can
 override the minimum version to support which is passed to <tt>
Tcl_InitStubs()</tt> and <tt>Tk_InitStubs()</tt> with <tt>
-DSWIG_TCL_STUBS_VERSION=&quot;8.3&quot;</tt> or the version being compiled with
 using <tt>-DSWIG_TCL_STUBS_VERSION=TCL_VERSION</tt>.</p>
<HR NOSHADE>
<h1><a name="Mzscheme">37 SWIG and MzScheme/Racket</a></h1>

<!-- INDEX -->
<div class="sectiontoc">
<ul>
<li><a href="#MzScheme_nn2">Creating native structures</a></li>
<li><a href="#MzScheme_simple">Simple example</a></li>
<li><a href="#MzScheme_external_docs">External documentation</a></li>
</ul>
</div>
<!-- INDEX -->
<p> This section contains information on SWIG's support of Racket,
 formally known as MzScheme.</p>
<h2><a name="MzScheme_nn2">37.1 Creating native structures</a></h2>
<p> Example interface file:</p>
<div class="code">
<pre>
/* define a macro for the struct creation */
%define handle_ptr(TYPE, NAME)
%typemap(argout) TYPE *NAME{
  Scheme_Object *o = SWIG_NewStructFromPtr($1, $*1_mangle);
  SWIG_APPEND_VALUE(o);
}

%typemap(in, numinputs=0) TYPE *NAME (TYPE temp) {
  $1 = &amp;temp;
}
%enddef

/* setup the typemaps for the pointer to an output parameter cntrs */
handle_ptr(struct diag_cntrs, cntrs);
</pre>
</div>
<p> Then in scheme, you can use regular struct access procedures like</p>
<div class="code">
<pre>
        ; suppose a function created a struct foo as
        ; (define foo (make-diag-cntrs (#x1 #x2 #x3) (make-inspector))
        ; Then you can do
        (format &quot;0x~x&quot; (diag-cntrs-field1 foo))
        (format &quot;0x~x&quot; (diag-cntrs-field2 foo))
        ;etc...
</pre>
</div>
<h2><a name="MzScheme_simple">37.2 Simple example</a></h2>
<p> A few examples are available in the Examples/mzscheme directory. The
 code and log of a session using SWIG below should help getting started.</p>
<p> C header file:</p>
<div class="code">
<pre>
// example.h
int fact(int n);
</pre>
</div>
<p> C source code:</p>
<div class="code">
<pre>
// File: example.c
#include &quot;example.h&quot;

int fact(int n) {
  if (n &lt; 0) { /* This should probably return an error, but this is simpler */
    return 0;
  }
  if (n == 0) {
    return 1;
  }
  else {
    /* testing for overflow would be a good idea here */
    return n * fact(n-1);
  }
}
</pre>
</div>
<p> SWIG interface file:</p>
<div class="code">
<pre>
/* File: example.i */
%module example

%{
#include &quot;example.h&quot;
%}

int fact(int n);
</pre>
</div>
<p> The session below using the above files is on an OS X machine, but
 the points to be made are more general. On OS X, libtool is the tool
 which creates libraries, which are named .dylib, rather than .so on
 other unixes, or .dll on Windows.</p>
<div class="shell">
<pre>
% swig -mzscheme -declaremodule example.i
% gcc -c -m32 -o example.o example.c # force 32-bit object file (mzscheme is 32-bit only)
% libtool -dynamic -o libexample.dylib example.o # make it into a library
% ls # what've we got so far?
example.c example.o
example.h example_wrap.c
example.i libexample.dylib*
% mzc --cgc --cc example_wrap.c # compile the wrapping code
% LDFLAGS=&quot;-L. -lexample&quot; mzc --ld example_wrap.dylib example_wrap.o # ...and link it
% mzscheme -e '(path-&gt;string (build-path &quot;compiled&quot; &quot;native&quot; (system-library-subpath)))'
&quot;compiled/native/i386-macosx/3m&quot;
% mkdir -p compiled/native/i386-macosx/3m # move the extension library to a magic place
% mv example_wrap.dylib compiled/native/i386-macosx/3m/example_ss.dylib
% mzscheme
Welcome to MzScheme v4.2.4 [3m], Copyright (c) 2004-2010 PLT Scheme Inc.
&gt; (require &quot;example.ss&quot;)
&gt; (fact 5)
120
&gt; ^D
% echo 'It works!'
</pre>
</div>
<p> Some points of interest:</p>
<ul>
<li> This is on a 64-bit machine, so we have to include the -m32 option
 when building the object file</li>
<li> If you want to declare a scheme module (and you probably do), it's
 important that you include the -declaremodule option to swig (if you
 miss this out, it'll appear to work, but fail later).</li>
<li> Use mzc to compile and then link the wrapped code. You'll probably
 need to adjust the link flags to refer to the library you're wrapping
 (you can either do this with an LDFLAGS declaration, as here, or with
 multiple ++ldf options to mzc).</li>
<li> Create the directory with path (build-path &quot;compiled&quot; &quot;native&quot;
 (system-library-subpath)) and move the freshly-generated .dylib to
 there, changing its name to module-name_ss.dylib. After that, you can
 REQUIRE the new module with (require &quot;module-name.ss&quot;).</li>
<li> The above requests mzc to create an extension using the CGC
 garbage-collector. The alternative -- the 3m collector -- has generally
 better performance, but work is still required for SWIG to emit code
 which is compatible with it.</li>
</ul>
<h2><a name="MzScheme_external_docs">37.3 External documentation</a></h2>
<p> See the <a href="https://docs.racket-lang.org/inside/index.html">C
 API</a> for more description of using the mechanism for adding
 extensions. The main documentation is <a href="https://docs.racket-lang.org/">
here</a>.</p>
<p> Tip: mzc's --vv option is very useful for debugging the inevitable
 library problems you'll encounter.</p>
<HR NOSHADE>
<h1><a name="Ocaml">38 SWIG and OCaml</a></h1>

<!-- INDEX -->
<div class="sectiontoc">
<ul>
<li><a href="#Ocaml_nn2">Preliminaries</a>
<ul>
<li><a href="#Ocaml_nn3">Running SWIG</a></li>
<li><a href="#Ocaml_nn4">Compiling the code</a></li>
<li><a href="#Ocaml_nn5">The camlp4 module</a></li>
<li><a href="#Ocaml_nn6">Using your module</a></li>
<li><a href="#Ocaml_nn7">Compilation problems and compiling with C++</a></li>
</ul>
</li>
<li><a href="#Ocaml_nn8">The low-level Ocaml/C interface</a>
<ul>
<li><a href="#Ocaml_nn9">The generated module</a></li>
<li><a href="#Ocaml_nn10">Enums</a>
<ul>
<li><a href="#Ocaml_nn11">Enum typing in Ocaml</a></li>
</ul>
</li>
<li><a href="#Ocaml_nn12">Arrays</a>
<ul>
<li><a href="#Ocaml_nn13">Simple types of bounded arrays</a></li>
<li><a href="#Ocaml_nn14">Complex and unbounded arrays</a></li>
<li><a href="#Ocaml_nn15">Using an object</a></li>
<li><a href="#Ocaml_nn16">Example typemap for a function taking float *
 and int</a></li>
</ul>
</li>
<li><a href="#Ocaml_nn17">C++ Classes</a>
<ul>
<li><a href="#Ocaml_nn18">STL vector and string Example</a></li>
<li><a href="#Ocaml_nn19">C++ Class Example</a></li>
<li><a href="#Ocaml_nn20">Compiling the example</a></li>
<li><a href="#Ocaml_nn21">Sample Session</a></li>
</ul>
</li>
<li><a href="#Ocaml_nn22">Director Classes</a>
<ul>
<li><a href="#Ocaml_nn23">Director Introduction</a></li>
<li><a href="#Ocaml_nn24">Overriding Methods in Ocaml</a></li>
<li><a href="#Ocaml_nn25">Director Usage Example</a></li>
<li><a href="#Ocaml_nn26">Creating director objects</a></li>
<li><a href="#Ocaml_nn27">Typemaps for directors, directorin,
 directorout, directorargout</a></li>
<li><a href="#Ocaml_nn28">directorin typemap</a></li>
<li><a href="#Ocaml_nn29">directorout typemap</a></li>
<li><a href="#Ocaml_nn30">directorargout typemap</a></li>
</ul>
</li>
<li><a href="#Ocaml_nn31">Exceptions</a></li>
</ul>
</li>
<li><a href="#Ocaml_nn32">Documentation Features</a>
<ul>
<li><a href="#Ocaml_nn33">Module docstring</a></li>
</ul>
</li>
</ul>
</div>
<!-- INDEX -->
<p> This chapter describes SWIG's support of Ocaml.</p>
<p> Ocaml is a relatively recent addition to the ML family, and is a
 recent addition to SWIG. It's the second compiled, typed language to be
 added. Ocaml has widely acknowledged benefits for engineers, mostly
 derived from a sophisticated type system, compile-time checking which
 eliminates several classes of common programming errors, and good
 native performance. While all of this is wonderful, there are
 well-written C and C++ libraries that Ocaml users will want to take
 advantage of as part of their arsenal (such as SSL and gdbm), as well
 as their own mature C and C++ code. SWIG allows this code to be used in
 a natural, type-safe way with Ocaml, by providing the necessary, but
 repetitive glue code which creates and uses Ocaml values to communicate
 with C and C++ code. In addition, SWIG also produces the needed Ocaml
 source that binds variants, functions, classes, etc.</p>
<p> If you're not familiar with the Objective Caml language, you can
 visit <a href="http://ocaml.org/">The Ocaml Website</a>.</p>
<h2><a name="Ocaml_nn2">38.1 Preliminaries</a></h2>
<p> SWIG is compatible with OCaml 3.12.0 and above. Given the choice,
 you should use the latest stable release. The SWIG Ocaml module has
 been tested on Linux (x86, PPC, Sparc) and Cygwin on Windows. The best
 way to determine whether your system will work is to compile the
 examples and test-suite which come with SWIG. You can do this by
 running <tt>make check</tt> from the SWIG root directory after
 installing SWIG. The Ocaml module has been tested using the system's
 dynamic linking (the usual -lxxx against libxxx.so, as well as with
 Gerd Stolpmann's <a href="http://download.camlcity.org/download/">Dl
 package</a>. The ocaml_dynamic and ocaml_dynamic_cpp targets in the
 file Examples/Makefile illustrate how to compile and link SWIG modules
 that will be loaded dynamically. This has only been tested on Linux so
 far.</p>
<h3><a name="Ocaml_nn3">38.1.1 Running SWIG</a></h3>
<p> The basics of getting a SWIG Ocaml module up and running can be seen
 from one of SWIG's example Makefiles, but is also described here. To
 build an Ocaml module, run SWIG using the <tt>-ocaml</tt> option.</p>
<div class="code">
<pre>
%swig -ocaml example.i
</pre>
</div>
<p>This will produce 3 files. The file <tt>example_wrap.c</tt> contains
 all of the C code needed to build an Ocaml module. To build the module,
 you will compile the file <tt>example_wrap.c</tt> with <tt>ocamlc</tt>
 or <tt>ocamlopt</tt> to create the needed .o file. You will need to
 compile the resulting .ml and .mli files as well, and do the final link
 with -custom (not needed for native link).</p>
<h3><a name="Ocaml_nn4">38.1.2 Compiling the code</a></h3>
<p> The OCaml SWIG module now requires you to compile a module (<tt>Swig</tt>
) separately. In addition to aggregating common SWIG functionality, the
 Swig module contains the data structure that represents C/C++ values.
 This allows easier data sharing between modules if two or more are
 combined, because the type of each SWIG'ed module's c_obj is derived
 from Swig.c_obj_t. This also allows SWIG to acquire new conversions
 painlessly, as well as giving the user more freedom with respect to
 custom typing. Use <tt>ocamlc</tt> or <tt>ocamlopt</tt> to compile your
 SWIG interface like:</p>
<div class="code">
<pre>
% swig -ocaml -co swig.mli ; swig -ocaml -co swig.ml
% ocamlc -c swig.mli ; ocamlc -c swig.ml
% ocamlc -c -ccopt &quot;-I/usr/include/foo&quot; example_wrap.c
% ocamlc -c example.mli
% ocamlc -c example.ml
</pre>
</div>
<p><tt>ocamlc</tt> is aware of .c files and knows how to handle them.
 Unfortunately, it does not know about .cxx, .cc, or .cpp files, so when
 SWIG is invoked in C++ mode, you must:</p>
<div class="code">
<pre>
% cp example_wrap.cxx example_wrap.cxx.c
% ocamlc -c ... -ccopt -xc++ example_wrap.cxx.c
% ...
</pre>
</div>
<h3><a name="Ocaml_nn5">38.1.3 The camlp4 module</a></h3>
<p> The camlp4 module (swigp4.ml -&gt; swigp4.cmo) contains a simple
 rewriter which makes C++ code blend more seamlessly with objective caml
 code. Its use is optional, but encouraged. The source file is included
 in the Lib/ocaml directory of the SWIG source distribution. You can
 checkout this file with <tt>&quot;swig -ocaml -co swigp4.ml&quot;</tt>. You
 should compile the file with <tt>&quot;ocamlc -I `camlp4 -where` -pp
 'camlp4o pa_extend.cmo q_MLast.cmo' -c swigp4.ml&quot;</tt></p>
<p> The basic principle of the module is to recognize certain non-caml
 expressions and convert them for use with C++ code as interfaced by
 SWIG. The camlp4 module is written to work with generated SWIG
 interfaces, and probably isn't great to use with anything else.</p>
<p> Here are the main rewriting rules:</p>
<table border="1" summary="Rewriting rules">
<tr><th>Input</th><th>Rewritten to</th></tr>
<tr><td>f'( ... ) as in
<br> atoi'(&quot;0&quot;) or
<br> _exit'(0)</td><td>f(C_list [ ... ]) as in
<br> atoi (C_list [ C_string &quot;0&quot; ]) or
<br> _exit (C_list [ C_int 0 ])</td></tr>
<tr><td>object -&gt; method ( ... )</td><td>(invoke object) &quot;method&quot;
 (C_list [ ... ])</td></tr>
<tr><td> object<i> 'binop</i> argument as in
<br> a '+= b</td><td> (invoke object) &quot;+=&quot; argument as in
<br> (invoke a) &quot;+=&quot; b</td><td></td></tr>
<tr><th colspan="2">Note that because camlp4 always recognizes &lt;&lt; and
 &gt;&gt;, they are replaced by lsl and lsr in operator names.
<tr><td><i> 'unop</i> object as in
<br> '! a</td><td> (invoke a) &quot;!&quot; C_void</td></tr>
<tr><td><b> Smart pointer access like this</b>
<br> object '-&gt; method ( args )
<br></td><td> (invoke (invoke object &quot;-&gt;&quot; C_void))</td></tr>
<tr><td><b> Invoke syntax</b>
<br> object . '( ... )</td><td> (invoke object) &quot;()&quot; (C_list [ ... ])</td>
</tr>
<tr><td><b> Array syntax</b>
<br> object '[ 10 ]</td><td> (invoke object) &quot;[]&quot; (C_int 10)</td></tr>
<tr><td><b> Assignment syntax</b>
<br> let a = '10 and b = '&quot;foo&quot; and c = '1.0 and d = 'true</td><td> let
 a = C_int 10 and b = C_string &quot;foo&quot; and c = C_double 1.0 and d = C_bool
 true</td></tr>
<tr><td><b> Cast syntax</b>
<br> let a = _atoi '(&quot;2&quot;) as int
<br> let b = (getenv &quot;PATH&quot;) to string
<br> This works for int, string, float, bool</td><td> let a = get_int
 (_atoi (C_string &quot;2&quot;))
<br> let b = C_string (getenv &quot;PATH&quot;)</td></tr>
</th></tr>
</table>
<h3><a name="Ocaml_nn6">38.1.4 Using your module</a></h3>
<p> You can test-drive your module by building a toplevel ocaml
 interpreter. Consult the ocaml manual for details.</p>
<p> When linking any ocaml bytecode with your module, use the -custom
 option to build your functions into the primitive list. This option is
 not needed when you build native code.</p>
<h3><a name="Ocaml_nn7">38.1.5 Compilation problems and compiling with
 C++</a></h3>
<p> As mentioned above, .cxx files need special handling to be compiled
 with <tt>ocamlc</tt>. Other than that, C code that uses <tt>class</tt>
 as a non-keyword, and C code that is too liberal with pointer types may
 not compile under the C++ compiler. Most code meant to be compiled as
 C++ will not have problems.</p>
<h2><a name="Ocaml_nn8">38.2 The low-level Ocaml/C interface</a></h2>
<p> In order to provide access to overloaded functions, and provide
 sensible outputs from them, all C entities are represented as members
 of the c_obj type:</p>
<p> In the code as seen by the typemap writer, there is a value,
 swig_result, that always contains the current return data. It is a
 list, and must be appended with the caml_list_append function, or with
 functions and macros provided by objective caml.</p>
<div class="code">
<pre>
type c_obj =
    C_void
  | C_bool of bool
  | C_char of char
  | C_uchar of char
  | C_short of int
  | C_ushort of int
  | C_int of int
  | C_uint of int32
  | C_int32 of int32
  | C_int64 of int64
  | C_float of float
  | C_double of float
  | C_ptr of int64 * int64
  | C_array of c_obj array
  | C_list of c_obj list
  | C_obj of (string -&gt; c_obj -&gt; c_obj)
  | C_string of string
  | C_enum of c_enum_t
</pre>
</div>
<p> A few functions exist which generate and return these:</p>
<ul>
<li>caml_ptr_val receives a c_obj and returns a void *. This should be
 used for all pointer purposes.</li>
<li>caml_long_val receives a c_obj and returns a long. This should be
 used for most integral purposes.</li>
<li>caml_val_ptr receives a void * and returns a c_obj.</li>
<li>caml_val_bool receives a C int and returns a c_obj representing its
 bool value.</li>
<li>caml_val_(u)?(char|short|int|long|float|double) receives an
 appropriate C value and returns a c_obj representing it.</li>
<li>caml_val_string receives a char * and returns a string value.</li>
<li>caml_val_string_len receives a char * and a length and returns a
 string value.</li>
<li>caml_val_obj receives a void * and an object type and returns a
 C_obj, which contains a closure giving method access.</li>
</ul>
<p> Because of this style, a typemap can return any kind of value it
 wants from a function. This enables out typemaps and inout typemaps to
 work well. The one thing to remember about outputting values is that
 you must append them to the return list with swig_result =
 caml_list_append(swig_result, v).</p>
<p> This function will return a new list that has your element appended.
 Upon return to caml space, the fnhelper function beautifies the result.
 A list containing a single item degrades to only that item (i.e. [
 C_int 3 ] -&gt; C_int 3), and a list containing more than one item is
 wrapped in C_list (i.e. [ C_char 'a' ; C_char 'b' ] -&gt; C_list [ C_char
 'a' ; C_char 'b' ]). This is in order to make return values easier to
 handle when functions have only one return value, such as constructors,
 and operators. In addition, string, pointer, and object values are
 interchangeable with respect to caml_ptr_val, so you can allocate
 memory as caml strings and still use the resulting pointers for C
 purposes, even using them to construct simple objects on. Note, though,
 that foreign C++ code does not respect the garbage collector, although
 the SWIG interface does.</p>
<p> The wild card type that you can use in lots of different ways is
 C_obj. It allows you to wrap any type of thing you like as an object
 using the same mechanism that the ocaml module does. When evaluated in
 caml_ptr_val, the returned value is the result of a call to the
 object's &quot;&amp;&quot; operator, taken as a pointer.</p>
<p> You should only construct values using objective caml, or using the
 functions caml_val_* functions provided as static functions to a SWIG
 ocaml module, as well as the caml_list_* functions. These functions
 provide everything a typemap needs to produce values. In addition,
 value items pass through directly, but you must make your own type
 signature for a function that uses value in this way.</p>
<h3><a name="Ocaml_nn9">38.2.1 The generated module</a></h3>
<p> The SWIG <tt>%module</tt> directive specifies the name of the Ocaml
 module to be generated. If you specified `<tt>%module example</tt>',
 then your Ocaml code will be accessible in the module Example. The
 module name is always capitalized as is the ocaml convention. Note that
 you must not use any Ocaml keyword to name your module. Remember that
 the keywords are not the same as the C++ ones.</p>
<p> You can introduce extra code into the output wherever you like with
 SWIG. These are the places you can introduce code:</p>
<table border="1" summary="Extra code sections">
<tr><td>&quot;header&quot;</td><td>This code is inserted near the beginning of the
 C wrapper file, before any function definitions.</td></tr>
<tr><td>&quot;wrapper&quot;</td><td>This code is inserted in the function
 definition section.</td></tr>
<tr><td>&quot;runtime&quot;</td><td>This code is inserted near the end of the C
 wrapper file.</td></tr>
<tr><td>&quot;mli&quot;</td><td>This code is inserted into the caml interface
 file. Special signatures should be inserted here.</td></tr>
<tr><td>&quot;ml&quot;</td><td>This code is inserted in the caml code defining the
 interface to your C code. Special caml code, as well as any
 initialization which should run when the module is loaded may be
 inserted here.</td></tr>
<tr><td>&quot;classtemplate&quot;</td><td>The &quot;classtemplate&quot; place is special
 because it describes the output SWIG will generate for class
 definitions.</td></tr>
</table>
<h3><a name="Ocaml_nn10">38.2.2 Enums</a></h3>
<p> SWIG will wrap enumerations as polymorphic variants in the output
 Ocaml code, as above in C_enum. In order to support all C++-style uses
 of enums, the function int_to_enum and enum_to_int are provided for
 ocaml code to produce and consume these values as integers. Other than
 that, correct uses of enums will not have a problem. Since enum labels
 may overlap between enums, the enum_to_int and int_to_enum functions
 take an enum type label as an argument. Example:</p>
<div class="code">
<pre>
%module enum_test
%{
enum c_enum_type { a = 1, b, c = 4, d = 8 };
%}
enum c_enum_type { a = 1, b, c = 4, d = 8 };
</pre>
</div>
<p> The output mli contains:</p>
<div class="code">
<pre>
type c_enum_type = [
  `unknown
| `c_enum_type
]
type c_enum_tag = [
  `int of int
| `a
| `b
| `c
| `d
]
val int_to_enum c_enum_type -&gt; int -&gt; c_obj
val enum_to_int c_enum_type -&gt; c_obj -&gt; c_obj
</pre>
</div>
<p> So it's possible to do this:</p>
<div class="code">
<pre>
bash-2.05a$ ocamlmktop -custom enum_test_wrap.o enum_test.cmo -o enum_test_top
bash-2.05a$ ./enum_test_top
        Objective Caml version 3.04

# open Enum_test ;;
# let x = C_enum `a ;;
val x : Enum_test.c_obj = C_enum `a
# enum_to_int `c_enum_type x ;;
- : Enum_test.c_obj = C_int 1
# int_to_enum `c_enum_type 4 ;;
- : Enum_test.c_obj = C_enum `c
</pre>
</div>
<h4><a name="Ocaml_nn11">38.2.2.1 Enum typing in Ocaml</a></h4>
<p> The ocaml SWIG module now has support for loading and using multiple
 SWIG modules at the same time. This enhances modularity, but presents
 problems when used with a language which assumes that each module's
 types are complete at compile time. In order to achieve total soundness
 enum types are now isolated per-module. The type issue matters when
 values are shared between functions imported from different modules.
 You must convert values to master values using the swig_val function
 before sharing them with another module.</p>
<h3><a name="Ocaml_nn12">38.2.3 Arrays</a></h3>
<h4><a name="Ocaml_nn13">38.2.3.1 Simple types of bounded arrays</a></h4>
<p> SWIG has support for array types, but you generally will need to
 provide a typemap to handle them. You can currently roll your own, or
 expand some of the macros provided (but not included by default) with
 the SWIG distribution.</p>
<p> By including &quot;carray.i&quot;, you will get access to some macros that
 help you create typemaps for array types fairly easily.</p>
<p> <tt>%make_simple_array_typemap</tt> is the easiest way to get access
 to arrays of simple types with known bounds in your code, but this only
 works for arrays whose bounds are completely specified.</p>
<h4><a name="Ocaml_nn14">38.2.3.2 Complex and unbounded arrays</a></h4>
<p> Unfortunately, unbounded arrays and pointers can't be handled in a
 completely general way by SWIG, because the end-condition of such an
 array can't be predicted. In some cases, it will be by consent (e.g. an
 array of four or more chars), sometimes by explicit length (char
 *buffer, int len), and sometimes by sentinel value (0, -1, etc.). SWIG
 can't predict which of these methods will be used in the array, so you
 have to specify it for yourself in the form of a typemap.</p>
<h4><a name="Ocaml_nn15">38.2.3.3 Using an object</a></h4>
<p> It's possible to use C++ to your advantage by creating a simple
 object that provides access to your array. This may be more desirable
 in some cases, since the object can provide bounds checking, etc., that
 prevents crashes.</p>
<p> Consider writing an object when the ending condition of your array
 is complex, such as using a required sentinel, etc.</p>
<h4><a name="Ocaml_nn16">38.2.3.4 Example typemap for a function taking
 float * and int</a></h4>
<p> This is a simple example <tt>in</tt> typemap for an array of float,
 where the length of the array is specified as an extra parameter. Other
 such typemaps will work similarly. In the example, the function
 printfloats is called with a float array, and specified length. The
 actual length reported in the len argument is the length of the array
 passed from ocaml, making passing an array into this type of function
 convenient.</p>
<table bgcolor="#dddddd" border="1" summary="float * and int typemap example">
<tr><th>
<center>tarray.i</center>
</th></tr>
<tr><td>
<pre>
%module tarray
%{
#include &lt;stdio.h&gt;

void printfloats( float *tab, int len ) {
  int i;

  for( i = 0; i &lt; len; i++ ) {
    printf( &quot;%f &quot;, tab[i] );
  }

  printf( &quot;\n&quot; );
}
%}

%typemap(in) (float *tab, int len) {
  int i;
  /* $*1_type */
  $2 = caml_array_len($input);
  $1 = ($*1_type *)malloc( $2 * sizeof( float ) );
  for( i = 0; i &lt; $2; i++ ) {
    $1[i] = caml_double_val(caml_array_nth($input, i));
  }
}

void printfloats( float *tab, int len );
</pre>
</td></tr>
<tr><th>Sample Run</th></tr>
<tr><td>
<pre>
# open Tarray ;;
# _printfloats (C_array [| C_double 1.0 ; C_double 3.0 ; C_double 5.6666 |]) ;;
1.000000 3.000000 5.666600
- : Tarray.c_obj = C_void
</pre>
</td></tr>
</table>
<h3><a name="Ocaml_nn17">38.2.4 C++ Classes</a></h3>
<p> C++ classes, along with structs and unions are represented by C_obj
 (string -&gt; c_obj -&gt; c_obj) wrapped closures. These objects contain a
 method list, and a type, which allow them to be used like C++ objects.
 When passed into typemaps that use pointers, they degrade to pointers
 through their &quot;&amp;&quot; method. Every method an object has is represented as
 a string in the object's method table, and each method table exists in
 memory only once. In addition to any other operators an object might
 have, certain builtin ones are provided by SWIG: (all of these take no
 arguments (C_void))</p>
<table summary="SWIG provided operators">
<tr><td>&quot;~&quot;</td><td>Delete this object</td></tr>
<tr><td>&quot;&amp;&quot;</td><td>Return an ordinary C_ptr value representing this
 object's address</td></tr>
<tr><td>&quot;sizeof&quot;</td><td>If enabled with (&quot;sizeof&quot;=&quot;1&quot;) on the module
 node, return the object's size in char.</td></tr>
<tr><td>&quot;:methods&quot;</td><td>Returns a list of strings containing the
 names of the methods this object contains</td></tr>
<tr><td>&quot;:classof&quot;</td><td>Returns the name of the class this object
 belongs to.</td></tr>
<tr><td>&quot;:parents&quot;</td><td>Returns a list of all direct parent classes
 which have been wrapped by SWIG.</td></tr>
<tr><td>&quot;::[parent-class]&quot;</td><td>Returns a view of the object as the
 indicated parent class. This is mainly used internally by the SWIG
 module, but may be useful to client programs.</td></tr>
<tr><td>&quot;[member-variable]&quot;</td><td>Each member variable is wrapped as a
 method with an optional parameter. Called with one argument, the member
 variable is set to the value of the argument. With zero arguments, the
 value is returned.</td></tr>
</table>
<p> Note that this string belongs to the wrapper object, and not the
 underlying pointer, so using create_[x]_from_ptr alters the returned
 value for the same object.</p>
<h4><a name="Ocaml_nn18">38.2.4.1 STL vector and string Example</a></h4>
<p> Standard typemaps are now provided for STL vector and string. More
 are in the works. STL strings are passed just like normal strings, and
 returned as strings. STL string references don't mutate the original
 string, (which might be surprising), because Ocaml strings are mutable
 but have fixed length. Instead, use multiple returns, as in the
 argout_ref example.</p>
<table bgcolor="#dddddd" border="1" summary="STL vector and string example">
<tr><th>
<center>example.i</center>
</th></tr>
<tr><td>
<pre>
%module example
%{
#include &quot;example.h&quot;
%}

%include &lt;stl.i&gt;

namespace std {
  %template(StringVector) std::vector &lt; string &gt;;
};

%include &quot;example.h&quot;
</pre>
</td></tr>
<tr><td><font size="-1"><i>This example is in Examples/ocaml/stl</i></font>
</td></tr>
</table>
<p> Since there's a makefile in that directory, the example is easy to
 build.</p>
<p> Here's a sample transcript of an interactive session using a string
 vector after making a toplevel (make toplevel). This example uses the
 camlp4 module.</p>
<div class="code">
<pre>
bash-2.05a$ ./runme_top
        Objective Caml version 3.06

        Camlp4 Parsing version 3.06

# open Swig ;;
# open Example ;;
# let x = new_StringVector '() ;;
val x : Example.c_obj = C_obj &lt;fun&gt;
# x -&gt; &quot;:methods&quot; () ;;
- : Example.c_obj =
C_list
 [C_string &quot;nop&quot;; C_string &quot;size&quot;; C_string &quot;empty&quot;; C_string &quot;clear&quot;;
  C_string &quot;push_back&quot;; C_string &quot;[]&quot;; C_string &quot;=&quot;; C_string &quot;set&quot;;
  C_string &quot;~&quot;; C_string &quot;&amp;&quot;; C_string &quot;:parents&quot;; C_string &quot;:classof&quot;;
  C_string &quot;:methods&quot;]
# x -&gt; push_back (&quot;foo&quot;) ;;
- : Example.c_obj = C_void
# x -&gt; push_back (&quot;bar&quot;) ;;
- : Example.c_obj = C_void
# x -&gt; push_back (&quot;baz&quot;) ;;
- : Example.c_obj = C_void
# x '[1] ;;
- : Example.c_obj = C_string &quot;bar&quot;
# x -&gt; set (1, &quot;spam&quot;) ;;
- : Example.c_obj = C_void
# x '[1] ;;
- : Example.c_obj = C_string &quot;spam&quot;
# for i = 0 to (x -&gt; size() as int) - 1 do
    print_endline ((x '[i to int]) as string)
  done ;;
foo
bar
baz
- : unit = ()
#
</pre>
</div>
<h4><a name="Ocaml_nn19">38.2.4.2 C++ Class Example</a></h4>
<p> Here's a simple example using Trolltech's Qt Library:</p>
<table bgcolor="#dddddd" border="1" summary="Qt Library example">
<tr><th>
<center>qt.i</center>
</th></tr>
<tr><td>
<pre>
%module qt
%{
#include &lt;qapplication.h&gt;
#include &lt;qpushbutton.h&gt;
%}
class QApplication {
public:
  QApplication( int argc, char **argv );
  void setMainWidget( QWidget *widget );
  void exec();
};

class QPushButton {
public:
  QPushButton( char *str, QWidget *w );
  void resize( int x, int y );
  void show();
};
</pre>
</td></tr>
</table>
<h4><a name="Ocaml_nn20">38.2.4.3 Compiling the example</a></h4>
<div class="code">
<pre>
bash-2.05a$ QTPATH=/your/qt/path
bash-2.05a$ for file in swig.mli swig.ml swigp4.ml ; do swig -ocaml -co $file ; done
bash-2.05a$ ocamlc -c swig.mli ; ocamlc -c swig.ml
bash-2.05a$ ocamlc -I `camlp4 -where` -pp &quot;camlp4o pa_extend.cmo q_MLast.cmo&quot; -c swigp4.ml
bash-2.05a$ swig -ocaml -c++ -I$QTPATH/include qt.i
bash-2.05a$ mv qt_wrap.cxx qt_wrap.c
bash-2.05a$ ocamlc -c -ccopt -xc++ -ccopt -g -g -ccopt -I$QTPATH/include qt_wrap.c
bash-2.05a$ ocamlc -c qt.mli
bash-2.05a$ ocamlc -c qt.ml
bash-2.05a$ ocamlmktop -custom swig.cmo -I `camlp4 -where` \
  camlp4o.cma swigp4.cmo qt_wrap.o qt.cmo -o qt_top -cclib \
  -L$QTPATH/lib -cclib -lqt
</pre>
</div>
<h4><a name="Ocaml_nn21">38.2.4.4 Sample Session</a></h4>
<div class="code">
<pre>
bash-2.05a$ ./qt_top
        Objective Caml version 3.06

        Camlp4 Parsing version 3.06

# open Swig ;;
# open Qt ;;
# let a = new_QApplication '(0, 0) ;;
val a : Qt.c_obj = C_obj &lt;fun&gt;
# let hello = new_QPushButton '(&quot;hi&quot;, 0) ;;
val hello : Qt.c_obj = C_obj &lt;fun&gt;
# hello -&gt; resize (100, 30) ;;
- : Qt.c_obj = C_void
# hello -&gt; show () ;;
- : Qt.c_obj = C_void
# a -&gt; exec () ;;
</pre>
</div>
<p> Assuming you have a working installation of QT, you will see a
 window containing the string &quot;hi&quot; in a button.</p>
<h3><a name="Ocaml_nn22">38.2.5 Director Classes</a></h3>
<h4><a name="Ocaml_nn23">38.2.5.1 Director Introduction</a></h4>
<p> Director classes are classes which allow Ocaml code to override the
 public methods of a C++ object. This facility allows the user to use
 C++ libraries that require a derived class to provide application
 specific functionality in the context of an application or utility
 framework.</p>
<p> You can turn on director classes by using an optional module
 argument like this:</p>
<div class="code">
<pre>
%module(directors=&quot;1&quot;)

...

// Turn on the director class for a specific class like this:
%feature(&quot;director&quot;)
class foo {
  ...
};
</pre>
</div>
<h4><a name="Ocaml_nn24">38.2.5.2 Overriding Methods in Ocaml</a></h4>
<p> Because the Ocaml language module treats C++ method calls as calls
 to a certain function, all you need to do is to define the function
 that will handle the method calls in terms of the public methods of the
 object, and any other relevant information. The function <tt>
new_derived_object</tt> uses a stub class to call your methods in place
 of the ones provided by the underlying implementation. The object you
 receive is the underlying object, so you are free to call any methods
 you want from within your derived method. Note that calls to the
 underlying object do not invoke Ocaml code. You need to handle that
 yourself.</p>
<p> <tt>new_derived_object</tt> receives your function, the function
 that creates the underlying object, and any constructor arguments, and
 provides an object that you can use in any usual way. When C++ code
 calls one of the object's methods, the object invokes the Ocaml
 function as if it had been invoked from Ocaml, allowing any method
 definitions to override the C++ ones.</p>
<p> In this example, I'll examine the objective caml code involved in
 providing an overloaded class. This example is contained in
 Examples/ocaml/shapes.</p>
<h4><a name="Ocaml_nn25">38.2.5.3 Director Usage Example</a></h4>
<table bgcolor="#dddddd" border="1" summary="Director usage example">
<tr><th>
<center>runme.ml</center>
</th></tr>
<tr><td>
<pre>
open Swig
open Example

...

let triangle_class pts ob meth args =
  match meth with
      &quot;cover&quot; -&gt;
        (match args with
             C_list [ x_arg ; y_arg ] -&gt;
             let xa = x_arg as float
             and ya = y_arg as float in
               (point_in_triangle pts xa ya) to bool
           | _ -&gt; raise (Failure &quot;cover needs two double arguments.&quot;))
    | _ -&gt; (invoke ob) meth args ;;

...

let triangle =
  new_derived_object
    new_shape
    (triangle_class ((0.0, 0.0), (0.5, 1.0), (1.0, 0.6)))
    '() ;;

let _ = _draw_shape_coverage '(triangle, 60, 20) ;;
</pre>
</td></tr>
</table>
<p> This is the meat of what you need to do. The actual &quot;class&quot;
 definition containing the overloaded method is defined in the function
 triangle_class. This is a lot like the class definitions emitted by
 SWIG, if you look at example.ml, which is generated when SWIG consumes
 example.i. Basically, you are given the arguments as a c_obj and the
 method name as a string, and you must intercept the method you are
 interested in and provide whatever return value you need. Bear in mind
 that the underlying C++ code needs the right return type, or an
 exception will be thrown. This exception will generally be Failure, or
 NotObject. You must call other ocaml methods that you rely on yourself.
 Due to the way directors are implemented, method calls on your object
 from with ocaml code will always invoke C++ methods even if they are
 overridden in ocaml.</p>
<p> In the example, the draw_shape_coverage function plots the indicated
 number of points as either covered (<tt>x</tt>) or uncovered ( )
 between 0 and 1 on the X and Y axes. Your shape implementation can
 provide any coverage map it likes, as long as it responds to the
 &quot;cover&quot; method call with a boolean return (the underlying method
 returns bool). This might allow a tricky shape implementation, such as
 a boolean combination, to be expressed in a more effortless style in
 ocaml, while leaving the &quot;engine&quot; part of the program in C++.</p>
<h4><a name="Ocaml_nn26">38.2.5.4 Creating director objects</a></h4>
<p> The definition of the actual object triangle can be described this
 way:</p>
<div class="code">
<pre>
let triangle =
  new_derived_object
    new_shape
    (triangle_class ((0.0, 0.0), (0.5, 1.0), (1.0, 0.0)))
    '()
</pre>
</div>
<p> The first argument to <tt>new_derived_object</tt>, new_shape is the
 method which returns a shape instance. This function will be invoked
 with the third argument will be appended to the argument list [ C_void
 ]. In the example, the actual argument list is sent as (C_list [ C_void
 ; C_void ]). The augmented constructor for a director class needs the
 first argument to determine whether it is being constructed as a
 derived object, or as an object of the indicated type only (in this
 case <tt>shape</tt>). The Second argument is a closure that will be
 added to the final C_obj.</p>
<p> The actual object passed to the self parameter of the director
 object will be a C_director_core, containing a c_obj option ref and a
 c_obj. The c_obj provided is the same object that will be returned from
 new_derived object, that is, the object exposing the overridden
 methods. The other part is an option ref that will have its value
 extracted before becoming the <tt>ob</tt> parameter of your class
 closure. This ref will contain <tt>None</tt> if the C++ object
 underlying is ever destroyed, and will consequently trigger an
 exception when any method is called on the object after that point (the
 actual raise is from an inner function used by new_derived_object, and
 throws NotObject). This prevents a deleted C++ object from causing a
 core dump, as long as the object is destroyed properly.</p>
<h4><a name="Ocaml_nn27">38.2.5.5 Typemaps for directors, directorin,
 directorout, directorargout</a></h4>
<p> Special typemaps exist for use with directors, the <tt>directorin,
 directorout, directorargout</tt> are used in place of <tt>in, out,
 argout</tt> typemaps, except that their direction is reversed. They
 provide for you to provide argout values, as well as a function return
 value in the same way you provide function arguments, and to receive
 arguments the same way you normally receive function returns.</p>
<h4><a name="Ocaml_nn28">38.2.5.6 directorin typemap</a></h4>
<p> The <tt>directorin</tt> typemap is used when you will receive
 arguments from a call made by C++ code to you, therefore, values will
 be translated from C++ to ocaml. You must provide some valid C_obj
 value. This is the value your ocaml code receives when you are called.
 In general, a simple <tt>directorin</tt> typemap can use the same body
 as a simple <tt>out</tt> typemap.</p>
<h4><a name="Ocaml_nn29">38.2.5.7 directorout typemap</a></h4>
<p> The <tt>directorout</tt> typemap is used when you will send an
 argument from your code back to the C++ caller. That is; directorout
 specifies a function return conversion. You can usually use the same
 body as an <tt>in</tt> typemap for the same type, except when there are
 special requirements for object ownership, etc.</p>
<h4><a name="Ocaml_nn30">38.2.5.8 directorargout typemap</a></h4>
<p> C++ allows function arguments which are by pointer (*) and by
 reference (&amp;) to receive a value from the called function, as well as
 sending one there. Sometimes, this is the main purpose of the argument
 given. <tt>directorargout</tt> typemaps allow your caml code to emulate
 this by specifying additional return values to be put into the output
 parameters. The SWIG ocaml module is a bit loose in order to make code
 easier to write. In this case, your return to the caller must be a list
 containing the normal function return first, followed by any argout
 values in order. These argout values will be taken from the list and
 assigned to the values to be returned to C++ through directorargout
 typemaps. In the event that you don't specify all of the necessary
 values, integral values will read zero, and struct or object returns
 have undefined results.</p>
<h3><a name="Ocaml_nn31">38.2.6 Exceptions</a></h3>
<p> If an error occurs in a C or C++ function, you may want to convert
 that error into an OCaml exception. To do this, you can use the <tt>
%exception</tt> directive. The <tt>%exception</tt> directive simply lets
 you rewrite part of the generated wrapper code to include an error
 check. It is detailed in full in the <a href="#Customization_exception">
Exception handling with %exception</a> section.</p>
<p> In C, a function often indicates an error by returning a status code
 (e.g. a negative number or a NULL pointer). Here is a simple example of
 how you might handle that:</p>
<div class="code">
<pre>
%exception malloc {
  $action
  if (result == NULL) {
    caml_failwith(&quot;Not enough memory&quot;);
  }
}
void *malloc(size_t nbytes);
</pre>
</div>
<p> In OCaml:</p>
<div class="code">
<pre>
# let a = _malloc (C_int 20000000000);;
Exception: Failure &quot;Not enough memory&quot;.
#
</pre>
</div>
<p> If a library provides some kind of general error handling framework,
 you can also use that. For example:</p>
<div class="code">
<pre>
%exception {
  $action
  if (err_occurred()) {
    caml_failwith(err_message());
  }
}
</pre>
</div>
<p> If no declaration name is given to <tt>%exception</tt>, it is
 applied to all wrapper functions. <tt>$action</tt> is a SWIG special
 variable and is replaced by the C/C++ function call being wrapped.</p>
<p> C++ exceptions are also easy to handle. We can catch a C++ exception
 and rethrow it as an OCaml exception like this:</p>
<div class="code">
<pre>
%exception getitem {
  try {
    $action
  } catch (std::out_of_range &amp;e) {
    caml_failwith(e.what());
  }
}

class FooClass {
  public:
    int getitem(int index);      // Exception handling added
    ...
};
</pre>
</div>
<p> The language-independent <tt>exception.i</tt> library file can also
 be used to raise exceptions. See the <a href="#Library">SWIG Library</a>
 chapter.</p>
<h2><a name="Ocaml_nn32">38.3 Documentation Features</a></h2>
<p> The features described in this section can be used to generate
 documentation comments (colloquially referred to as &quot;docstrings&quot;) that
 can be read by <a href="https://caml.inria.fr/pub/docs/manual-ocaml/ocamldoc.html">
OCamldoc</a>.</p>
<h3><a name="Ocaml_nn33">38.3.1 Module docstring</a></h3>
<p> The first documentation comment of an <tt>mli</tt> file is the
 comment associated with the entire module. SWIG supports this by
 setting an option of the <tt>%module</tt> directive. For example:</p>
<div class="code">
<pre>
%module(docstring=&quot;This is the example module's docstring&quot;) example
</pre>
</div>
<p> When you have more than just a line or so, you can retain the
 readability of the <tt>%module</tt> directive by using a macro. For
 example:</p>
<div class="code">
<pre>
%define DOCSTRING
&quot;The `XmlResource` class allows program resources defining menus,
controls on a panel, etc. to be loaded from an XML file.&quot;
%enddef

%module(docstring=DOCSTRING) xrc
</pre>
</div><HR NOSHADE>
<h1><a name="Extending">39 Extending SWIG to support new languages</a></h1>

<!-- INDEX -->
<div class="sectiontoc">
<ul>
<li><a href="#Extending_nn2">Introduction</a></li>
<li><a href="#Extending_nn3">Prerequisites</a></li>
<li><a href="#Extending_nn4">The Big Picture</a></li>
<li><a href="#Extending_nn5">Execution Model</a>
<ul>
<li><a href="#Extending_nn6">Preprocessing</a></li>
<li><a href="#Extending_nn7">Parsing</a></li>
<li><a href="#Extending_nn8">Parse Trees</a></li>
<li><a href="#Extending_nn9">Attribute namespaces</a></li>
<li><a href="#Extending_nn10">Symbol Tables</a></li>
<li><a href="#Extending_nn11">The %feature directive</a></li>
<li><a href="#Extending_nn12">Code Generation</a></li>
<li><a href="#Extending_nn13">SWIG and XML</a></li>
</ul>
</li>
<li><a href="#Extending_nn14">Primitive Data Structures</a>
<ul>
<li><a href="#Extending_nn15">Strings</a></li>
<li><a href="#Extending_nn16">Hashes</a></li>
<li><a href="#Extending_nn17">Lists</a></li>
<li><a href="#Extending_nn18">Common operations</a></li>
<li><a href="#Extending_nn19">Iterating over Lists and Hashes</a></li>
<li><a href="#Extending_nn20">I/O</a></li>
</ul>
</li>
<li><a href="#Extending_nn21">Navigating and manipulating parse trees</a>
</li>
<li><a href="#Extending_nn22">Working with attributes</a></li>
<li><a href="#Extending_nn23">Type system</a>
<ul>
<li><a href="#Extending_nn24">String encoding of types</a></li>
<li><a href="#Extending_nn25">Type construction</a></li>
<li><a href="#Extending_nn26">Type tests</a></li>
<li><a href="#Extending_nn27">Typedef and inheritance</a></li>
<li><a href="#Extending_nn28">Lvalues</a></li>
<li><a href="#Extending_nn29">Output functions</a></li>
</ul>
</li>
<li><a href="#Extending_nn30">Parameters</a></li>
<li><a href="#Extending_nn31">Writing a Language Module</a>
<ul>
<li><a href="#Extending_nn32">Execution model</a></li>
<li><a href="#Extending_starting_out">Starting out</a></li>
<li><a href="#Extending_nn34">Command line options</a></li>
<li><a href="#Extending_nn35">Configuration and preprocessing</a></li>
<li><a href="#Extending_nn36">Entry point to code generation</a></li>
<li><a href="#Extending_nn37">Module I/O and wrapper skeleton</a></li>
<li><a href="#Extending_nn38">Low-level code generators</a></li>
<li><a href="#Extending_configuration_files">Configuration files</a></li>
<li><a href="#Extending_nn40">Runtime support</a></li>
<li><a href="#Extending_nn41">Standard library files</a></li>
<li><a href="#Extending_nn42">User examples</a></li>
<li><a href="#Extending_test_suite">Test driven development and the
 test-suite</a>
<ul>
<li><a href="#Extending_running_test_suite">Running the test-suite</a></li>
</ul>
</li>
<li><a href="#Extending_nn43">Documentation</a></li>
<li><a href="#Extending_coding_style_guidelines">Coding style guidelines</a>
</li>
<li><a href="#Extending_language_status">Target language status</a>
<ul>
<li><a href="#Extending_supported_status">Supported status</a></li>
<li><a href="#Extending_experimental_status">Experimental status</a></li>
</ul>
</li>
<li><a href="#Extending_prerequisites">Prerequisites for adding a new
 language module to the SWIG distribution</a></li>
</ul>
</li>
<li><a href="#Extending_debugging_options">Debugging Options</a></li>
<li><a href="#Extending_nn46">Guide to parse tree nodes</a></li>
<li><a href="#Extending_further_info">Further Development Information</a>
</li>
</ul>
</div>
<!-- INDEX -->
<h2><a name="Extending_nn2">39.1 Introduction</a></h2>
<p> This chapter describes SWIG's internal organization and the process
 by which new target languages can be developed. First, a brief word of
 warning---SWIG is continually evolving. The information in this chapter
 is mostly up to date, but changes are ongoing. Expect a few
 inconsistencies.</p>
<p> Also, this chapter is not meant to be a hand-holding tutorial. As a
 starting point, you should probably look at one of SWIG's existing
 modules.</p>
<h2><a name="Extending_nn3">39.2 Prerequisites</a></h2>
<p> In order to extend SWIG, it is useful to have the following
 background:</p>
<ul>
<li>An understanding of the C API for the target language.</li>
<li>A good grasp of the C++ type system.</li>
<li>An understanding of typemaps and some of SWIG's advanced features.</li>
<li>Some familiarity with writing C++ (language modules are currently
 written in C++).</li>
</ul>
<p> Since SWIG is essentially a specialized C++ compiler, it may be
 useful to have some prior experience with compiler design (perhaps even
 a compilers course) to better understand certain parts of the system. A
 number of books will also be useful. For example, &quot;The C Programming
 Language&quot; by Kernighan and Ritchie (a.k.a, &quot;K&amp;R&quot;) and the C++ standard,
 &quot;ISO/IEC 14882 Programming Languages - C++&quot; will be of great use.</p>
<p> Also, it is useful to keep in mind that SWIG primarily operates as
 an extension of the C++<em> type</em> system. At first glance, this
 might not be obvious, but almost all SWIG directives as well as the
 low-level generation of wrapper code are driven by C++ datatypes.</p>
<h2><a name="Extending_nn4">39.3 The Big Picture</a></h2>
<p> SWIG is a special purpose compiler that parses C++ declarations to
 generate wrapper code. To make this conversion possible, SWIG makes
 three fundamental extensions to the C++ language:</p>
<ul>
<li><b>Typemaps</b>. Typemaps are used to define the
 conversion/marshalling behavior of specific C++ datatypes. All type
 conversion in SWIG is based on typemaps. Furthermore, the association
 of typemaps to datatypes utilizes an advanced pattern matching
 mechanism that is fully integrated with the C++ type system.</li>
<li><b>Declaration Annotation</b>. To customize wrapper code generation,
 most declarations can be annotated with special features. For example,
 you can make a variable read-only, you can ignore a declaration, you
 can rename a member function, you can add exception handling, and so
 forth. Virtually all of these customizations are built on top of a
 low-level declaration annotator that can attach arbitrary attributes to
 any declaration. Code generation modules can look for these attributes
 to guide the wrapping process.</li>
<li><b>Class extension</b>. SWIG allows classes and structures to be
 extended with new methods and attributes (the <tt>%extend</tt>
 directive). This has the effect of altering the API in the target
 language and can be used to generate OO interfaces to C libraries.</li>
</ul>
<p> It is important to emphasize that virtually all SWIG features reduce
 to one of these three fundamental concepts. The type system and pattern
 matching rules also play a critical role in making the system work. For
 example, both typemaps and declaration annotation are based on pattern
 matching and interact heavily with the underlying type system.</p>
<h2><a name="Extending_nn5">39.4 Execution Model</a></h2>
<p> When you run SWIG on an interface, processing is handled in stages
 by a series of system components:</p>
<ul>
<li>An integrated C preprocessor reads a collection of configuration
 files and the specified interface file into memory. The preprocessor
 performs the usual functions including macro expansion and file
 inclusion. However, the preprocessor also performs some transformations
 of the interface. For instance, <tt>#define</tt> statements are
 sometimes transformed into <tt>%constant</tt> declarations. In
 addition, information related to file/line number tracking is inserted.</li>
<li>A C/C++ parser reads the preprocessed input and generates a full
 parse tree of all of the SWIG directives and C declarations found. The
 parser is responsible for many aspects of the system including
 renaming, declaration annotation, and template expansion. However, the
 parser does not produce any output nor does it interact with the target
 language module as it runs. SWIG is not a one-pass compiler.</li>
<li>A type-checking pass is made. This adjusts all of the C++ typenames
 to properly handle namespaces, typedefs, nested classes, and other
 issues related to type scoping.</li>
<li>A semantic pass is made on the parse tree to collect information
 related to properties of the C++ interface. For example, this pass
 would determine whether or not a class allows a default constructor.</li>
<li>A code generation pass is made using a specific target language
 module. This phase is responsible for generating the actual wrapper
 code. All of SWIG's user-defined modules are invoked during this latter
 stage of compilation.</li>
</ul>
<p> The next few sections briefly describe some of these stages.</p>
<h3><a name="Extending_nn6">39.4.1 Preprocessing</a></h3>
<p> The preprocessor plays a critical role in the SWIG implementation.
 This is because a lot of SWIG's processing and internal configuration
 is managed not by code written in C, but by configuration files in the
 SWIG library. In fact, when you run SWIG, parsing starts with a small
 interface file like this (note: this explains the cryptic error
 messages that new users sometimes get when SWIG is misconfigured or
 installed incorrectly):</p>
<div class="code">
<pre>
%include &quot;swig.swg&quot;             // Global SWIG configuration
%include &quot;<em>langconfig.swg</em>&quot;       // Language specific configuration
%include &quot;yourinterface.i&quot;      // Your interface file
</pre>
</div>
<p> The <tt>swig.swg</tt> file contains global configuration
 information. In addition, this file defines many of SWIG's standard
 directives as macros. For instance, part of of <tt>swig.swg</tt> looks
 like this:</p>
<div class="code">
<pre>
...
/* Code insertion directives such as %wrapper %{ ... %} */

#define %begin       %insert(&quot;begin&quot;)
#define %runtime     %insert(&quot;runtime&quot;)
#define %header      %insert(&quot;header&quot;)
#define %wrapper     %insert(&quot;wrapper&quot;)
#define %init        %insert(&quot;init&quot;)

/* Access control directives */

#define %immutable   %feature(&quot;immutable&quot;, &quot;1&quot;)
#define %mutable     %feature(&quot;immutable&quot;)

/* Directives for callback functions */

#define %callback(x) %feature(&quot;callback&quot;) `x`;
#define %nocallback  %feature(&quot;callback&quot;);

/* %ignore directive */

#define %ignore         %rename($ignore)
#define %ignorewarn(x)  %rename(&quot;$ignore:&quot; x)
...
</pre>
</div>
<p> The fact that most of the standard SWIG directives are macros is
 intended to simplify the implementation of the internals. For instance,
 rather than having to support dozens of special directives, it is
 easier to have a few basic primitives such as <tt>%feature</tt> or <tt>
%insert</tt>.</p>
<p> The<em> <tt>langconfig.swg</tt></em> file is supplied by the target
 language. This file contains language-specific configuration
 information. More often than not, this file provides run-time wrapper
 support code (e.g., the type-checker) as well as a collection of
 typemaps that define the default wrapping behavior. Note: the name of
 this file depends on the target language and is usually something like <tt>
python.swg</tt> or <tt>perl5.swg</tt>.</p>
<p> As a debugging aid, the text that SWIG feeds to its C++ parser can
 be obtained by running <tt>swig -E interface.i</tt>. This output
 probably isn't too useful in general, but it will show how macros have
 been expanded as well as everything else that goes into the low-level
 construction of the wrapper code.</p>
<h3><a name="Extending_nn7">39.4.2 Parsing</a></h3>
<p> The current C++ parser handles a subset of C++. Most
 incompatibilities with C are due to subtle aspects of how SWIG parses
 declarations. Specifically, SWIG expects all C/C++ declarations to
 follow this general form:</p>
<div class="diagram">
<pre>
<em>storage</em> <em>type</em> <em>declarator</em> <em>initializer</em>;
</pre>
</div>
<p> <tt><em>storage</em></tt> is a keyword such as <tt>extern</tt>, <tt>
static</tt>, <tt>typedef</tt>, or <tt>virtual</tt>. <tt><em>type</em></tt>
 is a primitive datatype such as <tt>int</tt> or <tt>void</tt>. <tt><em>
type</em></tt> may be optionally qualified with a qualifier such as <tt>
const</tt> or <tt>volatile</tt>. <tt><em>declarator</em></tt> is a name
 with additional type-construction modifiers attached to it (pointers,
 arrays, references, functions, etc.). Examples of declarators include <tt>
*x</tt>, <tt>**x</tt>, <tt>x[20]</tt>, and <tt>(*x)(int, double)</tt>.
 The <tt><em>initializer</em></tt> may be a value assigned using <tt>=</tt>
 or body of code enclosed in braces <tt>{ ... }</tt>.</p>
<p> This declaration format covers most common C++ declarations.
 However, the C++ standard is somewhat more flexible in the placement of
 the parts. For example, it is technically legal, although uncommon to
 write something like <tt>int typedef const a</tt> in your program. SWIG
 simply doesn't bother to deal with this case.</p>
<p> The other significant difference between C++ and SWIG is in the
 treatment of typenames. In C++, if you have a declaration like this,</p>
<div class="code">
<pre>
int blah(Foo *x, Bar *y);
</pre>
</div>
<p> it won't parse correctly unless <tt>Foo</tt> and <tt>Bar</tt> have
 been previously defined as types either using a <tt>class</tt>
 definition or a <tt>typedef</tt>. The reasons for this are subtle, but
 this treatment of typenames is normally integrated at the level of the
 C tokenizer---when a typename appears, a different token is returned to
 the parser instead of an identifier.</p>
<p> SWIG does not operate in this manner--any legal identifier can be
 used as a type name. The reason for this is primarily motivated by the
 use of SWIG with partially defined data. Specifically, SWIG is supposed
 to be easy to use on interfaces with missing type information.</p>
<p> Because of the different treatment of typenames, the most serious
 limitation of the SWIG parser is that it can't process type
 declarations where an extra (and unnecessary) grouping operator is
 used. For example:</p>
<div class="code">
<pre>
int (x);         /* A variable x */
int (y)(int);    /* A function y */
</pre>
</div>
<p> The placing of extra parentheses in type declarations like this is
 already recognized by the C++ community as a potential source of
 strange programming errors. For example, Scott Meyers &quot;Effective STL&quot;
 discusses this problem in a section on avoiding C++'s &quot;most vexing
 parse.&quot;</p>
<p> The parser is also unable to handle declarations with no return type
 or bare argument names. For example, in an old C program, you might see
 things like this:</p>
<div class="code">
<pre>
foo(a, b) {
...
}
</pre>
</div>
<p> In this case, the return type as well as the types of the arguments
 are taken by the C compiler to be an <tt>int</tt>. However, SWIG
 interprets the above code as an abstract declarator for a function
 returning a <tt>foo</tt> and taking types <tt>a</tt> and <tt>b</tt> as
 arguments).</p>
<h3><a name="Extending_nn8">39.4.3 Parse Trees</a></h3>
<p> The SWIG parser produces a complete parse tree of the input file
 before any wrapper code is actually generated. Each item in the tree is
 known as a &quot;Node&quot;. Each node is identified by a symbolic tag.
 Furthermore, a node may have an arbitrary number of children. The parse
 tree structure and tag names of an interface can be displayed using <tt>
swig -debug-tags</tt>. For example:</p>
<div class="shell">
<pre>
$ <b>swig -c++ -python -debug-tags example.i</b>
 . top (example.i:1)
 . top . include (example.i:1)
 . top . include . typemap (/r0/beazley/Projects/lib/swig1.3/swig.swg:71)
 . top . include . typemap . typemapitem (/r0/beazley/Projects/lib/swig1.3/swig.swg:71)
 . top . include . typemap (/r0/beazley/Projects/lib/swig1.3/swig.swg:83)
 . top . include . typemap . typemapitem (/r0/beazley/Projects/lib/swig1.3/swig.swg:83)
 . top . include (example.i:4)
 . top . include . insert (/r0/beazley/Projects/lib/swig1.3/python/python.swg:7)
 . top . include . insert (/r0/beazley/Projects/lib/swig1.3/python/python.swg:8)
 . top . include . typemap (/r0/beazley/Projects/lib/swig1.3/python/python.swg:19)
...
 . top . include (example.i:6)
 . top . include . module (example.i:2)
 . top . include . insert (example.i:6)
 . top . include . include (example.i:9)
 . top . include . include . class (example.h:3)
 . top . include . include . class . access (example.h:4)
 . top . include . include . class . constructor (example.h:7)
 . top . include . include . class . destructor (example.h:10)
 . top . include . include . class . cdecl (example.h:11)
 . top . include . include . class . cdecl (example.h:11)
 . top . include . include . class . cdecl (example.h:12)
 . top . include . include . class . cdecl (example.h:13)
 . top . include . include . class . cdecl (example.h:14)
 . top . include . include . class . cdecl (example.h:15)
 . top . include . include . class (example.h:18)
 . top . include . include . class . access (example.h:19)
 . top . include . include . class . cdecl (example.h:20)
 . top . include . include . class . access (example.h:21)
 . top . include . include . class . constructor (example.h:22)
 . top . include . include . class . cdecl (example.h:23)
 . top . include . include . class . cdecl (example.h:24)
 . top . include . include . class (example.h:27)
 . top . include . include . class . access (example.h:28)
 . top . include . include . class . cdecl (example.h:29)
 . top . include . include . class . access (example.h:30)
 . top . include . include . class . constructor (example.h:31)
 . top . include . include . class . cdecl (example.h:32)
 . top . include . include . class . cdecl (example.h:33)
</pre>
</div>
<p> Even for the most simple interface, the parse tree structure is
 larger than you might expect. For example, in the above output, a
 substantial number of nodes are actually generated by the <tt>
python.swg</tt> configuration file which defines typemaps and other
 directives. The contents of the user-supplied input file don't appear
 until the end of the output.</p>
<p> The contents of each parse tree node consist of a collection of
 attribute/value pairs. Internally, the nodes are simply represented by
 hash tables. A display of the entire parse-tree structure can be
 obtained using <tt>swig -debug-top &lt;n&gt;</tt>, where <tt>n</tt> is the
 stage being processed. There are a number of other parse tree display
 options, for example, <tt>swig -debug-module &lt;n&gt;</tt> will avoid
 displaying system parse information and only display the parse tree
 pertaining to the user's module at stage <tt>n</tt> of processing.</p>
<div class="shell">
<pre>
$ swig -c++ -python -debug-module 4 example.i
      +++ include ----------------------------------------
      | name         - &quot;example.i&quot;

            +++ module ----------------------------------------
            | name         - &quot;example&quot;
            |
            +++ insert ----------------------------------------
            | code         - &quot;\n#include \&quot;example.h\&quot;\n&quot;
            |
            +++ include ----------------------------------------
            | name         - &quot;example.h&quot;

                  +++ class ----------------------------------------
                  | abstract     - &quot;1&quot;
                  | sym:name     - &quot;Shape&quot;
                  | name         - &quot;Shape&quot;
                  | kind         - &quot;class&quot;
                  | symtab       - 0x40194140
                  | sym:symtab   - 0x40191078

                        +++ access ----------------------------------------
                        | kind         - &quot;public&quot;
                        |
                        +++ constructor ----------------------------------------
                        | sym:name     - &quot;Shape&quot;
                        | name         - &quot;Shape&quot;
                        | decl         - &quot;f().&quot;
                        | code         - &quot;{\n    nshapes++;\n  }&quot;
                        | sym:symtab   - 0x40194140
                        |
                        +++ destructor ----------------------------------------
                        | sym:name     - &quot;~Shape&quot;
                        | name         - &quot;~Shape&quot;
                        | storage      - &quot;virtual&quot;
                        | code         - &quot;{\n    nshapes--;\n  }&quot;
                        | sym:symtab   - 0x40194140
                        |
                        +++ cdecl ----------------------------------------
                        | sym:name     - &quot;x&quot;
                        | name         - &quot;x&quot;
                        | decl         - &quot;&quot;
                        | type         - &quot;double&quot;
                        | sym:symtab   - 0x40194140
                        |
                        +++ cdecl ----------------------------------------
                        | sym:name     - &quot;y&quot;
                        | name         - &quot;y&quot;
                        | decl         - &quot;&quot;
                        | type         - &quot;double&quot;
                        | sym:symtab   - 0x40194140
                        |
                        +++ cdecl ----------------------------------------
                        | sym:name     - &quot;move&quot;
                        | name         - &quot;move&quot;
                        | decl         - &quot;f(double, double).&quot;
                        | parms        - double, double
                        | type         - &quot;void&quot;
                        | sym:symtab   - 0x40194140
                        |
                        +++ cdecl ----------------------------------------
                        | sym:name     - &quot;area&quot;
                        | name         - &quot;area&quot;
                        | decl         - &quot;f(void).&quot;
                        | parms        - void
                        | storage      - &quot;virtual&quot;
                        | value        - &quot;0&quot;
                        | type         - &quot;double&quot;
                        | sym:symtab   - 0x40194140
                        |
                        +++ cdecl ----------------------------------------
                        | sym:name     - &quot;perimeter&quot;
                        | name         - &quot;perimeter&quot;
                        | decl         - &quot;f(void).&quot;
                        | parms        - void
                        | storage      - &quot;virtual&quot;
                        | value        - &quot;0&quot;
                        | type         - &quot;double&quot;
                        | sym:symtab   - 0x40194140
                        |
                        +++ cdecl ----------------------------------------
                        | sym:name     - &quot;nshapes&quot;
                        | name         - &quot;nshapes&quot;
                        | decl         - &quot;&quot;
                        | storage      - &quot;static&quot;
                        | type         - &quot;int&quot;
                        | sym:symtab   - 0x40194140
                        |
                  +++ class ----------------------------------------
                  | sym:name     - &quot;Circle&quot;
                  | name         - &quot;Circle&quot;
                  | kind         - &quot;class&quot;
                  | bases        - 0x40194510
                  | symtab       - 0x40194538
                  | sym:symtab   - 0x40191078

                        +++ access ----------------------------------------
                        | kind         - &quot;private&quot;
                        |
                        +++ cdecl ----------------------------------------
                        | name         - &quot;radius&quot;
                        | decl         - &quot;&quot;
                        | type         - &quot;double&quot;
                        |
                        +++ access ----------------------------------------
                        | kind         - &quot;public&quot;
                        |
                        +++ constructor ----------------------------------------
                        | sym:name     - &quot;Circle&quot;
                        | name         - &quot;Circle&quot;
                        | parms        - double
                        | decl         - &quot;f(double).&quot;
                        | code         - &quot;{ }&quot;
                        | sym:symtab   - 0x40194538
                        |
                        +++ cdecl ----------------------------------------
                        | sym:name     - &quot;area&quot;
                        | name         - &quot;area&quot;
                        | decl         - &quot;f(void).&quot;
                        | parms        - void
                        | storage      - &quot;virtual&quot;
                        | type         - &quot;double&quot;
                        | sym:symtab   - 0x40194538
                        |
                        +++ cdecl ----------------------------------------
                        | sym:name     - &quot;perimeter&quot;
                        | name         - &quot;perimeter&quot;
                        | decl         - &quot;f(void).&quot;
                        | parms        - void
                        | storage      - &quot;virtual&quot;
                        | type         - &quot;double&quot;
                        | sym:symtab   - 0x40194538
                        |
                  +++ class ----------------------------------------
                  | sym:name     - &quot;Square&quot;
                  | name         - &quot;Square&quot;
                  | kind         - &quot;class&quot;
                  | bases        - 0x40194760
                  | symtab       - 0x40194788
                  | sym:symtab   - 0x40191078

                        +++ access ----------------------------------------
                        | kind         - &quot;private&quot;
                        |
                        +++ cdecl ----------------------------------------
                        | name         - &quot;width&quot;
                        | decl         - &quot;&quot;
                        | type         - &quot;double&quot;
                        |
                        +++ access ----------------------------------------
                        | kind         - &quot;public&quot;
                        |
                        +++ constructor ----------------------------------------
                        | sym:name     - &quot;Square&quot;
                        | name         - &quot;Square&quot;
                        | parms        - double
                        | decl         - &quot;f(double).&quot;
                        | code         - &quot;{ }&quot;
                        | sym:symtab   - 0x40194788
                        |
                        +++ cdecl ----------------------------------------
                        | sym:name     - &quot;area&quot;
                        | name         - &quot;area&quot;
                        | decl         - &quot;f(void).&quot;
                        | parms        - void
                        | storage      - &quot;virtual&quot;
                        | type         - &quot;double&quot;
                        | sym:symtab   - 0x40194788
                        |
                        +++ cdecl ----------------------------------------
                        | sym:name     - &quot;perimeter&quot;
                        | name         - &quot;perimeter&quot;
                        | decl         - &quot;f(void).&quot;
                        | parms        - void
                        | storage      - &quot;virtual&quot;
                        | type         - &quot;double&quot;
                        | sym:symtab   - 0x40194788
</pre>
</div>
<h3><a name="Extending_nn9">39.4.4 Attribute namespaces</a></h3>
<p> Attributes of parse tree nodes are often prepended with a namespace
 qualifier. For example, the attributes <tt>sym:name</tt> and <tt>
sym:symtab</tt> are attributes related to symbol table management and
 are prefixed with <tt>sym:</tt>. As a general rule, only those
 attributes which are directly related to the raw declaration appear
 without a prefix (type, name, declarator, etc.).</p>
<p> Target language modules may add additional attributes to nodes to
 assist the generation of wrapper code. The convention for doing this is
 to place these attributes in a namespace that matches the name of the
 target language. For example, <tt>python:foo</tt> or <tt>perl:foo</tt>.</p>
<h3><a name="Extending_nn10">39.4.5 Symbol Tables</a></h3>
<p> During parsing, all symbols are managed in the space of the target
 language. The <tt>sym:name</tt> attribute of each node contains the
 symbol name selected by the parser. Normally, <tt>sym:name</tt> and <tt>
name</tt> are the same. However, the <tt>%rename</tt> directive can be
 used to change the value of <tt>sym:name</tt>. You can see the effect
 of <tt>%rename</tt> by trying it on a simple interface and dumping the
 parse tree. For example:</p>
<div class="code">
<pre>
%rename(foo_i) foo(int);
%rename(foo_d) foo(double);

void foo(int);
void foo(double);
void foo(Bar *b);
</pre>
</div>
<p> There are various <tt>debug-</tt> options that can be useful for
 debugging and analysing the parse tree. For example, the <tt>debug-top
 &lt;n&gt;</tt> or <tt>debug-module &lt;n&gt;</tt> options will dump the entire/top
 of the parse tree or the module subtree at one of the four <tt>n</tt>
 stages of processing. The parse tree can be viewed after the final
 stage of processing by running SWIG:</p>
<div class="shell">
<pre>
$ swig -debug-top 4 example.i
...
            +++ cdecl ----------------------------------------
            | sym:name     - &quot;foo_i&quot;
            | name         - &quot;foo&quot;
            | decl         - &quot;f(int).&quot;
            | parms        - int
            | type         - &quot;void&quot;
            | sym:symtab   - 0x40165078
            |
            +++ cdecl ----------------------------------------
            | sym:name     - &quot;foo_d&quot;
            | name         - &quot;foo&quot;
            | decl         - &quot;f(double).&quot;
            | parms        - double
            | type         - &quot;void&quot;
            | sym:symtab   - 0x40165078
            |
            +++ cdecl ----------------------------------------
            | sym:name     - &quot;foo&quot;
            | name         - &quot;foo&quot;
            | decl         - &quot;f(p.Bar).&quot;
            | parms        - Bar *
            | type         - &quot;void&quot;
            | sym:symtab   - 0x40165078
</pre>
</div>
<p> All symbol-related conflicts and complaints about overloading are
 based on <tt>sym:name</tt> values. For instance, the following example
 uses <tt>%rename</tt> in reverse to generate a name clash.</p>
<div class="code">
<pre>
%rename(foo) foo_i(int);
%rename(foo) foo_d(double);

void foo_i(int);
void foo_d(double);
void foo(Bar *b);
</pre>
</div>
<p> When you run SWIG on this you now get:</p>
<div class="shell">
<pre>
$ ./swig example.i
example.i:6. Overloaded declaration ignored.  foo_d(double )
example.i:5. Previous declaration is foo_i(int )
example.i:7. Overloaded declaration ignored.  foo(Bar *)
example.i:5. Previous declaration is foo_i(int )
</pre>
</div>
<h3><a name="Extending_nn11">39.4.6 The %feature directive</a></h3>
<p> A number of SWIG directives such as <tt>%exception</tt> are
 implemented using the low-level <tt>%feature</tt> directive. For
 example:</p>
<div class="code">
<pre>
%feature(&quot;except&quot;) getitem(int) {
  try {
     $action
  } catch (badindex) {
     ...
  }
}

...
class Foo {
public:
  Object *getitem(int index) throws(badindex);
  ...
};
</pre>
</div>
<p> The behavior of <tt>%feature</tt> is very easy to describe--it
 simply attaches a new attribute to any parse tree node that matches the
 given prototype. When a feature is added, it shows up as an attribute
 in the <tt>feature:</tt> namespace. You can see this when running with
 the <tt>-debug-top 4</tt> option. For example:</p>
<div class="shell">
<pre>
 +++ cdecl ----------------------------------------
 | sym:name     - &quot;getitem&quot;
 | name         - &quot;getitem&quot;
 | decl         - &quot;f(int).p.&quot;
 | parms        - int
 | type         - &quot;Object&quot;
 | feature:except - &quot;{\n    try {\n       $action\n    } catc...&quot;
 | sym:symtab   - 0x40168ac8
 |
</pre>
</div>
<p> Feature names are completely arbitrary and a target language module
 can be programmed to respond to any feature name that it wants to
 recognize. The data stored in a feature attribute is usually just a raw
 unparsed string. For example, the exception code above is simply stored
 without any modifications.</p>
<h3><a name="Extending_nn12">39.4.7 Code Generation</a></h3>
<p> Language modules work by defining handler functions that know how to
 respond to different types of parse-tree nodes. These handlers simply
 look at the attributes of each node in order to produce low-level code.</p>
<p> In reality, the generation of code is somewhat more subtle than
 simply invoking handler functions. This is because parse-tree nodes
 might be transformed. For example, suppose you are wrapping a class
 like this:</p>
<div class="code">
<pre>
class Foo {
public:
  virtual int *bar(int x);
};
</pre>
</div>
<p> When the parser constructs a node for the member <tt>bar</tt>, it
 creates a raw &quot;cdecl&quot; node with the following attributes:</p>
<div class="diagram">
<pre>
nodeType    : cdecl
name        : bar
type        : int
decl        : f(int).p
parms       : int x
storage     : virtual
sym:name    : bar
</pre>
</div>
<p> To produce wrapper code, this &quot;cdecl&quot; node undergoes a number of
 transformations. First, the node is recognized as a function
 declaration. This adjusts some of the type information--specifically,
 the declarator is joined with the base datatype to produce this:</p>
<div class="diagram">
<pre>
nodeType    : cdecl
name        : bar
type        : p.int        &lt;-- Notice change in return type
decl        : f(int).p
parms       : int x
storage     : virtual
sym:name    : bar
</pre>
</div>
<p> Next, the context of the node indicates that the node is really a
 member function. This produces a transformation to a low-level accessor
 function like this:</p>
<div class="diagram">
<pre>
nodeType    : cdecl
name        : bar
type        : int.p
decl        : f(int).p
parms       : Foo *self, int x            &lt;-- Added parameter
storage     : virtual
wrap:action : result = (arg1)-&gt;bar(arg2)  &lt;-- Action code added
sym:name    : Foo_bar                     &lt;-- Symbol name changed
</pre>
</div>
<p> In this transformation, notice how an additional parameter was added
 to the parameter list and how the symbol name of the node has suddenly
 changed into an accessor using the naming scheme described in the &quot;SWIG
 Basics&quot; chapter. A small fragment of &quot;action&quot; code has also been
 generated--notice how the <tt>wrap:action</tt> attribute defines the
 access to the underlying method. The data in this transformed node is
 then used to generate a wrapper.</p>
<p> Language modules work by registering handler functions for dealing
 with various types of nodes at different stages of transformation. This
 is done by inheriting from a special <tt>Language</tt> class and
 defining a collection of virtual methods. For example, the Python
 module defines a class as follows:</p>
<div class="code">
<pre>
class PYTHON : public Language {
protected:
public :
  virtual void main(int, char *argv[]);
  virtual int  top(Node *);
  virtual int  functionWrapper(Node *);
  virtual int  constantWrapper(Node *);
  virtual int  variableWrapper(Node *);
  virtual int  nativeWrapper(Node *);
  virtual int  membervariableHandler(Node *);
  virtual int  memberconstantHandler(Node *);
  virtual int  memberfunctionHandler(Node *);
  virtual int  constructorHandler(Node *);
  virtual int  destructorHandler(Node *);
  virtual int  classHandler(Node *);
  virtual int  classforwardDeclaration(Node *);
  virtual int  insertDirective(Node *);
  virtual int  importDirective(Node *);
};
</pre>
</div>
<p> The role of these functions is described shortly.</p>
<h3><a name="Extending_nn13">39.4.8 SWIG and XML</a></h3>
<p> Much of SWIG's current parser design was originally motivated by
 interest in using XML to represent SWIG parse trees. Although XML is
 not currently used in any direct manner, the parse tree structure, use
 of node tags, attributes, and attribute namespaces are all influenced
 by aspects of XML parsing. Therefore, in trying to understand SWIG's
 internal data structures, it may be useful to keep XML in the back of
 your mind as a model.</p>
<h2><a name="Extending_nn14">39.5 Primitive Data Structures</a></h2>
<p> Most of SWIG is constructed using three basic data structures:
 strings, hashes, and lists. These data structures are dynamic in same
 way as similar structures found in many scripting languages. For
 instance, you can have containers (lists and hash tables) of mixed
 types and certain operations are polymorphic.</p>
<p> This section briefly describes the basic structures so that later
 sections of this chapter make more sense.</p>
<p> When describing the low-level API, the following type name
 conventions are used:</p>
<ul>
<li><tt>String</tt>. A string object.</li>
<li><tt>Hash</tt>. A hash object.</li>
<li><tt>List</tt>. A list object.</li>
<li><tt>String_or_char</tt>. A string object or a <tt>char *</tt>.</li>
<li><tt>Object_or_char</tt>. An object or a <tt>char *</tt>.</li>
<li><tt>Object</tt>. Any object (string, hash, list, etc.)</li>
</ul>
<p> In most cases, other typenames in the source are aliases for one of
 these primitive types. Specifically:</p>
<div class="code">
<pre>
typedef String SwigType;
typedef Hash   Parm;
typedef Hash   ParmList;
typedef Hash   Node;
typedef Hash   Symtab;
typedef Hash   Typetab;
</pre>
</div>
<h3><a name="Extending_nn15">39.5.1 Strings</a></h3>
<p><b> <tt>String *NewString(const String_or_char *val)</tt></b></p>
<div class="indent"> Creates a new string with initial value <tt>val</tt>
. <tt>val</tt> may be a <tt>char *</tt> or another <tt>String</tt>
 object. If you want to create an empty string, use &quot;&quot; for val.</div>
<p><b> <tt>String *NewStringf(const char *fmt, ...)</tt></b></p>
<div class="indent"> Creates a new string whose initial value is set
 according to a C <tt>printf</tt> style format string in <tt>fmt</tt>.
 Additional arguments follow depending on <tt>fmt</tt>.</div>
<p><b> <tt>String *Copy(String *s)</tt></b></p>
<div class="indent"> Make a copy of the string <tt>s</tt>.</div>
<p><b> <tt>void Delete(String *s)</tt></b></p>
<div class="indent"> Deletes <tt>s</tt>.</div>
<p><b> <tt>int Len(const String_or_char *s)</tt></b></p>
<div class="indent"> Returns the length of the string.</div>
<p><b> <tt>char *Char(const String_or_char *s)</tt></b></p>
<div class="indent"> Returns a pointer to the first character in a
 string.</div>
<p><b> <tt>void Append(String *s, const String_or_char *t)</tt></b></p>
<div class="indent"> Appends <tt>t</tt> to the end of string <tt>s</tt>.</div>
<p><b> <tt>void Insert(String *s, int pos, const String_or_char *t)</tt></b>
</p>
<div class="indent"> Inserts <tt>t</tt> into <tt>s</tt> at position <tt>
pos</tt>. The contents of <tt>s</tt> are shifted accordingly. The
 special value <tt>DOH_END</tt> can be used for <tt>pos</tt> to indicate
 insertion at the end of the string (appending).</div>
<p><b> <tt>int Strcmp(const String_or_char *s, const String_or_char *t)</tt>
</b></p>
<div class="indent"> Compare strings <tt>s</tt> and <tt>t</tt>. Same as
 the C <tt>strcmp()</tt> function.</div>
<p><b> <tt>int Strncmp(const String_or_char *s, const String_or_char *t,
 int len)</tt></b></p>
<div class="indent"> Compare the first <tt>len</tt> characters of
 strings <tt>s</tt> and <tt>t</tt>. Same as the C <tt>strncmp()</tt>
 function.</div>
<p><b> <tt>char *Strstr(const String_or_char *s, const String_or_char
 *pat)</tt></b></p>
<div class="indent"> Returns a pointer to the first occurrence of <tt>
pat</tt> in <tt>s</tt>. Same as the C <tt>strstr()</tt> function.</div>
<p><b> <tt>char *Strchr(const String_or_char *s, char ch)</tt></b></p>
<div class="indent"> Returns a pointer to the first occurrence of
 character <tt>ch</tt> in <tt>s</tt>. Same as the C <tt>strchr()</tt>
 function.</div>
<p><b> <tt>void Chop(String *s)</tt></b></p>
<div class="indent"> Chops trailing whitespace off the end of <tt>s</tt>
.</div>
<p><b> <tt>int Replace(String *s, const String_or_char *pat, const
 String_or_char *rep, int flags)</tt></b></p>
<div class="indent">
<p> Replaces the pattern <tt>pat</tt> with <tt>rep</tt> in string <tt>s</tt>
. <tt>flags</tt> is a combination of the following flags:</p>
<div class="code">
<pre>
DOH_REPLACE_ANY       - Replace all occurrences
DOH_REPLACE_ID        - Valid C identifiers only
DOH_REPLACE_NOQUOTE   - Don't replace in quoted strings
DOH_REPLACE_FIRST     - Replace first occurrence only.
</pre>
</div>
<p> Returns the number of replacements made (if any).</p>
</div>
<h3><a name="Extending_nn16">39.5.2 Hashes</a></h3>
<p><b> <tt>Hash *NewHash()</tt></b></p>
<div class="indent"> Creates a new empty hash table.</div>
<p><b> <tt>Hash *Copy(Hash *h)</tt></b></p>
<div class="indent"> Make a shallow copy of the hash <tt>h</tt>.</div>
<p><b> <tt>void Delete(Hash *h)</tt></b></p>
<div class="indent"> Deletes <tt>h</tt>.</div>
<p><b> <tt>int Len(Hash *h)</tt></b></p>
<div class="indent"> Returns the number of items in <tt>h</tt>.</div>
<p><b> <tt>Object *Getattr(Hash *h, const String_or_char *key)</tt></b></p>
<div class="indent"> Gets an object from <tt>h</tt>. <tt>key</tt> may be
 a string or a simple <tt>char *</tt> string. Returns NULL if not found.</div>
<p><b> <tt>int Setattr(Hash *h, const String_or_char *key, const
 Object_or_char *val)</tt></b></p>
<div class="indent"> Stores <tt>val</tt> in <tt>h</tt>. <tt>key</tt> may
 be a string or a simple <tt>char *</tt>. If <tt>val</tt> is not a
 standard object (String, Hash, or List) it is assumed to be a <tt>char
 *</tt> in which case it is used to construct a <tt>String</tt> that is
 stored in the hash. If <tt>val</tt> is NULL, the object is deleted.
 Increases the reference count of <tt>val</tt>. Returns 1 if this
 operation replaced an existing hash entry, 0 otherwise.</div>
<p><b> <tt>int Delattr(Hash *h, const String_or_char *key)</tt></b></p>
<div class="indent"> Deletes the hash item referenced by <tt>key</tt>.
 Decreases the reference count on the corresponding object (if any).
 Returns 1 if an object was removed, 0 otherwise.</div>
<p><b> <tt>List *Keys(Hash *h)</tt></b></p>
<div class="indent"> Returns the list of hash table keys.</div>
<h3><a name="Extending_nn17">39.5.3 Lists</a></h3>
<p><b> <tt>List *NewList()</tt></b></p>
<div class="indent"> Creates a new empty list.</div>
<p><b> <tt>List *Copy(List *x)</tt></b></p>
<div class="indent"> Make a shallow copy of the List <tt>x</tt>.</div>
<p><b> <tt>void Delete(List *x)</tt></b></p>
<div class="indent"> Deletes <tt>x</tt>.</div>
<p><b> <tt>int Len(List *x)</tt></b></p>
<div class="indent"> Returns the number of items in <tt>x</tt>.</div>
<p><b> <tt>Object *Getitem(List *x, int n)</tt></b></p>
<div class="indent"> Returns an object from <tt>x</tt> with index <tt>n</tt>
. If <tt>n</tt> is beyond the end of the list, the last item is
 returned. If <tt>n</tt> is negative, the first item is returned.</div>
<p><b> <tt>int *Setitem(List *x, int n, const Object_or_char *val)</tt></b>
</p>
<div class="indent"> Stores <tt>val</tt> in <tt>x</tt>. If <tt>val</tt>
 is not a standard object (String, Hash, or List) it is assumed to be a <tt>
char *</tt> in which case it is used to construct a <tt>String</tt> that
 is stored in the list. <tt>n</tt> must be in range. Otherwise, an
 assertion will be raised.</div>
<p><b> <tt>int *Delitem(List *x, int n)</tt></b></p>
<div class="indent"> Deletes item <tt>n</tt> from the list, shifting
 items down if necessary. To delete the last item in the list, use the
 special value <tt>DOH_END</tt> for <tt>n</tt>.</div>
<p><b> <tt>void Append(List *x, const Object_or_char *t)</tt></b></p>
<div class="indent"> Appends <tt>t</tt> to the end of <tt>x</tt>. If <tt>
t</tt> is not a standard object, it is assumed to be a <tt>char *</tt>
 and is used to create a String object.</div>
<p><b> <tt>void Insert(String *s, int pos, const Object_or_char *t)</tt></b>
</p>
<div class="indent"> Inserts <tt>t</tt> into <tt>s</tt> at position <tt>
pos</tt>. The contents of <tt>s</tt> are shifted accordingly. The
 special value <tt>DOH_END</tt> can be used for <tt>pos</tt> to indicate
 insertion at the end of the list (appending). If <tt>t</tt> is not a
 standard object, it is assumed to be a <tt>char *</tt> and is used to
 create a String object.</div>
<h3><a name="Extending_nn18">39.5.4 Common operations</a></h3>
 The following operations are applicable to all datatypes.
<p><b> <tt>Object *Copy(Object *x)</tt></b></p>
<div class="indent"> Make a copy of the object <tt>x</tt>.</div>
<p><b> <tt>void Delete(Object *x)</tt></b></p>
<div class="indent"> Deletes <tt>x</tt>.</div>
<p><b> <tt>void Setfile(Object *x, String_or_char *f)</tt></b></p>
<div class="indent"> Sets the filename associated with <tt>x</tt>. Used
 to track objects and report errors.</div>
<p><b> <tt>String *Getfile(Object *x)</tt></b></p>
<div class="indent"> Gets the filename associated with <tt>x</tt>.</div>
<p><b> <tt>void Setline(Object *x, int n)</tt></b></p>
<div class="indent"> Sets the line number associated with <tt>x</tt>.
 Used to track objects and report errors.</div>
<p><b> <tt>int Getline(Object *x)</tt></b></p>
<div class="indent"> Gets the line number associated with <tt>x</tt>.</div>
<h3><a name="Extending_nn19">39.5.5 Iterating over Lists and Hashes</a></h3>
 To iterate over the elements of a list or a hash table, the following
 functions are used:
<p><b> <tt>Iterator First(Object *x)</tt></b></p>
<div class="indent"> Returns an iterator object that points to the first
 item in a list or hash table. The <tt>item</tt> attribute of the
 Iterator object is a pointer to the item. For hash tables, the <tt>key</tt>
 attribute of the Iterator object additionally points to the
 corresponding Hash table key. The <tt>item</tt> and <tt>key</tt>
 attributes are NULL if the object contains no items or if there are no
 more items.</div>
<p><b> <tt>Iterator Next(Iterator i)</tt></b></p>
<div class="indent">
<p>Returns an iterator that points to the next item in a list or hash
 table. Here are two examples of iteration:</p>
<div class="code">
<pre>
List *l = (some list);
Iterator i;

for (i = First(l); i.item; i = Next(i)) {
  Printf(stdout, &quot;%s\n&quot;, i.item);
}

Hash *h = (some hash);
Iterator j;

for (j = First(j); j.item; j= Next(j)) {
  Printf(stdout, &quot;%s : %s\n&quot;, j.key, j.item);
}
</pre>
</div></div>
<h3><a name="Extending_nn20">39.5.6 I/O</a></h3>
 Special I/O functions are used for all internal I/O. These operations
 work on C <tt>FILE *</tt> objects, String objects, and special <tt>File</tt>
 objects (which are merely a wrapper around <tt>FILE *</tt>).
<p><b> <tt>int Printf(String_or_FILE *f, const char *fmt, ...)</tt></b></p>
<div class="indent"> Formatted I/O. Same as the C <tt>fprintf()</tt>
 function except that output can also be directed to a string object.
 Note: the <tt>%s</tt> format specifier works with both strings and <tt>
char *</tt>. All other format operators have the same meaning.</div>
<p><b> <tt>int Printv(String_or_FILE *f, String_or_char *arg1, ...,
 NULL)</tt></b></p>
<div class="indent"> Prints a variable number of strings arguments to
 the output. The last argument to this function must be NULL. The other
 arguments can either be <tt>char *</tt> or string objects.</div>
<p><b> <tt>int Putc(int ch, String_or_FILE *f)</tt></b></p>
<div class="indent"> Same as the C <tt>fputc()</tt> function.</div>
<p><b> <tt>int Write(String_or_FILE *f, void *buf, int len)</tt></b></p>
<div class="indent"> Same as the C <tt>write()</tt> function.</div>
<p><b> <tt>int Read(String_or_FILE *f, void *buf, int maxlen)</tt></b></p>
<div class="indent"> Same as the C <tt>read()</tt> function.</div>
<p><b> <tt>int Getc(String_or_FILE *f)</tt></b></p>
<div class="indent"> Same as the C <tt>fgetc()</tt> function.</div>
<p><b> <tt>int Ungetc(int ch, String_or_FILE *f)</tt></b></p>
<div class="indent"> Same as the C <tt>ungetc()</tt> function.</div>
<p><b> <tt>int Seek(String_or_FILE *f, int offset, int whence)</tt></b></p>
<div class="indent"> Same as the C <tt>seek()</tt> function. <tt>offset</tt>
 is the number of bytes. <tt>whence</tt> is one of <tt>SEEK_SET</tt>, <tt>
SEEK_CUR</tt>, or <tt>SEEK_END</tt>..</div>
<p><b> <tt>long Tell(String_or_FILE *f)</tt></b></p>
<div class="indent"> Same as the C <tt>tell()</tt> function.</div>
<p><b> <tt>File *NewFile(const char *filename, const char *mode, List
 *newfiles)</tt></b></p>
<div class="indent"> Create a File object using the <tt>fopen()</tt>
 library call. This file differs from <tt>FILE *</tt> in that it can be
 placed in the standard SWIG containers (lists, hashes, etc.). The <tt>
filename</tt> is added to the <tt>newfiles</tt> list if <tt>newfiles</tt>
 is non-zero and the file was created successfully.</div>
<p><b> <tt>File *NewFileFromFile(FILE *f)</tt></b></p>
<div class="indent"> Create a File object wrapper around an existing <tt>
FILE *</tt> object.</div>
<p> There's no explicit function to close a file, just call <tt>
Delete(f)</tt> - this decreases the reference count, and the file will
 be closed when the reference count reaches zero.</p>
<p> The use of the above I/O functions and strings play a critical role
 in SWIG. It is common to see small code fragments of code generated
 using code like this:</p>
<div class="code">
<pre>
/* Print into a string */
String *s = NewString(&quot;&quot;);
Printf(s, &quot;Hello\n&quot;);
for (i = 0; i &lt; 10; i++) {
  Printf(s, &quot;%d\n&quot;, i);
}
...
/* Print string into a file */
Printf(f, &quot;%s\n&quot;, s);
</pre>
</div>
<p> Similarly, the preprocessor and parser all operate on string-files.</p>
<h2><a name="Extending_nn21">39.6 Navigating and manipulating parse
 trees</a></h2>
 Parse trees are built as collections of hash tables. Each node is a
 hash table in which arbitrary attributes can be stored. Certain
 attributes in the hash table provide links to other parse tree nodes.
 The following macros can be used to move around the parse tree.
<p><b> <tt>String *nodeType(Node *n)</tt></b></p>
<div class="indent"> Returns the node type tag as a string. The returned
 string indicates the type of parse tree node.</div>
<p><b> <tt>Node *nextSibling(Node *n)</tt></b></p>
<div class="indent"> Returns the next node in the parse tree. For
 example, the next C declaration.</div>
<p><b> <tt>Node *previousSibling(Node *n)</tt></b></p>
<div class="indent"> Returns the previous node in the parse tree. For
 example, the previous C declaration.</div>
<p><b> <tt>Node *firstChild(Node *n)</tt></b></p>
<div class="indent"> Returns the first child node. For example, if <tt>n</tt>
 was a C++ class node, this would return the node for the first class
 member.</div>
<p><b> <tt>Node *lastChild(Node *n)</tt></b></p>
<div class="indent"> Returns the last child node. You might use this if
 you wanted to append a new node to the children of a class.</div>
<p><b> <tt>Node *parentNode(Node *n)</tt></b></p>
<div class="indent"> Returns the parent of node <tt>n</tt>. Use this to
 move up the pass tree.</div>
<p> The following macros can be used to change all of the above
 attributes. Normally, these functions are only used by the parser.
 Changing them without knowing what you are doing is likely to be
 dangerous.</p>
<p><b> <tt>void set_nodeType(Node *n, const String_or_char)</tt></b></p>
<div class="indent"> Change the node type. tree node.</div>
<p><b> <tt>void set_nextSibling(Node *n, Node *s)</tt></b></p>
<div class="indent"> Set the next sibling.</div>
<p><b> <tt>void set_previousSibling(Node *n, Node *s)</tt></b></p>
<div class="indent"> Set the previous sibling.</div>
<p><b> <tt>void set_firstChild(Node *n, Node *c)</tt></b></p>
<div class="indent"> Set the first child node.</div>
<p><b> <tt>void set_lastChild(Node *n, Node *c)</tt></b></p>
<div class="indent"> Set the last child node.</div>
<p><b> <tt>void set_parentNode(Node *n, Node *p)</tt></b></p>
<div class="indent"> Set the parent node.</div>
<p> The following utility functions are used to alter the parse tree (at
 your own risk)</p>
<p><b> <tt>void appendChild(Node *parent, Node *child)</tt></b></p>
<div class="indent"> Append a child to <tt>parent</tt>. The appended
 node becomes the last child.</div>
<p><b> <tt>void deleteNode(Node *node)</tt></b></p>
<div class="indent"> Deletes a node from the parse tree. Deletion
 reconnects siblings and properly updates the parent so that sibling
 nodes are unaffected.</div>
<h2><a name="Extending_nn22">39.7 Working with attributes</a></h2>
<p> Since parse tree nodes are just hash tables, attributes are accessed
 using the <tt>Getattr()</tt>, <tt>Setattr()</tt>, and <tt>Delattr()</tt>
 operations. For example:</p>
<div class="code">
<pre>
int functionHandler(Node *n) {
  String *name    = Getattr(n, &quot;name&quot;);
  String *symname = Getattr(n, &quot;sym:name&quot;);
  SwigType *type  = Getattr(n, &quot;type&quot;);
  ...
}
</pre>
</div>
<p> New attributes can be freely attached to a node as needed. However,
 when new attributes are attached during code generation, they should be
 prepended with a namespace prefix. For example:</p>
<div class="code">
<pre>
...
Setattr(n, &quot;python:docstring&quot;, doc);     /* Store docstring */
...
</pre>
</div>
<p> A quick way to check the value of an attribute is to use the <tt>
checkAttribute()</tt> function like this:</p>
<div class="code">
<pre>
if (checkAttribute(n, &quot;storage&quot;, &quot;virtual&quot;)) {
  /* n is virtual */
  ...
}
</pre>
</div>
<p> Changing the values of existing attributes is allowed and is
 sometimes done to implement node transformations. However, if a
 function/method modifies a node, it is required to restore modified
 attributes to their original values. To simplify the task of
 saving/restoring attributes, the following functions are used:</p>
<p><b> <tt>int Swig_save(const char *ns, Node *n, const char *name1,
 const char *name2, ..., NIL)</tt></b></p>
<div class="indent"> Saves a copy of attributes <tt>name1</tt>, <tt>
name2</tt>, etc. from node <tt>n</tt>. Copies of the attributes are
 actually resaved in the node in a different namespace which is set by
 the <tt>ns</tt> argument. For example, if you call <tt>Swig_save(&quot;foo&quot;,
 n, &quot;type&quot;, NIL)</tt>, then the &quot;type&quot; attribute will be copied and
 saved as &quot;foo:type&quot;. The namespace name itself is stored in the &quot;view&quot;
 attribute of the node. If necessary, this can be examined to find out
 where previous values of attributes might have been saved.</div>
<p><b> <tt>int Swig_restore(Node *n)</tt></b></p>
<div class="indent">
<p> Restores the attributes saved by the previous call to <tt>
Swig_save()</tt>. Those attributes that were supplied to <tt>Swig_save()</tt>
 will be restored to their original values.</p>
<p> The <tt>Swig_save()</tt> and <tt>Swig_restore()</tt> functions must
 always be used as a pair. That is, every call to <tt>Swig_save()</tt>
 must have a matching call to <tt>Swig_restore()</tt>. Calls can be
 nested if necessary. Here is an example that shows how the functions
 might be used:</p>
<div class="code">
<pre>
int variableHandler(Node *n) {
  Swig_save(&quot;variableHandler&quot;, n, &quot;type&quot;, &quot;sym:name&quot;, NIL);
  String *symname = Getattr(n, &quot;sym:name&quot;);
  SwigType *type  = Getattr(n, &quot;type&quot;);
  ...
  Append(symname, &quot;_global&quot;);        // Change symbol name
  SwigType_add_pointer(type);        // Add pointer
  ...
  generate wrappers
  ...
  Swig_restore(n);                  // Restore original values
  return SWIG_OK;
}
</pre>
</div></div>
<p><b> <tt>int Swig_require(const char *ns, Node *n, const char *name1,
 const char *name2, ..., NIL)</tt></b></p>
<div class="indent"> This is an enhanced version of <tt>Swig_save()</tt>
 that adds error checking. If an attribute name is not present in <tt>n</tt>
, a failed assertion results and SWIG terminates with a fatal error.
 Optionally, if an attribute name is specified as &quot;*<em>name</em>&quot;, a
 copy of the attribute is saved as with <tt>Swig_save()</tt>. If an
 attribute is specified as &quot;?<em>name</em>&quot;, the attribute is optional. <tt>
Swig_restore()</tt> must always be called after using this function.</div>
<h2><a name="Extending_nn23">39.8 Type system</a></h2>
<p> SWIG implements the complete C++ type system including typedef,
 inheritance, pointers, references, and pointers to members. A detailed
 discussion of type theory is impossible here. However, let's cover the
 highlights.</p>
<h3><a name="Extending_nn24">39.8.1 String encoding of types</a></h3>
<p> All types in SWIG consist of a base datatype and a collection of
 type operators that are applied to the base. A base datatype is almost
 always some kind of primitive type such as <tt>int</tt> or <tt>double</tt>
. The operators consist of things like pointers, references, arrays, and
 so forth. Internally, types are represented as strings that are
 constructed in a very precise manner. Here are some examples:</p>
<div class="diagram">
<pre>
C datatype                     SWIG encoding (strings)
-----------------------------  --------------------------
int                            &quot;int&quot;
int *                          &quot;p.int&quot;
const int *                    &quot;p.q(const).int&quot;
int (*x)(int, double)          &quot;p.f(int, double).int&quot;
int [20][30]                   &quot;a(20).a(30).int&quot;
int (F::*)(int)                &quot;m(F).f(int).int&quot;
vector&lt;int&gt; *                  &quot;p.vector&lt;(int)&gt;&quot;
</pre>
</div>
<p> Reading the SWIG encoding is often easier than figuring out the C
 code---just read it from left to right. For a type of &quot;p.f(int,
 double).int&quot; is a &quot;pointer to a function(int, double) that returns
 int&quot;.</p>
<p> The following operator encodings are used in type strings:</p>
<div class="diagram">
<pre>
Operator              Meaning
-------------------   -------------------------------
p.                    Pointer to
a(n).                 Array of dimension n
r.                    C++ reference
m(class).             Member pointer to class
f(args).              Function.
q(qlist).             Qualifiers
</pre>
</div>
<p> In addition, type names may be parameterized by templates. This is
 represented by enclosing the template parameters in <tt>&lt;( ... )&gt;</tt>.
 Variable length arguments are represented by the special base type of <tt>
v(...)</tt>.</p>
<p> If you want to experiment with type encodings, the raw type strings
 can be inserted into an interface file using backticks `` wherever a
 type is expected. For instance, here is an extremely perverted example:</p>
<div class="diagram">
<pre>
`p.a(10).p.f(int, p.f(int).int)` foo(int, int (*x)(int));
</pre>
</div>
<p> This corresponds to the immediately obvious C declaration:</p>
<div class="diagram">
<pre>
(*(*foo(int, int (*)(int)))[10])(int, int (*)(int));
</pre>
</div>
<p> Aside from the potential use of this declaration on a C programming
 quiz, it motivates the use of the special SWIG encoding of types. The
 SWIG encoding is much easier to work with because types can be easily
 examined, modified, and constructed using simple string operations
 (comparison, substrings, concatenation, etc.). For example, in the
 parser, a declaration like this</p>
<div class="code">
<pre>
int *a[30];
</pre>
</div>
<p> is processed in a few pieces. In this case, you have the base type &quot;<tt>
int</tt>&quot; and the declarator of type &quot;<tt>a(30).p.</tt>&quot;. To make the
 final type, the two parts are just joined together using string
 concatenation.</p>
<h3><a name="Extending_nn25">39.8.2 Type construction</a></h3>
<p> The following functions are used to construct types. You should use
 these functions instead of trying to build the type strings yourself.</p>
<p><b> <tt>void SwigType_add_pointer(SwigType *ty)</tt></b></p>
<div class="indent"> Adds a pointer to <tt>ty</tt>.</div>
<p><b> <tt>void SwigType_del_pointer(SwigType *ty)</tt></b></p>
<div class="indent"> Removes a single pointer from <tt>ty</tt>.</div>
<p><b> <tt>void SwigType_add_reference(SwigType *ty)</tt></b></p>
<div class="indent"> Adds a reference to <tt>ty</tt>.</div>
<p><b> <tt>void SwigType_add_array(SwigType *ty, const String_or_char
 *size)</tt></b></p>
<div class="indent"> Adds an array with dimension <tt>dim</tt> to <tt>ty</tt>
.</div>
<p><b> <tt>void SwigType_del_array(SwigType *ty)</tt></b></p>
<div class="indent"> Removes a single array dimension from <tt>ty</tt>.</div>
<p><b> <tt>int SwigType_array_ndim(SwigType *ty)</tt></b></p>
<div class="indent"> Returns number of array dimensions of <tt>ty</tt>.</div>
<p><b> <tt>String* SwigType_array_getdim(SwigType *ty, int n)</tt></b></p>
<div class="indent"> Returns <tt>n</tt>th array dimension of <tt>ty</tt>
.</div>
<p><b> <tt>void SwigType_array_setdim(SwigType *ty, int n, const
 String_or_char *rep)</tt></b></p>
<div class="indent"> Sets <tt>n</tt>th array dimensions of <tt>ty</tt>
 to <tt>rep</tt>.</div>
<p><b> <tt>void SwigType_add_qualifier(SwigType *ty, const
 String_or_char *q)</tt></b></p>
<div class="indent"> Adds a type qualifier <tt>q</tt> to <tt>ty</tt>. <tt>
q</tt> is typically <tt>&quot;const&quot;</tt> or <tt>&quot;volatile&quot;</tt>.</div>
<p><b> <tt>void SwigType_add_memberpointer(SwigType *ty, const
 String_or_char *cls)</tt></b></p>
<div class="indent"> Adds a pointer to a member of class <tt>cls</tt> to
 <tt>ty</tt>.</div>
<p><b> <tt>void SwigType_add_function(SwigType *ty, ParmList *p)</tt></b>
</p>
<div class="indent"> Adds a function to <tt>ty</tt>. <tt>p</tt> is a
 linked-list of parameter nodes as generated by the parser. See the
 section on parameter lists for details about the representation.</div>
<p><b> <tt>void SwigType_add_template(SwigType *ty, ParmList *p)</tt></b>
</p>
<div class="indent"> Adds a template to <tt>ty</tt>. <tt>p</tt> is a
 linked-list of parameter nodes as generated by the parser. See the
 section on parameter lists for details about the representation.</div>
<p><b> <tt>SwigType *SwigType_pop(SwigType *ty)</tt></b></p>
<div class="indent"> Removes the last type constructor from <tt>ty</tt>
 and returns it. <tt>ty</tt> is modified.</div>
<p><b> <tt>void SwigType_push(SwigType *ty, SwigType *op)</tt></b></p>
<div class="indent"> Pushes the type operators in <tt>op</tt> onto type <tt>
ty</tt>. The opposite of <tt>SwigType_pop()</tt>.</div>
<p><b> <tt>SwigType *SwigType_pop_arrays(SwigType *ty)</tt></b></p>
<div class="indent"> Removes all leading array operators from <tt>ty</tt>
 and returns them. <tt>ty</tt> is modified. For example, if <tt>ty</tt>
 is <tt>&quot;a(20).a(10).p.int&quot;</tt>, then this function would return <tt>
&quot;a(20).a(10).&quot;</tt> and modify <tt>ty</tt> so that it has the value <tt>
&quot;p.int&quot;</tt>.</div>
<p><b> <tt>SwigType *SwigType_pop_function(SwigType *ty)</tt></b></p>
<div class="indent"> Removes a function operator from <tt>ty</tt>
 including any qualification. <tt>ty</tt> is modified. For example, if <tt>
ty</tt> is <tt>&quot;f(int).int&quot;</tt>, then this function would return <tt>
&quot;f(int).&quot;</tt> and modify <tt>ty</tt> so that it has the value <tt>&quot;int&quot;</tt>
.</div>
<p><b> <tt>SwigType *SwigType_base(SwigType *ty)</tt></b></p>
<div class="indent"> Returns the base type of a type. For example, if <tt>
ty</tt> is <tt>&quot;p.a(20).int&quot;</tt>, this function would return <tt>&quot;int&quot;</tt>
. <tt>ty</tt> is unmodified.</div>
<p><b> <tt>SwigType *SwigType_prefix(SwigType *ty)</tt></b></p>
<div class="indent"> Returns the prefix of a type. For example, if <tt>
ty</tt> is <tt>&quot;p.a(20).int&quot;</tt>, this function would return <tt>
&quot;p.a(20).&quot;</tt>. <tt>ty</tt> is unmodified.</div>
<h3><a name="Extending_nn26">39.8.3 Type tests</a></h3>
<p> The following functions can be used to test properties of a
 datatype.</p>
<p><b> <tt>int SwigType_ispointer(SwigType *ty)</tt></b></p>
<div class="indent"> Checks if <tt>ty</tt> is a standard pointer.</div>
<p><b> <tt>int SwigType_ismemberpointer(SwigType *ty)</tt></b></p>
<div class="indent"> Checks if <tt>ty</tt> is a member pointer.</div>
<p><b> <tt>int SwigType_isreference(SwigType *ty)</tt></b></p>
<div class="indent"> Checks if <tt>ty</tt> is a C++ reference.</div>
<p><b> <tt>int SwigType_isarray(SwigType *ty)</tt></b></p>
<div class="indent"> Checks if <tt>ty</tt> is an array.</div>
<p><b> <tt>int SwigType_isfunction(SwigType *ty)</tt></b></p>
<div class="indent"> Checks if <tt>ty</tt> is a function.</div>
<p><b> <tt>int SwigType_isqualifier(SwigType *ty)</tt></b></p>
<div class="indent"> Checks if <tt>ty</tt> is a qualifier.</div>
<p><b> <tt>int SwigType_issimple(SwigType *ty)</tt></b></p>
<div class="indent"> Checks if <tt>ty</tt> is a simple type. No
 operators applied.</div>
<p><b> <tt>int SwigType_isconst(SwigType *ty)</tt></b></p>
<div class="indent"> Checks if <tt>ty</tt> is a const type.</div>
<p><b> <tt>int SwigType_isvarargs(SwigType *ty)</tt></b></p>
<div class="indent"> Checks if <tt>ty</tt> is a varargs type.</div>
<p><b> <tt>int SwigType_istemplate(SwigType *ty)</tt></b></p>
<div class="indent"> Checks if <tt>ty</tt> is a templatized type.</div>
<h3><a name="Extending_nn27">39.8.4 Typedef and inheritance</a></h3>
<p> The behavior of <tt>typedef</tt> declaration is to introduce a type
 alias. For instance, <tt>typedef int Integer</tt> makes the identifier <tt>
Integer</tt> an alias for <tt>int</tt>. The treatment of typedef in SWIG
 is somewhat complicated due to the pattern matching rules that get
 applied in typemaps and the fact that SWIG prefers to generate wrapper
 code that closely matches the input to simplify debugging (a user will
 see the typedef names used in their program instead of the low-level
 primitive C datatypes).</p>
<p> To handle <tt>typedef</tt>, SWIG builds a collection of trees
 containing typedef relations. For example,</p>
<div class="code">
<pre>
typedef int Integer;
typedef Integer *IntegerPtr;
typedef int Number;
typedef int Size;
</pre>
</div>
<p> produces two trees like this:</p>
<div class="diagram">
<pre>
                 int               p.Integer
               ^  ^  ^                 ^
              /   |   \                |
             /    |    \               |
        Integer  Size   Number    IntegerPtr
</pre>
</div>
<p> To resolve a single typedef relationship, the following function is
 used:</p>
<p><b> <tt>SwigType *SwigType_typedef_resolve(SwigType *ty)</tt></b></p>
<div class="indent"> Checks if <tt>ty</tt> can be reduced to a new type
 via typedef. If so, returns the new type. If not, returns NULL.</div>
<p> Typedefs are only resolved in simple typenames that appear in a
 type. For example, the type base name and in function parameters. When
 resolving types, the process starts in the leaf nodes and moves up the
 tree towards the root. Here are a few examples that show how it works:</p>
<div class="diagram">
<pre>
Original type            After typedef_resolve()
------------------------ -----------------------
Integer                  int
a(30).Integer            int
p.IntegerPtr             p.p.Integer
p.p.Integer              p.p.int
</pre>
</div>
<p> For complicated types, the process can be quite involved. Here is
 the reduction of a function pointer:</p>
<div class="diagram">
<pre>
p.f(Integer, p.IntegerPtr, Size).Integer          : Start
p.f(Integer, p.IntegerPtr, Size).int
p.f(int, p.IntegerPtr, Size).int
p.f(int, p.p.Integer, Size).int
p.f(int, p.p.int, Size).int
p.f(int, p.p.int, int).int                        : End
</pre>
</div>
<p> Two types are equivalent if their full type reductions are the same.
 The following function will fully reduce a datatype:</p>
<p><b> <tt>SwigType *SwigType_typedef_resolve_all(SwigType *ty)</tt></b></p>
<div class="indent"> Fully reduces <tt>ty</tt> according to typedef
 rules. Resulting datatype will consist only of primitive typenames.</div>
<h3><a name="Extending_nn28">39.8.5 Lvalues</a></h3>
<p> When generating wrapper code, it is necessary to emit datatypes that
 can be used on the left-hand side of an assignment operator (an
 lvalue). However, not all C datatypes can be used in this
 way---especially arrays and const-qualified types. To generate a type
 that can be used as an lvalue, use the following function:</p>
<p><b> <tt>SwigType *SwigType_ltype(SwigType *ty)</tt></b></p>
<div class="indent"> Converts type <tt>ty</tt> to a type that can be
 used as an lvalue in assignment. The resulting type is stripped of
 qualifiers and arrays are converted to a pointers.</div>
<p> The creation of lvalues is fully aware of typedef and other aspects
 of the type system. Therefore, the creation of an lvalue may result in
 unexpected results. Here are a few examples:</p>
<div class="code">
<pre>
typedef double Matrix4[4][4];
Matrix4 x;    // type = 'Matrix4', ltype='p.a(4).double'

typedef const char * Literal;
Literal y;    // type = 'Literal', ltype='p.char'
</pre>
</div>
<h3><a name="Extending_nn29">39.8.6 Output functions</a></h3>
<p> The following functions produce strings that are suitable for
 output.</p>
<p><b> <tt>String *SwigType_str(SwigType *ty, const String_or_char *id =
 0)</tt></b></p>
<div class="indent"> Generates a C string for a datatype. <tt>id</tt> is
 an optional declarator. For example, if <tt>ty</tt> is &quot;p.f(int).int&quot;
 and <tt>id</tt> is &quot;foo&quot;, then this function produces &quot;<tt>int
 (*foo)(int)</tt>&quot;. This function is used to convert string-encoded
 types back into a form that is valid C syntax.</div>
<p><b> <tt>String *SwigType_lstr(SwigType *ty, const String_or_char *id
 = 0)</tt></b></p>
<div class="indent"> This is the same as <tt>SwigType_str()</tt> except
 that the result is generated from the type's lvalue (as generated from
 SwigType_ltype).</div>
<p><b> <tt>String *SwigType_lcaststr(SwigType *ty, const String_or_char
 *id = 0)</tt></b></p>
<div class="indent"> Generates a casting operation that converts from
 type <tt>ty</tt> to its lvalue. <tt>id</tt> is an optional name to
 include in the cast. For example, if <tt>ty</tt> is &quot;<tt>
q(const).p.char</tt>&quot; and <tt>id</tt> is &quot;<tt>foo</tt>&quot;, this function
 produces the string &quot;<tt>(char *) foo</tt>&quot;.</div>
<p><b> <tt>String *SwigType_rcaststr(SwigType *ty, const String_or_char
 *id = 0)</tt></b></p>
<div class="indent"> Generates a casting operation that converts from a
 type's lvalue to a type equivalent to <tt>ty</tt>. <tt>id</tt> is an
 optional name to include in the cast. For example, if <tt>ty</tt> is &quot;<tt>
q(const).p.char</tt>&quot; and <tt>id</tt> is &quot;<tt>foo</tt>&quot;, this function
 produces the string &quot;<tt>(const char *) foo</tt>&quot;.</div>
<p><b> <tt>String *SwigType_manglestr(SwigType *ty)</tt></b></p>
<div class="indent"> Generates a mangled string encoding of type <tt>ty</tt>
. The mangled string only contains characters that are part of a valid C
 identifier. The resulting string is used in various parts of SWIG, but
 is most commonly associated with type-descriptor objects that appear in
 wrappers (e.g., <tt>SWIGTYPE_p_double</tt>).</div>
<h2><a name="Extending_nn30">39.9 Parameters</a></h2>
<p> Several type-related functions involve parameter lists. These
 include functions and templates. Parameter list are represented as a
 list of nodes with the following attributes:</p>
<div class="diagram">
<pre>
&quot;type&quot;        -  Parameter type  (required)
&quot;name&quot;        -  Parameter name  (optional)
&quot;value&quot;       -  Initializer     (optional)
</pre>
</div>
<p> Typically parameters are denoted in the source by using a typename
 of <tt>Parm *</tt> or <tt>ParmList *</tt>. To walk a parameter list,
 simply use code like this:</p>
<div class="diagram">
<pre>
Parm *parms;
Parm *p;
for (p = parms; p; p = nextSibling(p)) {
  SwigType *type  = Getattr(p, &quot;type&quot;);
  String   *name  = Getattr(p, &quot;name&quot;);
  String   *value = Getattr(p, &quot;value&quot;);
  ...
}
</pre>
</div>
<p> Note: this code is exactly the same as what you would use to walk
 parse tree nodes.</p>
<p> An empty list of parameters is denoted by a NULL pointer.</p>
<p> Since parameter lists are fairly common, the following utility
 functions are provided to manipulate them:</p>
<p><b> <tt>Parm *CopyParm(Parm *p);</tt></b></p>
<div class="indent"> Copies a single parameter.</div>
<p><b> <tt>ParmList *CopyParmList(ParmList *p);</tt></b></p>
<div class="indent"> Copies an entire list of parameters.</div>
<p><b> <tt>int ParmList_len(ParmList *p);</tt></b></p>
<div class="indent"> Returns the number of parameters in a parameter
 list.</div>
<p><b> <tt>String *ParmList_str(ParmList *p);</tt></b></p>
<div class="indent"> Converts a parameter list into a C string. For
 example, produces a string like &quot;<tt>(int *p, int n, double x);</tt>&quot;.</div>
<p><b> <tt>String *ParmList_protostr(ParmList *p);</tt></b></p>
<div class="indent"> The same as <tt>ParmList_str()</tt> except that
 parameter names are not included. Used to emit prototypes.</div>
<p><b> <tt>int ParmList_numrequired(ParmList *p);</tt></b></p>
<div class="indent"> Returns the number of required (non-optional)
 arguments in <tt>p</tt>.</div>
<h2><a name="Extending_nn31">39.10 Writing a Language Module</a></h2>
<p> One of the easiest routes to supporting a new language module is to
 copy an already supported language module implementation and modify it.
 Be sure to choose a language that is similar in nature to the new
 language. All language modules follow a similar structure and this
 section briefly outlines the steps needed to create a bare-bones
 language module from scratch. Since the code is relatively easy to
 read, this section describes the creation of a minimal Python module.
 You should be able to extrapolate this to other languages.</p>
<h3><a name="Extending_nn32">39.10.1 Execution model</a></h3>
<p> Code generation modules are defined by inheriting from the <tt>
Language</tt> class, currently defined in the <tt>Source/Modules</tt>
 directory of SWIG. Starting from the parsing of command line options,
 all aspects of code generation are controlled by different methods of
 the <tt>Language</tt> that must be defined by your module.</p>
<h3><a name="Extending_starting_out">39.10.2 Starting out</a></h3>
<p> To define a new language module, first create a minimal
 implementation using this example as a guide:</p>
<div class="code">
<pre>
#include &quot;swigmod.h&quot;

class PYTHON : public Language {
public:

  virtual void main(int argc, char *argv[]) {
    printf(&quot;I'm the Python module.\n&quot;);
  }

  virtual int top(Node *n) {
    printf(&quot;Generating code.\n&quot;);
    return SWIG_OK;
  }

};

extern &quot;C&quot; Language *
swig_python(void) {
  return new PYTHON();
}
</pre>
</div>
<p> The &quot;swigmod.h&quot; header file contains, among other things, the
 declaration of the <tt>Language</tt> base class and so you should
 include it at the top of your language module's source file. Similarly,
 the &quot;swigconfig.h&quot; header file contains some other useful definitions
 that you may need. Note that you should<em> not</em> include any header
 files that are installed with the target language. That is to say, the
 implementation of the SWIG Python module shouldn't have any
 dependencies on the Python header files. The wrapper code generated by
 SWIG will almost always depend on some language-specific C/C++ header
 files, but SWIG itself does not.</p>
<p> Give your language class a reasonable name, usually the same as the
 target language. By convention, these class names are all uppercase
 (e.g. &quot;PYTHON&quot; for the Python language module) but this is not a
 requirement. This class will ultimately consist of a number of
 overrides of the virtual functions declared in the <tt>Language</tt>
 base class, in addition to any language-specific member functions and
 data you need. For now, just use the dummy implementations shown above.</p>
<p> The language module ends with a factory function, <tt>swig_python()</tt>
, that simply returns a new instance of the language class. As shown, it
 should be declared with the <tt>extern &quot;C&quot;</tt> storage qualifier so
 that it can be called from C code. It should also return a pointer to
 the base class (<tt>Language</tt>) so that only the interface (and not
 the implementation) of your language module is exposed to the rest of
 SWIG.</p>
<p> Save the code for your language module in a file named &quot;<tt>
python.cxx</tt>&quot; and place this file in the <tt>Source/Modules</tt>
 directory of the SWIG distribution. To ensure that your module is
 compiled into SWIG along with the other language modules, modify the
 file <tt>Source/Makefile.am</tt> to include the additional source
 files. In addition, modify the file <tt>Source/Modules/swigmain.cxx</tt>
 with an additional command line option that activates the module. Read
 the source---it's straightforward.</p>
<p> Next, at the top level of the SWIG distribution, re-run the <tt>
autogen.sh</tt> script to regenerate the various build files:</p>
<div class="shell">
<pre>
$ <b>./autogen.sh</b>
</pre>
</div>
<p> Next re-run <tt>configure</tt> to regenerate all of the Makefiles:</p>
<div class="shell">
<pre>
$ <b>./configure</b>
</pre>
</div>
<p> Finally, rebuild SWIG with your module added:</p>
<div class="shell">
<pre>
$ <b>make</b>
</pre>
</div>
<p> Once it finishes compiling, try running SWIG with the command-line
 option that activates your module. For example, <tt>swig -python foo.i</tt>
. The messages from your new module should appear.</p>
<h3><a name="Extending_nn34">39.10.3 Command line options</a></h3>
<p> When SWIG starts, the command line options are passed to your
 language module. This occurs before any other processing occurs
 (preprocessing, parsing, etc.). To capture the command line options,
 simply use code similar to this:</p>
<div class="code">
<pre>
void Language::main(int argc, char *argv[]) {
  for (int i = 1; i &lt; argc; i++) {
    if (argv[i]) {
      if (strcmp(argv[i], &quot;-interface&quot;) == 0) {
        if (argv[i+1]) {
          interface = NewString(argv[i+1]);
          Swig_mark_arg(i);
          Swig_mark_arg(i+1);
          i++;
        } else {
          Swig_arg_error();
        }
      } else if (strcmp(argv[i], &quot;-globals&quot;) == 0) {
        if (argv[i+1]) {
          global_name = NewString(argv[i+1]);
          Swig_mark_arg(i);
          Swig_mark_arg(i+1);
          i++;
        } else {
          Swig_arg_error();
        }
      } else if ((strcmp(argv[i], &quot;-proxy&quot;) == 0)) {
        proxy_flag = 1;
        Swig_mark_arg(i);
      } else if (strcmp(argv[i], &quot;-keyword&quot;) == 0) {
        use_kw = 1;
        Swig_mark_arg(i);
      } else if (strcmp(argv[i], &quot;-help&quot;) == 0) {
        fputs(usage, stderr);
      }
      ...
    }
  }
}
</pre>
</div>
<p> The exact set of options depends on what you want to do in your
 module. Generally, you would use the options to change code generation
 modes or to print diagnostic information.</p>
<p> If a module recognizes an option, it should always call <tt>
Swig_mark_arg()</tt> to mark the option as valid. If you forget to do
 this, SWIG will terminate with an unrecognized command line option
 error.</p>
<h3><a name="Extending_nn35">39.10.4 Configuration and preprocessing</a></h3>
<p> In addition to looking at command line options, the <tt>main()</tt>
 method is responsible for some initial configuration of the SWIG
 library and preprocessor. To do this, insert some code like this:</p>
<div class="code">
<pre>
void main(int argc, char *argv[]) {
  ... command line options ...

  /* Set language-specific subdirectory in SWIG library */
  SWIG_library_directory(&quot;python&quot;);

  /* Set language-specific preprocessing symbol */
  Preprocessor_define(&quot;SWIGPYTHON 1&quot;, 0);

  /* Set language-specific configuration file */
  SWIG_config_file(&quot;python.swg&quot;);

  /* Set typemap language (historical) */
  SWIG_typemap_lang(&quot;python&quot;);
}
</pre>
</div>
<p> The above code does several things--it registers the name of the
 language module with the core, it supplies some preprocessor macro
 definitions for use in input files (so that they can determine the
 target language), and it registers a start-up file. In this case, the
 file <tt>python.swg</tt> will be parsed before any part of the
 user-supplied input file.</p>
<p> Before proceeding any further, create a directory for your module in
 the SWIG library (The <tt>Lib</tt> directory). Now, create a
 configuration file in the directory. For example, <tt>python.swg</tt>.</p>
<p> Just to review, your language module should now consist of two
 files-- an implementation file <tt>python.cxx</tt> and a configuration
 file <tt>python.swg</tt>.</p>
<h3><a name="Extending_nn36">39.10.5 Entry point to code generation</a></h3>
<p> SWIG is a multi-pass compiler. Once the <tt>main()</tt> method has
 been invoked, the language module does not execute again until
 preprocessing, parsing, and a variety of semantic analysis passes have
 been performed. When the core is ready to start generating wrappers, it
 invokes the <tt>top()</tt> method of your language class. The argument
 to <tt>top</tt> is a single parse tree node that corresponds to the top
 of the entire parse tree.</p>
<p> To get the code generation process started, the <tt>top()</tt>
 procedure needs to do several things:</p>
<ul>
<li>Initialize the wrapper code output.</li>
<li>Set the module name.</li>
<li>Emit common initialization code.</li>
<li>Emit code for all of the child nodes.</li>
<li>Finalize the wrapper module and cleanup.</li>
</ul>
<p> An outline of <tt>top()</tt> might be as follows:</p>
<div class="code">
<pre>
int Python::top(Node *n) {

  /* Get the module name */
  String *module = Getattr(n, &quot;name&quot;);

  /* Get the output file name */
  String *outfile = Getattr(n, &quot;outfile&quot;);

  /* Initialize I/O (see next section) */
  ...

  /* Output module initialization code */
  ...

  /* Emit code for children */
  Language::top(n);

  ...
  /* Cleanup files */
  ...

  return SWIG_OK;
}
</pre>
</div>
<h3><a name="Extending_nn37">39.10.6 Module I/O and wrapper skeleton</a></h3>

<!-- please report bugs in this section to mgossage -->
<p> Within SWIG wrappers, there are five main sections. These are (in
 order)</p>
<ul>
<li>begin: This section is a placeholder for users to put code at the
 beginning of the C/C++ wrapper file.</li>
<li>runtime: This section has most of the common SWIG runtime code.</li>
<li>header: This section holds declarations and inclusions from the .i
 file.</li>
<li>wrapper: This section holds all the wrapper code.</li>
<li>init: This section holds the module initialisation function (the
 entry point for the interpreter).</li>
</ul>
<p> Different parts of the SWIG code will fill different sections, then
 upon completion of the wrappering all the sections will be saved to the
 wrapper file.</p>
<p> To perform this will require several additions to the code in
 various places, such as:</p>
<div class="code">
<pre>
class PYTHON : public Language {
protected:
  /* General DOH objects used for holding the strings */
  File *f_begin;
  File *f_runtime;
  File *f_header;
  File *f_wrappers;
  File *f_init;

public:
  ...

};

int Python::top(Node *n) {

  ...

  /* Initialize I/O */
  f_begin = NewFile(outfile, &quot;w&quot;, SWIG_output_files());
  if (!f_begin) {
    FileErrorDisplay(outfile);
    SWIG_exit(EXIT_FAILURE);
  }
  f_runtime = NewString(&quot;&quot;);
  f_init = NewString(&quot;&quot;);
  f_header = NewString(&quot;&quot;);
  f_wrappers = NewString(&quot;&quot;);

  /* Register file targets with the SWIG file handler */
  Swig_register_filebyname(&quot;begin&quot;, f_begin);
  Swig_register_filebyname(&quot;header&quot;, f_header);
  Swig_register_filebyname(&quot;wrapper&quot;, f_wrappers);
  Swig_register_filebyname(&quot;runtime&quot;, f_runtime);
  Swig_register_filebyname(&quot;init&quot;, f_init);

  /* Output module initialization code */
  Swig_banner(f_begin);
  ...

  /* Emit code for children */
  Language::top(n);

  ...
  /* Write all to the file */
  Dump(f_runtime, f_begin);
  Dump(f_header, f_begin);
  Dump(f_wrappers, f_begin);
  Wrapper_pretty_print(f_init, f_begin);

  /* Cleanup files */
  Delete(f_runtime);
  Delete(f_header);
  Delete(f_wrappers);
  Delete(f_init);
  Delete(f_begin);

  return SWIG_OK;
}
</pre>
</div>
<p> Using this to process a file will generate a wrapper file, however
 the wrapper will only consist of the common SWIG code as well as any
 inline code which was written in the .i file. It does not contain any
 wrappers for any of the functions or classes.</p>
<p> The code to generate the wrappers are the various member functions,
 which currently have not been touched. We will look at <tt>
functionWrapper()</tt> as this is the most commonly used function. In
 fact many of the other wrapper routines will call this to do their
 work.</p>
<p> A simple modification to write some basic details to the wrapper
 looks like this:</p>
<div class="code">
<pre>
int Python::functionWrapper(Node *n) {
  /* Get some useful attributes of this function */
  String   *name   = Getattr(n, &quot;sym:name&quot;);
  SwigType *type   = Getattr(n, &quot;type&quot;);
  ParmList *parms  = Getattr(n, &quot;parms&quot;);
  String   *parmstr= ParmList_str_defaultargs(parms); // to string
  String   *func   = SwigType_str(type, NewStringf(&quot;%s(%s)&quot;, name, parmstr));
  String   *action = Getattr(n, &quot;wrap:action&quot;);

  Printf(f_wrappers, &quot;functionWrapper   : %s\n&quot;, func);
  Printf(f_wrappers, &quot;           action : %s\n&quot;, action);
  return SWIG_OK;
}
</pre>
</div>
<p> This will now produce some useful information within your wrapper
 file.</p>
<div class="shell">
<pre>
functionWrapper   : void delete_Shape(Shape *self)
           action : delete arg1;

functionWrapper   : void Shape_x_set(Shape *self, double x)
           action : if (arg1) (arg1)-&gt;x = arg2;

functionWrapper   : double Shape_x_get(Shape *self)
           action : result = (double) ((arg1)-&gt;x);

functionWrapper   : void Shape_y_set(Shape *self, double y)
           action : if (arg1) (arg1)-&gt;y = arg2;
...
</pre>
</div>
<h3><a name="Extending_nn38">39.10.7 Low-level code generators</a></h3>

<!-- please report bugs in this section to mgossage -->
<p> As ingenious as SWIG is, and despite all its capabilities and the
 power of its parser, the Low-level code generation takes a lot of work
 to write properly. Mainly because every language insists on its own
 manner of interfacing to C/C++. To write the code generators you will
 need a good understanding of how to manually write an interface to your
 chosen language, so make sure you have your documentation handy.</p>
<p> At this point it is also probably a good idea to take a very simple
 file (just one function), and try letting SWIG generate wrappers for
 many different languages. Take a look at all of the wrappers generated,
 and decide which one looks closest to the language you are trying to
 wrap. This may help you to decide which code to look at.</p>
<p> In general most language wrappers look a little like this:</p>
<div class="code">
<pre>
/* wrapper for TYPE3 some_function(TYPE1, TYPE2); */
RETURN_TYPE _wrap_some_function(ARGS){
  TYPE1 arg1;
  TYPE2 arg2;
  TYPE3 result;

  if(ARG1 is not of TYPE1) goto fail;
  arg1=(convert ARG1);
  if(ARG2 is not of TYPE2) goto fail;
  arg2=(convert ARG2);

  result=some_function(arg1, arg2);

  convert 'result' to whatever the language wants;

  do any tidy up;

  return ALL_OK;

  fail:
  do any tidy up;
  return ERROR;
}
</pre>
</div>
<p> Yes, it is rather vague and not very clear. But each language works
 differently so this will have to do for now.</p>
<p> Tackling this problem will be done in two stages:</p>
<ul>
<li>The skeleton: the function wrapper, and call, but without the
 conversion</li>
<li>The conversion: converting the arguments to-from what the language
 wants</li>
</ul>
<p> The first step will be done in the code, the second will be done in
 typemaps.</p>
<p> Our first step will be to write the code for <tt>functionWrapper()</tt>
. What is shown below is<b> NOT</b> the solution, merely a step in the
 right direction. There are a lot of issues to address.</p>
<ul>
<li>Variable length and default parameters</li>
<li>Typechecking and number of argument checks</li>
<li>Overloaded functions</li>
<li>Inout and Output only arguments</li>
</ul>
<div class="code">
<pre>
virtual int functionWrapper(Node *n) {
  /* get useful attributes */
  String   *name   = Getattr(n, &quot;sym:name&quot;);
  SwigType *type   = Getattr(n, &quot;type&quot;);
  ParmList *parms  = Getattr(n, &quot;parms&quot;);
  ...

  /* create the wrapper object */
  Wrapper *wrapper = NewWrapper();

  /* create the functions wrappered name */
  String *wname = Swig_name_wrapper(iname);

  /* deal with overloading */
  ....

  /* write the wrapper function definition */
  Printv(wrapper-&gt;def, &quot;RETURN_TYPE &quot;, wname, &quot;(ARGS) {&quot;, NIL);

  /* if any additional local variable needed, add them now */
  ...

  /* write the list of locals/arguments required */
  emit_args(type, parms, wrapper);

  /* check arguments */
  ...

  /* write typemaps(in) */
  ....

  /* write constraints */
  ....

  /* Emit the function call */
  emit_action(n, wrapper);

  /* return value if necessary  */
  ....

  /* write typemaps(out) */
  ....

  /* add cleanup code */
  ....

  /* Close the function(ok) */
  Printv(wrapper-&gt;code, &quot;return ALL_OK;\n&quot;, NIL);

  /* add the failure cleanup code */
  ...

  /* Close the function(error) */
  Printv(wrapper-&gt;code, &quot;return ERROR;\n&quot;, &quot;}\n&quot;, NIL);

  /* final substitutions if applicable */
  ...

  /* Dump the function out */
  Wrapper_print(wrapper, f_wrappers);

  /* tidy up */
  Delete(wname);
  DelWrapper(wrapper);

  return SWIG_OK;
}
</pre>
</div>
<p> Executing this code will produce wrappers which have our basic
 skeleton but without the typemaps, there is still work to do.</p>
<h3><a name="Extending_configuration_files">39.10.8 Configuration files</a>
</h3>

<!-- please report bugs in this section to ttn -->
<p> At the time of this writing, SWIG supports nearly twenty languages,
 which means that for continued sanity in maintaining the configuration
 files, the language modules need to follow some conventions. These are
 outlined here along with the admission that, yes it is ok to violate
 these conventions in minor ways, as long as you know where to apply the
 proper kludge to keep the overall system regular and running.
 Engineering is the art of compromise, see...</p>
<p> Much of the maintenance regularity depends on choosing a suitable
 nickname for your language module (and then using it in a controlled
 way). Nicknames should be all lower case letters with an optional
 numeric suffix (no underscores, no dashes, no spaces). Some examples
 are: <tt>foo</tt>, <tt>bar</tt>, <tt>qux99</tt>.</p>
<p> The numeric suffix variant, as in the last example, is somewhat
 tricky to work with because sometimes people expect to refer to the
 language without this number but sometimes that number is extremely
 relevant (especially when it corresponds to language implementation
 versions with incompatible interfaces). New language modules that
 unavoidably require a numeric suffix in their nickname should include
 that number in all uses, or be prepared to kludge.</p>
<p> The nickname is used in four places:</p>
<table summary="nickname table">
<tr><td><b>usage</b></td><td><b>transform</b></td></tr>
<tr><td>&quot;skip&quot; tag</td><td>(none)</td></tr>
<tr><td>Examples/ subdir name</td><td>(none)</td></tr>
<tr><td>Examples/test-suite/ subdir name</td><td>(none)</td></tr>

<!-- add more uses here (remember to adjust header) -->
</table>
<p> As you can see, most usages are direct.</p>
<dl>
<dt><b> configure.ac</b></dt>
<dd> This file is processed by
<p> <a HREF="http://www.gnu.org/software/autoconf/">autoconf</a> to
 generate the <tt>configure</tt> script. This is where you need to add
 shell script fragments and autoconf macros to detect the presence of
 whatever development support your language module requires, typically
 directories where headers and libraries can be found, and/or utility
 programs useful for integrating the generated wrapper code.</p>
<p> Use the <tt>AC_ARG_WITH</tt>, <tt>AC_MSG_CHECKING</tt>, <tt>AC_SUBST</tt>
 macros and so forth (see other languages for examples). Avoid using the
 <tt>[</tt> and <tt>]</tt> character in shell script fragments. The
 variable names passed to <tt>AC_SUBST</tt> should begin with the
 nickname, entirely upcased.</p>
<p> At the end of the new section is the place to put the aforementioned
 nickname kludges (should they be needed). See Perl5 for examples of
 what to do. [If this is still unclear after you've read the code, ping
 me and I'll expand on this further. --ttn]</p>
</dd>
<dt><b> Makefile.in</b></dt>
<dd>
<p> Some of the variables AC_SUBSTituted are essential to the support of
 your language module. Fashion these into a shell script &quot;test&quot; clause
 and assign that to a skip tag using &quot;-z&quot; and &quot;-o&quot;:</p>
<div class="code"> <tt>skip-qux99 = [ -z &quot;@QUX99INCLUDE@&quot; -o -z
 &quot;@QUX99LIBS&quot; ]</tt></div>
<p> This means if those vars should ever be empty, qux99 support should
 be considered absent and so it would be a good idea to skip actions
 that might rely on it.</p>
<p> Here is where you may also define an alias (but then you'll need to
 kludge --- don't do this):</p>
<div class="code"> <tt>skip-qux = $(skip-qux99)</tt></div>
<p> Lastly, you need to modify each of <tt>check-aliveness</tt>, <tt>
check-examples</tt>, <tt>check-test-suite</tt> and <tt>lib-languages</tt>
 (var). Use the nickname for these, not the alias. Note that you can do
 this even before you have any tests or examples set up; the Makefile
 rules do some sanity checking and skip around these kinds of problems.</p>
</dd>
<dt><b> Examples/Makefile.in</b></dt>
<dd> Nothing special here; see comments at the top of this file and look
 to the existing languages for examples.</dd>
<dt><b> Examples/qux99/check.list</b></dt>
<dd> Do <tt>cp ../python/check.list .</tt> and modify to taste. One
 subdir per line.</dd>
<dt><b> Lib/qux99/extra-install.list</b></dt>
<dd> If you add your language to the top-level Makefile.in var <tt>
lib-languages</tt>, then <tt>make install</tt> will install all <tt>*.i</tt>
 and <tt>*.swg</tt> files from the language-specific subdirectory of <tt>
Lib</tt>. Use (optional) file <tt>extra-install.list</tt> in that
 directory to name additional files to install (see ruby for example).</dd>
<dt><b> Source/Modules/Makefile.am</b></dt>
<dd> Add appropriate files to this Automake file. That's it!
<p> When you have modified these files, please make sure that the new
 language module is completely ignored if it is not installed and
 detected on a box, that is, <tt>make check-examples</tt> and <tt>make
 check-test-suite</tt> politely displays the ignoring language message.</p>
</dd>
</dl>
<h3><a name="Extending_nn40">39.10.9 Runtime support</a></h3>
<p> Discuss the kinds of functions typically needed for SWIG runtime
 support (e.g. <tt>SWIG_ConvertPtr()</tt> and <tt>SWIG_NewPointerObj()</tt>
) and the names of the SWIG files that implement those functions.</p>
<h3><a name="Extending_nn41">39.10.10 Standard library files</a></h3>
<p> The standard library files that most languages supply keeps growing
 as SWIG matures. The following are the minimum that are usually
 supported:</p>
<ul>
<li> typemaps.i</li>
<li> std_string.i</li>
<li> std_vector.i</li>
<li> stl.i</li>
</ul>
<p> Please copy these and modify for any new language.</p>
<h3><a name="Extending_nn42">39.10.11 User examples</a></h3>
<p> Each of the language modules provides one or more examples. These
 examples are used to demonstrate different features of the language
 module to SWIG end-users, but you'll find that they're useful during
 development and testing of your language module as well. You can use
 examples from the existing SWIG language modules for inspiration.</p>
<p> Each example is self-contained and consists of (at least) a <tt>
Makefile</tt>, a SWIG interface file for the example module, and a
 'runme' script that demonstrates the functionality for that module. All
 of these files are stored in the same subdirectory under the <tt>
Examples/[lang]</tt> directory. There are two classic examples which
 should be the first to convert to a new language module. These are the
 &quot;simple&quot; C example and the &quot;class&quot; C++ example. These can be found, for
 example for Python, in <tt>Examples/python/simple</tt> and <tt>
Examples/python/class</tt>.</p>
<p> By default, all of the examples are built and run when the user
 types <tt>make check</tt>. To ensure that your examples are
 automatically run during this process, see the section on <a href="#Extending_configuration_files">
configuration files</a>.</p>
<h3><a name="Extending_test_suite">39.10.12 Test driven development and
 the test-suite</a></h3>
<p> A test driven development approach is central to the improvement and
 development of SWIG. Most modifications to SWIG are accompanied by
 additional regression tests and checking all tests to ensure that no
 regressions have been introduced.</p>
<p> The regression testing is carried out by the SWIG<i> test-suite</i>.
 The test-suite consists of numerous testcase interface files in the <tt>
Examples/test-suite</tt> directory as well as target language specific
 runtime tests in the <tt>Examples/test-suite/[lang]</tt> directory.
 When a testcase is run, it will execute the following steps for each
 testcase:</p>
<ol>
<li>Execute SWIG passing it the testcase interface file.</li>
<li>Compile the resulting generated C/C++ code with either the C or C++
 compiler into object files.</li>
<li>Link the object files into a dynamic library (dll/shared object).</li>
<li>Compile any generated and any runtime test target language code with
 the target language compiler, if the target language supports
 compilation. This step thus does not apply to the interpreted
 languages.</li>
<li>Execute a runtime test if one exists.</li>
</ol>
<p> For example, the<i> ret_by_value</i> testcase consists of two
 components. The first component is the <tt>
Examples/test-suite/ret_by_value.i</tt> interface file. The name of the
 SWIG module<b> must</b> always be the name of the testcase, so the <tt>
ret_by_value.i</tt> interface file thus begins with:</p>
<div class="code">
<pre>
%module ret_by_value
</pre>
</div>
<p> The testcase code will then follow the module declaration, usually
 within a <tt>%inline %{ ... %}</tt> section for the majority of the
 tests.</p>
<p> The second component is the optional runtime tests. Any runtime
 tests are named using the following convention: <tt>
[testcase]_runme.[ext]</tt>, where <tt>[testcase]</tt> is the testcase
 name and <tt>[ext]</tt> is the normal extension for the target language
 file. In this case, the Java and Python target languages implement a
 runtime test, so their files are respectively, <tt>
Examples/test-suite/java/ret_by_value_runme.java</tt> and <tt>
Examples/test-suite/python/ret_by_value_runme.py</tt>.</p>
<p> The goal of the test-suite is to test as much as possible in a<b>
 silent</b> manner. This way any SWIG or compiler errors or warnings are
 easily visible. Should there be any warnings, changes must be made to
 either fix them (preferably) or suppress them. Compilation or runtime
 errors result in a testcase failure and will be immediately visible. It
 is therefore essential that the runtime tests are written in a manner
 that displays nothing to stdout/stderr on success but error/exception
 out with an error message on stderr on failure.</p>
<h4><a name="Extending_running_test_suite">39.10.12.1 Running the
 test-suite</a></h4>
<p> In order for the test-suite to work for a particular target
 language, the language must be correctly detected and configured during
 the configure stage so that the correct Makefiles are generated. Most
 development occurs on Linux, so usually it is a matter of installing
 the development packages for the target language and simply configuring
 as outlined <a href="#Extending_starting_out">earlier</a>.</p>
<p> If when running the test-suite commands that follow, you get a
 message that the test was skipped, it indicates that the configure
 stage is missing information in order to compile and run everything for
 that language.</p>
<p> The test-suite can be run in a number of ways. The first group of
 commands are for running multiple testcases in one run and should be
 executed in the top level directory. To run the entire test-suite (can
 take a long time):</p>
<div class="shell">
<pre>
make -k check-test-suite
</pre>
</div>
<p> To run the test-suite just for target language [lang], replace
 [lang] with one of csharp, java, perl5, python, ruby, tcl etc:</p>
<div class="shell">
<pre>
make check-[lang]-test-suite
</pre>
</div>
<p> Note that if a runtime test is available, a message &quot;(with run
 test)&quot; is displayed when run. For example:</p>
<div class="shell">
<pre>
$ make check-python-test-suite
checking python test-suite
checking python testcase argcargvtest (with run test)
checking python testcase python_autodoc
checking python testcase python_append (with run test)
checking python testcase callback (with run test)
</pre>
</div>
<p> The files generated on a previous run can be deleted using the clean
 targets, either the whole test-suite or for a particular language:</p>
<div class="shell">
<pre>
make clean-test-suite
make clean-[lang]-test-suite
</pre>
</div>
<p> The test-suite can be run in a<i> partialcheck</i> mode where just
 SWIG is executed, that is, the compile, link and running of the
 testcases is not performed. Note that the partialcheck does not require
 the target language to be correctly configured and detected and unlike
 the other test-suite make targets, is never skipped. Once again, either
 all the languages can be executed or just a chosen language:</p>
<div class="shell">
<pre>
make partialcheck-test-suite
make partialcheck-[lang]-test-suite
</pre>
</div>
<p> If your computer has more than one CPU, you are strongly advised to
 use parallel make to speed up the execution speed. This can be done
 with any of the make targets that execute more than one testcase. For
 example, a dual core processor can efficiently use 2 parallel jobs:</p>
<div class="shell">
<pre>
make -j2 check-test-suite
make -j2 check-python-test-suite
make -j2 partialcheck-java-test-suite
</pre>
</div>
<p> The second group of commands are for running individual testcases
 and should be executed in the appropriate target language directory, <tt>
Examples/test-suite/[lang]</tt>. Testcases can contain either C or C++
 code and when one is written, a decision must be made as to which of
 these input languages is to be used. Replace <tt>[testcase]</tt> in the
 commands below with the name of the testcase.</p>
<p> For a C language testcase, add the testcase under the C_TEST_CASES
 list in <tt>Examples/test-suite/common.mk</tt> and execute individually
 as:</p>
<div class="shell">
<pre>
make -s [testcase].ctest
</pre>
</div>
<p> For a C++ language testcase, add the testcase under the
 CPP_TEST_CASES list in <tt>Examples/test-suite/common.mk</tt> and
 execute individually as:</p>
<div class="shell">
<pre>
make -s [testcase].cpptest
</pre>
</div>
<p> A third category of tests are C++ language testcases testing
 multiple modules (the %import directive). These require more than one
 shared library (dll/shared object) to be built and so are separated out
 from the normal C++ testcases. Add the testcase under the
 MULTI_CPP_TEST_CASES list in <tt>Examples/test-suite/common.mk</tt> and
 execute individually as:</p>
<div class="shell">
<pre>
make -s [testcase].multicpptest
</pre>
</div>
<p> To delete the generated files, execute:</p>
<div class="shell">
<pre>
make -s [testcase].clean
</pre>
</div>
<p> If you would like to see the exact commands being executed, drop the
 -s option:</p>
<div class="shell">
<pre>
make [testcase].ctest
make [testcase].cpptest
make [testcase].multicpptest
</pre>
</div>
<p> Some real examples of each:</p>
<div class="shell">
<pre>
make -s ret_by_value.clean
make -s ret_by_value.ctest
make -s bools.cpptest
make -s imports.multicpptest
</pre>
</div>
<p> Advanced usage of the test-suite facilitates running tools on some
 of the five stages. The make variables <tt>SWIGTOOL</tt> and <tt>
RUNTOOL</tt> are used to specify a tool to respectively, invoke SWIG and
 the execution of the runtime test. You are advised to view the <tt>
Examples/test-suite/common.mk</tt> file for details but for a short
 summary, the classic usage is to use <a href="http://valgrind.org/">
Valgrind</a> for memory checking. For example, checking for memory leaks
 when running the runtime test in the target language interpreter:</p>
<div class="shell">
<pre>
make ret_by_value.ctest RUNTOOL=&quot;valgrind --leak-check=full&quot;
</pre>
</div>
<p> This will probably make more sense if you look at the output of the
 above as it will show the exact commands being executed. SWIG can be
 analyzed for bad memory accesses using:</p>
<div class="shell">
<pre>
make ret_by_value.ctest SWIGTOOL=&quot;valgrind --tool=memcheck --trace-children=yes&quot;
</pre>
</div>
<p> A debugger can also be invoked easily on an individual test, for
 example gdb:</p>
<div class="shell">
<pre>
make ret_by_value.ctest RUNTOOL=&quot;gdb --args&quot;
</pre>
</div>
<p> SWIG reads the <tt>SWIG_FEATURES</tt> environment variable to obtain
 options in addition to those passed on the command line. This is
 particularly useful as the entire test-suite or a particular testcase
 can be run customized by using additional arguments, for example the -O
 optimization flag can be added in, as shown below for the bash shell:</p>
<div class="shell">
<pre>
env SWIG_FEATURES=-O make check-python-test-suite
</pre>
</div>
<p> The syntax for setting environment variables varies from one shell
 to the next, but it also works as shown in the example below, where
 some typemap debugging is added in:</p>
<div class="shell">
<pre>
make ret_by_value.ctest SWIG_FEATURES=&quot;-debug-tmsearch&quot;
</pre>
</div>
<p> There is also a special 'errors' test-suite which is a set of
 regression tests checking SWIG warning and error messages. It can be
 run in the same way as the other language test-suites, replacing [lang]
 with errors, such as <tt>make check-errors-test-suite</tt>. The test
 cases used and the way it works is described in <tt>
Examples/test-suite/errors/Makefile.in</tt>.</p>
<h3><a name="Extending_nn43">39.10.13 Documentation</a></h3>
<p> Don't forget to write end-user documentation for your language
 module. Currently, each language module has a dedicated chapter You
 shouldn't rehash things that are already covered in sufficient detail
 in the <a href="#SWIG">SWIG Basics</a> and <a href="#SWIGPlus">SWIG and
 C++</a> chapters. There is no fixed format for<em> what</em>, exactly,
 you should document about your language module, but you'll obviously
 want to cover issues that are unique to your language.</p>
<p> Some topics that you'll want to be sure to address include:</p>
<ul>
<li> Command line options unique to your language module.</li>
<li> Non-obvious mappings between C/C++ and target language concepts.
 For example, if your target language provides a single floating point
 type, it should be no big surprise to find that C/C++ <tt>float</tt>
 and <tt>double</tt> types are mapped to it. On the other hand, if your
 target language doesn't provide support for &quot;classes&quot; or something
 similar, you'd want to discuss how C++ classes are handled.</li>
<li> How to compile the SWIG-generated wrapper code into shared
 libraries that can actually be used. For some languages, there are
 well-defined procedures for doing this, but for others it's an ad hoc
 process. Provide as much detail as appropriate, and links to other
 resources if available.</li>
</ul>
<h3><a name="Extending_coding_style_guidelines">39.10.14 Coding style
 guidelines</a></h3>
<p> The coding guidelines for the C/C++ source code are pretty much K&amp;R
 C style. The style can be inferred from the existing code base and is
 largely dictated by the <tt>indent</tt> code beautifier tool set to K&amp;R
 style. The code can formatted using the make targets in the Source
 directory. Below is an example of how to format the emit.cxx file:</p>
<blockquote>
<pre>
$ cd Source
$ make beautify-file INDENTFILE=Modules/emit.cxx
</pre>
</blockquote>
<p> Of particular note is indentation is set to 2 spaces and a tab is
 used instead of 8 spaces. The generated C/C++ code should also follow
 this style as close as possible. However, tabs should be avoided as
 unlike the SWIG developers, users will never have consistent tab
 settings.</p>
<h3><a name="Extending_language_status">39.10.15 Target language status</a>
</h3>
<p> Target languages are given a status of either 'Supported' or
 'Experimental' depending on their maturity as broadly outlined in the <a
href="#Introduction_target_languages">Target language introduction</a>.
 This section provides more details on how this status is given.</p>
<h4><a name="Extending_supported_status">39.10.15.1 Supported status</a></h4>
<p> A target language is given the 'Supported' status when</p>
<ul>
<li> It is in a mature, well functioning state.</li>
<li> It has its own comprehensive chapter in the documentation. The
 level of documentation should be comprehensive and match the standard
 of the other mature modules. Python and Java are good references.</li>
<li> It passes all of the main SWIG test-suite. The main test-suite is
 defined by the tests in the C_TEST_CASES, CPP_TEST_CASES and
 MULTI_CPP_TEST_CASES lists in Examples/test-suite/common.mk. The tests
 in CPP11_TEST_CASES will also be required in the near future.</li>
<li> The test-suite must also include at least twenty wide-ranging
 runtime tests. The most mature languages have a few hundred runtime
 tests. Note that porting runtime tests from another language module is
 a quick and easy way to achieve this.</li>
<li> It supports the vast majority of SWIG features. Some more advanced
 features, such as, directors, full nested class support and target
 language namespaces (nspace) may be unimplemented. A few support
 libraries may be missing, for example, a small number of STL libraries.</li>
<li> It provides strong backwards compatibility between releases. Each
 point release must aim to be fully backwards compatible. A point
 release version is the 3rd version digit, so each of the x.y.* versions
 should be backwards compatible. Backwards compatibility breakages can
 occur in a new major or minor version if absolutely necessary and if
 documented. A major or minor version is the first or second digit in
 the three digit version.</li>
<li> Fixing unintended regressions in the Supported languages will be
 given higher priority over experimental languages by the core SWIG
 developers.</li>
<li> Examples must be available and run successfully.</li>
<li> The examples and test-suite must be fully functioning on the Travis
 Continuous Integration platform.</li>
</ul>
<h4><a name="Extending_experimental_status">39.10.15.2 Experimental
 status</a></h4>
<p> A target language is given the 'Experimental' status when</p>
<ul>
<li> It is of sub-standard quality, failing to meet the above
 'Supported' status.</li>
<li> It is somewhere between the mid to mature stage of development.</li>
<li> It is in need of help to finish development.</li>
</ul>
<p> Some minimum requirements and notes about languages with the
 'Experimental' status:</p>
<ul>
<li> Will at least implement basic functionality - support wrapping C
 functions and simple C++ classes and templates.</li>
<li> Have its own documentation chapter containing a reasonable level of
 detail. The documentation must provide enough basic functionality for a
 user to get started.</li>
<li> Have fully functional examples of basic functionality (the simple
 and class examples).</li>
<li> The test-suite must be implemented and include a few runtime tests
 for both C and C++ test cases.</li>
<li> Failing tests must be put into one of the FAILING_CPP_TESTS or
 FAILING_C_TESTS lists in the test-suite. This will ensure the
 test-suite can be superficially made to pass by ignoring failing tests.
 The number of tests in these lists should be no greater than half of
 the number of tests in the full test-suite.</li>
<li> The examples and test-suite must also be fully functioning on the
 Travis Continuous Integration platform. However, experimental languages
 will be set as 'allow_failures'. This means that pull requests and
 normal development commits will not break the entire Travis build
 should an experimental language fail.</li>
<li> Any new failed tests will be fixed on a 'best effort' basis by core
 developers with no promises made.</li>
<li> If a language module has an official maintainer, then the
 maintainer will be requested to focus on fixing test-suite regressions
 and commit to migrating the module to become a 'Supported' module.</li>
<li> If a module does not have an official maintainer, then, as
 maintenance will be on a 'best efforts' basis by the core maintainers,
 no guarantees will be provided from one release to the next and
 regressions may creep in.</li>
<li> Experimental target languages will have a (suppressible) warning
 explaining the Experimental sub-standard status and encourage users to
 help improve it.</li>
<li> No backwards compatibility is guaranteed as the module is
 effectively 'in development'. If a language module has an official
 maintainer, then a backwards compatibility guarantee may be provided at
 the maintainer's discretion and should be documented as such.</li>
</ul>
<h3><a name="Extending_prerequisites">39.10.16 Prerequisites for adding
 a new language module to the SWIG distribution</a></h3>
<p> New target language modules can be included in SWIG and
 contributions are encouraged for popular languages. In order to be
 considered for inclusion, a language must at a minimum fit the
 'Experimental' status described above.</p>
<p> Below are some practical steps that should help meet these
 requirements.</p>
<ol>
<li> The &quot;simple&quot; example needs to be working to demonstrate basic C
 code wrappers. Port the example from another language, such as from <tt>
Examples/python/simple</tt>.</li>
<li> The &quot;class&quot; example needs to be working to demonstrate basic C++
 code wrappers. Port the example from another language, such as from <tt>
Examples/python/class</tt>.</li>
<li> Modify <tt>configure.ac</tt>, <tt>Makefile.in</tt> and <tt>
Examples/Makefile.in</tt> to run these examples. Please make sure that
 if the new language is not installed properly on a box, <tt>make -k
 check</tt> should still work by skipping the tests and examples for the
 new language module.</li>
<li> Copying an existing language module and adapting the source for it
 is likely to be the most efficient approach to fully developing a new
 module as a number of corner cases are covered in the existing
 implementations. The most advanced scripting languages are Python and
 Ruby. The most advanced compiled target languages are Java and C#.</li>
<li> Get the <a href="#Extending_running_test_suite">test-suite</a>
 running for the new language (<tt>make check-[lang]-test-suite</tt>).
 While the test-suite tests many corner cases, we'd expect the majority
 of it to work without much effort once the generated code is compiling
 correctly for basic functionality as most of the corner cases are
 covered in the SWIG core. Aim to first get one C and one C++ runtime
 test running in the test-suite. Adding further runtime tests should be
 a lot easier afterwards by porting existing runtime tests from another
 language module.</li>
<li> The structure and contents of the html documentation chapter can be
 copied and adapted from one of the other language modules.</li>
<li> Source code can be formatted correctly using the info in the <a href="#Extending_coding_style_guidelines">
coding style guidelines</a> section.</li>
<li> When ready, post a patch on Github, join the swig-devel mailing
 list and email the SWIG developers with a demonstration of commitment
 to maintaining the language module, certainly in the short term and
 ideally long term.</li>
</ol>
<p> Once accepted into the official Git repository, development efforts
 should concentrate on getting the entire test-suite to work in order to
 migrate the language module to the 'Supported' status. Runtime tests
 should be added for existing testcases and new test cases can be added
 should there be an area not already covered by the existing tests.</p>
<h2><a name="Extending_debugging_options">39.11 Debugging Options</a></h2>
<p> There are various command line options which can aid debugging a
 SWIG interface as well as debugging the development of a language
 module. These are as follows:</p>
<div class="shell">
<pre>
-debug-classes    - Display information about the classes found in the interface
-debug-module &lt;n&gt; - Display module parse tree at stages 1-4, &lt;n&gt; is a csv list of stages
-debug-symtabs    - Display symbol tables information
-debug-symbols    - Display target language symbols in the symbol tables
-debug-csymbols   - Display C symbols in the symbol tables
-debug-lsymbols   - Display target language layer symbols
-debug-tags       - Display information about the tags found in the interface
-debug-template   - Display information for debugging templates
-debug-top &lt;n&gt;    - Display entire parse tree at stages 1-4, &lt;n&gt; is a csv list of stages
-debug-typedef    - Display information about the types and typedefs in the interface
-debug-typemap    - Display information for debugging typemaps
-debug-tmsearch   - Display typemap search debugging information
-debug-tmused     - Display typemaps used debugging information
</pre>
</div>
<p> The complete list of command line options for SWIG are available by
 running <tt>swig -help</tt>.</p>
<h2><a name="Extending_nn46">39.12 Guide to parse tree nodes</a></h2>
<p> This section describes the different parse tree nodes and their
 attributes.</p>
<p><b> cdecl</b></p>
<p> Describes general C declarations including variables, functions, and
 typedefs. A declaration is parsed as &quot;storage T D&quot; where storage is a
 storage class, T is a base type, and D is a declarator.</p>
<div class="diagram">
<pre>
&quot;name&quot;          - Declarator name
&quot;type&quot;          - Base type T
&quot;decl&quot;          - Declarator type (abstract)
&quot;storage&quot;       - Storage class (static, extern, typedef, etc.)
&quot;parms&quot;         - Function parameters (if a function)
&quot;code&quot;          - Function body code (if supplied)
&quot;value&quot;         - Default value (if supplied)
</pre>
</div>
<p><b> constructor</b></p>
<p> C++ constructor declaration.</p>
<div class="diagram">
<pre>
&quot;name&quot;          - Name of constructor
&quot;parms&quot;         - Parameters
&quot;decl&quot;          - Declarator (function with parameters)
&quot;code&quot;          - Function body code (if any)
&quot;feature:new&quot;   - Set to indicate return of new object.
</pre>
</div>
<p><b> destructor</b></p>
<p> C++ destructor declaration.</p>
<div class="diagram">
<pre>
&quot;name&quot;          - Name of destructor
&quot;code&quot;          - Function body code (if any)
&quot;storage&quot;       - Storage class (set if virtual)
&quot;value&quot;         - Default value (set if pure virtual).
</pre>
</div>
<p><b> access</b></p>
<p> C++ access change.</p>
<div class="diagram">
<pre>
&quot;kind&quot;          - public, protected, private
</pre>
</div>
<p><b> constant</b></p>
<p> Constant created by %constant or #define.</p>
<div class="diagram">
<pre>
&quot;name&quot;          - Name of constant.
&quot;type&quot;          - Base type.
&quot;value&quot;         - Value.
&quot;storage&quot;       - Set to %constant
&quot;feature:immutable&quot; - Set to indicate read-only
</pre>
</div>
<p><b> class</b></p>
<p> C++ class definition or C structure definition.</p>
<div class="diagram">
<pre>
&quot;name&quot;          - Name of the class.
&quot;kind&quot;          - Class kind (&quot;struct&quot;, &quot;union&quot;, &quot;class&quot;)
&quot;symtab&quot;        - Enclosing symbol table.
&quot;tdname&quot;        - Typedef name. Use for typedef struct { ... } A.
&quot;abstract&quot;      - Set if class has pure virtual methods.
&quot;baselist&quot;      - List of base class names.
&quot;storage&quot;       - Storage class (if any)
&quot;unnamed&quot;       - Set if class is unnamed.
</pre>
</div>
<p><b> enum</b></p>
<p> Enumeration.</p>
<div class="diagram">
<pre>
&quot;name&quot;          - Name of the enum (if supplied).
&quot;storage&quot;       - Storage class (if any)
&quot;tdname&quot;        - Typedef name (typedef enum { ... } name).
&quot;unnamed&quot;       - Set if enum is unnamed.
</pre>
</div>
<p><b> enumitem</b></p>
<p> Enumeration value.</p>
<div class="diagram">
<pre>
&quot;name&quot;          - Name of the enum value.
&quot;type&quot;          - Type (integer or char)
&quot;value&quot;         - Enum value (if given)
&quot;feature:immutable&quot; - Set to indicate read-only
</pre>
</div>
<p><b> namespace</b></p>
<p> C++ namespace.</p>
<div class="diagram">
<pre>
&quot;name&quot;          - Name of the namespace.
&quot;symtab&quot;        - Symbol table for enclosed scope.
&quot;unnamed&quot;       - Set if unnamed namespace
&quot;alias&quot;         - Alias name. Set for namespace A = B;
</pre>
</div>
<p><b> using</b></p>
<p> C++ using directive.</p>
<div class="diagram">
<pre>
&quot;name&quot;          - Name of the object being referred to.
&quot;uname&quot;         - Qualified name actually given to using.
&quot;node&quot;          - Node being referenced.
&quot;namespace&quot;     - Namespace name being reference (using namespace name)
</pre>
</div>
<p><b> classforward</b></p>
<p> A forward C++ class declaration.</p>
<div class="diagram">
<pre>
&quot;name&quot;          - Name of the class.
&quot;kind&quot;          - Class kind (&quot;union&quot;, &quot;struct&quot;, &quot;class&quot;)
</pre>
</div>
<p><b> insert</b></p>
<p> Code insertion directive. For example, %{ ... %} or
 %insert(section).</p>
<div class="diagram">
<pre>
&quot;code&quot;          - Inserted code
&quot;section&quot;       - Section name (&quot;header&quot;, &quot;wrapper&quot;, etc.)
</pre>
</div>
<p><b> top</b></p>
<p> Top of the parse tree.</p>
<div class="diagram">
<pre>
&quot;module&quot;        - Module name
</pre>
</div>
<p><b> extend</b></p>
<p> %extend directive.</p>
<div class="diagram">
<pre>
&quot;name&quot;          - Module name
&quot;symtab&quot;        - Symbol table of enclosed scope.
</pre>
</div>
<p><b> apply</b></p>
<p> %apply pattern { patternlist }.</p>
<div class="diagram">
<pre>
&quot;pattern&quot;       - Source pattern.
&quot;symtab&quot;        - Symbol table of enclosed scope.
</pre>
</div>
<p><b> clear</b></p>
<p> %clear patternlist;</p>
<div class="diagram">
<pre>
&quot;firstChild&quot;    - Patterns to clear
</pre>
</div>
<p><b> include</b></p>
<p> %include directive.</p>
<div class="diagram">
<pre>
&quot;name&quot;         - Filename
&quot;firstChild&quot;   - Children
</pre>
</div>
<p><b> import</b></p>
<p> %import directive.</p>
<div class="diagram">
<pre>
&quot;name&quot;         - Filename
&quot;firstChild&quot;   - Children
</pre>
</div>
<p><b> module</b></p>
<p> %module directive.</p>
<div class="diagram">
<pre>
&quot;name&quot;         - Name of the module
</pre>
</div>
<p><b> typemap</b></p>
<p> %typemap directive.</p>
<div class="diagram">
<pre>
&quot;method&quot;       - Typemap method name.
&quot;code&quot;         - Typemap code.
&quot;kwargs&quot;       - Keyword arguments (if any)
&quot;firstChild&quot;   - Typemap patterns
</pre>
</div>
<p><b> typemapcopy</b></p>
<p> %typemap directive with copy.</p>
<div class="diagram">
<pre>
&quot;method&quot;       - Typemap method name.
&quot;pattern&quot;      - Typemap source pattern.
&quot;firstChild&quot;   - Typemap patterns
</pre>
</div>
<p><b> typemapitem</b></p>
<p> %typemap pattern. Used with %apply, %clear, %typemap.</p>
<div class="diagram">
<pre>
&quot;pattern&quot;      - Typemap pattern (a parameter list)
&quot;parms&quot;        - Typemap parameters.
</pre>
</div>
<p><b> types</b></p>
<p> %types directive.</p>
<div class="diagram">
<pre>
&quot;parms&quot;        - List of parameter types.
&quot;convcode&quot;     - Code which replaces the default casting / conversion code
</pre>
</div>
<p><b> extern</b></p>
<p> extern &quot;X&quot; { ... } declaration.</p>
<div class="diagram">
<pre>
&quot;name&quot;       - Name &quot;C&quot;, &quot;Fortran&quot;, etc.
</pre>
</div>
<h2><a name="Extending_further_info">39.13 Further Development
 Information</a></h2>
<p> There is further documentation available on the internals of SWIG,
 API documentation and debugging information. This is shipped with SWIG
 in the <tt>Doc/Devel</tt> directory.</p>
</BODY>
</HTML>