summaryrefslogtreecommitdiff
path: root/swigweb/Doc1.1/HTML/Tcl.html
blob: a9c31737ae3a80affa9c8f3f349966acfc645126 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
<!-- Published by Quadralay WebWorks HTML Lite 1.5.1 -->
<!-- And munged by Dave's special Python script -->
<html>
<head>
<title>SWIG and Tcl</title>
</head>

<body bgcolor="#ffffff">
<a name="n0"></a><h1>10 SWIG and Tcl</h1><p><ul>
<li> <a href="#n1">Preliminaries</a>
<li> <a href="#n2">Building Tcl/Tk Extensions under Windows 95/NT</a>
<li> <a href="#n3">Basic Tcl Interface</a>
<li> <a href="#n4">The object oriented interface</a>
<li> <a href="#n5">About the examples</a>
<li> <a href="#n6">Binary trees in Tcl</a>
<li> <a href="#n7">Building C/C++ data structures with Tk</a>
<li> <a href="#n8">Accessing arrays</a>
<li> <a href="#n9">Building a simple OpenGL module</a>
<li> <a href="#n10">Exception handling</a>
<li> <a href="#n11">Typemaps</a>
<li> <a href="#n12">Configuration management with SWIG</a>
<li> <a href="#n13">Building new kinds of Tcl interfaces (in Tcl)</a>
<li> <a href="#n14">Extending the Tcl Netscape Plugin</a>
<li> <a href="#n15">Tcl8.0 features</a>
</ul>

This chapter discusses SWIG's support of Tcl. SWIG supports Tcl versions 7.3 and newer, including Tcl 8.0. Tk 3.6 and newer can also be used. However, for the best results you should consider using Tcl 7.5/Tk4.1 or later.<p>
<a name="n1"></a><h2> Preliminaries</h2>
You will need to install Tcl/Tk on your system if you haven't done so already. If you are using Tcl 7.5 or newer, you should also determine if your system supports dynamic loading and shared libraries. SWIG will work with or without this, but the compilation process varies.<p>
<a name="n16"></a><h3> Running SWIG</h3>
To build a Tcl module, run swig using the <tt>-tcl</tt> option as follows :<p>
<p>
<blockquote><pre>swig -tcl example.i

</pre></blockquote>
This will produce 2 files. The first file, <tt>example_wrap.c, </tt>contains all of the C code needed to build your Tcl module. The second file contains supporting documentation and may be named <tt>example_wrap.doc</tt>, <tt>example_wrap.html</tt>, <tt>example_wrap.tex</tt>, etc... To build a Tcl extension you will need to compile the <tt>example_wrap.c</tt> file and link it with the rest of your program (and possibly Tcl itself).<p>
<a name="n17"></a><h3> Additional SWIG options</h3>
The following options are also available with the Tcl module :<p>
<p>
<blockquote><pre>-tcl8         Produce Tcl8.0 native wrappers (use in place of -tcl).
-module       Set the module name.
-namespace    Use [incr Tcl] namespaces.
-prefix pkg   Set a package prefix of `pkg'. This prefix will be
              attached to each function.
-htcl tcl.h   Set name of Tcl header file.
-htk tk.h     Set name of Tk header file.
-plugin       Generate additional code for the netscape plugin.
-noobject     Omit object oriented extensions (compatibility with SWIG 1.0)
</pre></blockquote>
<p>
Many of these options will be described later.<p>
<a name="n18"></a><h3> Getting the right header files and libraries</h3>
In order to compile Tcl/Tk extensions, you will need to locate the "<tt>tcl.h</tt>" and "<tt>tk.h</tt>" header files. These are usually located in <tt>/usr/local/include</tt>. You will also need to locate the Tcl/Tk libraries <tt>libtcl.a</tt> and <tt>libtk.a</tt>. These are usually located in <tt>/usr/local/lib</tt>.<p>
When locating the right header and libraries files, double check to make sure the files are the correct version and form a matching pair. SWIG works with the following Tcl/Tk releases.<p>
<p>
<blockquote><pre>Tcl 7.3, Tk 3.6
Tcl 7.4, Tk 4.0
Tcl 7.5, Tk 4.1
Tcl 7.6, Tk 4.2
Tcl 8.0a2, Tk 8.0a2
</pre></blockquote>
<p>
Do not mix versions. Although the code might compile if you do, it will usually core dump mysteriously. By default, SWIG looks for the header files "<tt>tcl.h</tt>" and "<tt>tk.h</tt>", but your installed version of Tcl/Tk may use slightly different names such as "<tt>tcl7.5.h</tt>" and "<tt>tk4.1.h</tt>". If you need to use different header files, you can use the <tt>-htcl</tt> and <tt>-htk</tt> options as in :<p>
<p>
<blockquote><pre>swig -tcl -htcl tcl7.5.h -htk tk4.1.h example.i

</pre></blockquote>
If you are installing Tcl/Tk yourself, it is often easier to set up a symbolic links between <tt>tcl.h</tt> and the header files for the latest installed version.  You might also be able to make symbolic links to the correct files in your working directory.<p>
<a name="n19"></a><h3> Compiling a dynamic module (Unix)</h3>
To compile a dynamically loadable module, you will need to compile your SWIG extension into a shared library. This usually looks something like the following (shown for Linux).<p>
<p>
<blockquote><pre>unix &gt; swig -tcl example.i
unix &gt; gcc -fpic example_wrap.c example.c -I/usr/local/include
unix &gt; gcc -shared example.o example_wrap.o -o example.so 									# Linux

</pre></blockquote>
Unfortunately, the process of building of building shared libraries varies on every single machine. SWIG will try to guess when you run configure, but it isn't always successful. It's always a good idea to read the man pages on the compiler/linker to find out more information.<p>
<a name="n20"></a><h3> Using a dynamic module</h3>
To use a dynamic module, you will need to load it using the Tcl load command as follows :<p>
<p>
<blockquote><pre>load ./example.so example

</pre></blockquote>
The first argument is the name of the shared library while the second argument is the name of the module (the same as what you specified with the <tt>%module</tt> directive). As alternative, you can turn your module into a Tcl package.   See the section on configuration management at the end of this chapter for details.<p>
<a name="n21"></a><h3> Static linking</h3>
If your machine does not support dynamic loading or you've tried to use it without success, you can build new versions of <tt>tclsh</tt> (the Tcl shell) or <tt>wish</tt> (Tcl/Tk shell) with your extensions added. To do this, use SWIG's <tt>%include</tt> directive as follows :<p>
<p>
<blockquote><pre>%module mymodule
... declarations ...

%include tclsh.i     // Support code for rebuilding tclsh
</pre></blockquote>
<p>
To rebuild tclsh, you will need to compile as follows :<p>
<p>
<blockquote><pre>unix &gt; swig -tcl example.i
unix &gt; gcc example_wrap.c example.c -I/usr/local/include -L/usr/local/lib -ltcl -ldl \
	-lm -o my_tclsh

</pre></blockquote>
Alternatively, you can use SWIG's <tt>-l</tt> option to add the tclsh.i library file without modifying the interface file.  For example :<p>
<p>
<blockquote><pre>unix &gt; swig -tcl -ltclsh.i example.i
unix &gt; gcc example_wrap.c example.c -I/usr/local/include -L/usr/local/lib -ltcl -ldl \
	-lm -o my_tclsh

</pre></blockquote>
The <tt>-ldl</tt> option will be required if your Tcl/Tk supports dynamic loading. On some machines (most notably Solaris),it will also be necessary to add <tt>-lsocket -lnsl</tt> to the compile line. This will produce a new version of <tt>tclsh</tt> that is identical to the old one, but with your extensions added.<p>
<p>
If you are using Tk, you will want to rebuild the <tt>wish</tt> executable instead. This can be done as follows :<p>
<p>
<blockquote><pre>%module mymodule
... declarations ...

%include wish.i       // Support code for rebuilding wish

</pre></blockquote>
The compilation process is similar as before, but now looks like this :<p>
<p>
<blockquote><pre>unix &gt; swig -tcl example.i
unix &gt; gcc example_wrap.c example.c -I/usr/local/include -L/usr/local/lib -ltk -ltcl \
	-lX11 -ldl -lm -o my_wish

</pre></blockquote>
In this case you will end up with a new version of the <tt>wish</tt> executable with your extensions added. Make sure you include <tt>-ltk</tt>, <tt>-ltcl</tt>, and <tt>-lX11</tt> in the order shown.<p>
<a name="n22"></a><h3> Compilation problems</h3>
Tcl is one of the easiest languages to compile extensions for. The Tcl header files should work without problems under C and C++. Perhaps the only tricky task is that of compiling dynamically loadable modules for C++. If your C++ code has static constructors, it is unlikely to work at all. In this case, you will need to build new versions of the <tt>tclsh</tt> or <tt>wish</tt> executables instead. You may also need to link against the <tt>libgcc.a</tt>, <tt>libg++.a</tt>, and l<tt>ibstdc++.a</tt> libraries (assuming g++).<p>
<a name="n23"></a><h3> Setting a package prefix</h3>
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>
<p>
<blockquote><pre>swig -tcl -prefix Foo example.i

</pre></blockquote>
If you have a function "<tt>bar</tt>" in the SWIG file, the prefix option will append the prefix to the name when creating a command and call it "<tt>Foo_bar</tt>". <p>
<a name="n24"></a><h3> Using [incr Tcl] namespaces</h3>
Alternatively, you can have SWIG install your module into an [incr Tcl] namespace by specifying the <tt>-namespace</tt> option :<p>
<p>
<blockquote><pre>swig -tcl -namespace example.i

</pre></blockquote>
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, the resulting wrapper code can be compiled under both Tcl and [incr Tcl]. When compiling under Tcl, the namespace will turn into a package prefix such as in <tt>Foo_bar</tt>. When running under [incr Tcl], it will be something like <tt>Foo::bar.</tt><p>
<a name="n2"></a><h2> Building Tcl/Tk Extensions under Windows 95/NT</h2>
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++ 4.x although the procedure may be similar with other compilers.<p>
<a name="n25"></a><h3> Running SWIG from Developer Studio</h3>
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>
<p>
<ul>
<li>Open up a new workspace and use the AppWizard to select a DLL project.
<li>Add both the SWIG interface file (the .i file), any supporting C files, and the name of the wrapper file that will be created by SWIG (ie. <tt>example_wrap.c</tt>).   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>Select the SWIG interface file and go to the settings menu.   Under settings, select the "Custom Build" option.
<li>Enter "SWIG" in the description field.
<li>Enter "<tt>swig -tcl -o $(ProjDir)\$(InputName)_wrap.c $(InputPath)</tt>" in the "Build command(s) field"
<li>Enter "<tt>$(ProjDir)\$(InputName)_wrap.c</tt>" in the "Output files(s) field".
<li>Next, select the settings for the entire project and go to "C++:Preprocessor". Add the include directories for your Tcl installation under "Additional include directories".
<li>Finally, select the settings for the entire project and go to "Link Options".  Add the Tcl library  file to your link libraries.  For example "<tt>tcl80.lib</tt>".  Also, set the name of the output file to match the name of your Tcl module (ie. example.dll).
<li>Build your project.
</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>
<p>
<blockquote><pre>

MSDOS &gt; tclsh80
% load example.dll
% fact 4
24
%
</pre></blockquote>
<a name="n26"></a><h3> Using NMAKE</h3>
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>
<p>
<blockquote><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></blockquote>
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>
<a name="n3"></a><h2> Basic Tcl Interface</h2>
<a name="n27"></a><h3> Functions</h3>
C functions are turned into new Tcl commands with the same usage as the C function. Default/optional arguments are also allowed. An interface file like this :<p>
<p>
<blockquote><pre>%module example
int foo(int a);
double bar (double, double b = 3.0);
...

</pre></blockquote>
Will be used in Tcl like this :<p>
<p>
<blockquote><pre>set a [foo 2]
set b [bar 3.5 -1.5]
set b [bar 3.5]              # Note : default argument is used 

</pre></blockquote>
There isn't much more to say...this is pretty straightforward.<p>
<a name="n28"></a><h3> Global variables</h3>
For global variables, things are a little more complicated. For the following C datatypes, SWIG will use Tcl's variable linking mechanism to provide direct access :<p>
<p>
<blockquote><pre>int, unsigned int,
double,
char *,

</pre></blockquote>
When used in an interface file and script, it will operate as follows :<p>
<p>
<blockquote><pre>// example.i
%module example
...
double My_variable;
...

# Tcl script
puts $My_variable            # Output value of C global variable
set My_variable 5.5          # Change the value

</pre></blockquote>
For all other C datatypes, SWIG will generate a pair of set/get functions. For example :<p>
<p>
<blockquote><pre>// example.i
short My_short;
</pre></blockquote>
<p>
will be accessed in Tcl as follows :<p>
<p>
<blockquote><pre>puts [My_short_get]          # Get value of global variable
My_short_set 5.5             # Set value of global variable

</pre></blockquote>
While not the most elegant solution, this is the only solution for now. Tcl's normal variable linking mechanism operates directly on a variables and would not work correctly on datatypes other than the 3 basic datatypes supported by Tcl (<tt>int</tt>, <tt>double</tt>, and <tt>char *</tt>).<p>
<a name="n29"></a><h3> Constants</h3>
Constants are created as read-only variables. For odd datatypes (not supported by the variable linking mechanism), SWIG generates a string representation of the constant and use it instead (you shouldn't notice this however since everything is already a string in Tcl). It is never necessary to use a special "get" function with constants. Unlike Tcl variables, constants can contain pointers, structure addresses, function pointers, etc...<p>
<a name="n30"></a><h3> Pointers</h3>
Pointers to C/C++ objects are represented as character strings such as the following :<p>
<p>
<blockquote><pre>_100f8e2_Vector_p

</pre></blockquote>
A NULL pointer is represented by the string "NULL". NULL pointers can also be explicitly created as follows :<p>
<p>
<blockquote><pre>_0_Vector_p

</pre></blockquote>
In Tcl 8.0, pointers are represented using a new type of Tcl object, but the string representation is the same (and is interchangable). As a general, direct manipulation of pointer values is discouraged. <p>
<a name="n31"></a><h3> Structures </h3>
SWIG generates a basic low-level interface to C structures. For example :<p>
<p>
<blockquote><pre>struct Vector {
	double x,y,z;
};

</pre></blockquote>
gets mapped into the following collection of C functions :<p>
<p>
<blockquote><pre>double Vector_x_get(Vector *obj)
double Vector_x_set(Vector *obj, double x)
double Vector_y_get(Vector *obj)
double Vector_y_set(Vector *obj, double y)
double Vector_z_get(Vector *obj)
double Vector_z_set(Vector *obj, double z)

</pre></blockquote>
These functions are then used in the resulting Tcl interface. For example :<p>
<p>
<blockquote><pre># v is a Vector that got created somehow
% Vector_x_get $v
3.5
% Vector_x_set $v 7.8            # Change x component
</pre></blockquote>
<p>
Similar access is provided for unions and the data members of C++ classes.<p>
<a name="n32"></a><h3> C++ Classes</h3>
C++ classes are handled by building a set of low level accessor functions. Consider the following class :<p>
<p>
<blockquote><pre>
class List {
public:
  List();
  ~List();
  int  search(char *item);
  void insert(char *item);
  void remove(char *item);
  char *get(int n);
  int  length;
static void print(List *l);
};
</pre></blockquote>
<p>
When wrapped by SWIG, the following functions are created :<p>
<p>
<blockquote><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);
int      List_length_set(List *l, int n);
void     List_print(List *l);

</pre></blockquote>
Within Tcl, we can use the functions as follows :<p>
<blockquote><pre>
% set l [new_List]
% List_insert $l Ale
% List_insert $l Stout
% List_insert $l Lager
% List_print $l
Lager
Stout
Ale
% puts [List_length_get $l]
3
% puts $l
_1008560_List_p
% 

</pre></blockquote>
C++ objects are really just pointers (which are represented as strings). Member functions and data are accessed by simply passing a pointer into a collection of accessor functions that take the pointer as the first argument.<p>
<p>
While somewhat primitive, the low-level SWIG interface provides direct and flexible access to almost any C++ object. As it turns out, it is possible to do some rather amazing things with this interface as will be shown in some of the later examples. SWIG 1.1 also generates an object oriented interface that can be used in addition to the basic interface just described here.<p>
<a name="n4"></a><h2> The object oriented interface</h2>
With SWIG 1.1, a new object oriented interface to C structures and C++ classes is supported. This interface supplements the low-level SWIG interface already defined--in fact, both can be used simultaneously. To illustrate this interface, consider our previous <tt>List</tt> class :<p>
<p>
<blockquote><pre>class List {
public:
  List();
  ~List();
  int  search(char *item);
  void insert(char *item);
  void remove(char *item);
  char *get(int n);
  int  length;
static void print(List *l);
};

</pre></blockquote>
Using the object oriented interface requires no additional modifications or recompilation of the SWIG module (the functions are just used differently).<p>
<a name="n33"></a><h3> Creating new objects</h3>
The name of the class becomes a new command for creating an object. There are 5 methods for creating an object (<tt>MyObject </tt>is the name of the corresponding C++ class) <p>
<p>
<blockquote><pre>MyObject o                   # Creates a new object `o' 

MyObject o -this $objptr     # Turn a pointer to an existing C++ object into a 
                             # Tcl object `o'

MyObject -this $objptr       # Turn the pointer $objptr into a Tcl "object"

MyObject -args args          # Create a new object and pick a name for it. A handle
                             # will be returned and is the same as the pointer value.

MyObject                     # The same as MyObject -args, but for constructors that
                             # take no arguments.
</pre></blockquote>
<p>
Thus, for our List class, we can create new List objects as follows :<p>
<p>
<blockquote><pre>List l                       # Create a new list l

set listptr [new_List]       # Create a new List using low level interface
List l2 -this $listptr       # Turn it into a List object named `l2'

set l3 [List]                # Create a new list. The name of the list is in $l3

List -this $listptr          # Turn $listptr into a Tcl object of the same name
</pre></blockquote>
<p>
Now assuming you're not completely confused at this point, the best way to think of this is that there are really two different ways of representing an object.   One approach is to simply use the pointer value as the name of an object. For example :<p>
<p>
<blockquote><pre>_100e8f8_List_p

</pre></blockquote>
The second approach is to allow you to pick a name for an object such as "foo".   The different types of constructors are really just mechanism for using either approach.<p>
<a name="n34"></a><h3> Invoking member functions</h3>
Member functions are invoked using the name of the object followed by the method name and any arguments. For example :<p>
<p>
<blockquote><pre>% List l
% l insert "Bob"
% l insert "Mary"
% l search "Dave"
0
% ...

</pre></blockquote>
Or if you let SWIG generate the name of the object... (this is the pointer model)<p>
<p>
<blockquote><pre>% set l [List]
% $l insert "Bob"            # Note $l contains the name of the object
% $l insert "Mary"
% $l search "Dave"
0
%
</pre></blockquote>
<a name="n35"></a><h3> Deleting objects</h3>
Since objects are created by adding new Tcl commands, they can be deleted by simply renaming them. For example :<p>
<p>
<blockquote><pre>% rename l ""                # Destroy list object `l'

</pre></blockquote>
SWIG will automatically call the corresponding C/C++ destructor, with one caveat--SWIG will not destroy an object if you created it from an already existing pointer (if you called the constructor using the -this option). Since the pointer already existed when you created the Tcl object, Tcl doesn't own the object so it would probably be a bad idea to destroy it.<p>
<a name="n36"></a><h3> Accessing member data</h3>
Member data of an object can be accessed using the <tt>cget</tt> method. The approach is quite similar to that used in [incr Tcl] and other Tcl extensions. For example :<p>
<p>
<blockquote><pre>% l cget -length             # Get the length of the list
13

</pre></blockquote>
The <tt>cget</tt> method currently only allows retrieval of one member at a time. Extracting multiple members will require repeated calls.<p>
<p>
The member <tt>-this</tt> contains the pointer to the object that is compatible with other SWIG functions. Thus, the following call would be legal<p>
<p>
<blockquote><pre>
% List l                            # Create a new list object
% l insert Mike
% List_print [l cget -this]         # Print it out using low-level function
</pre></blockquote>
<a name="n37"></a><h3> Changing member data</h3>
To change the value of member data, the <tt>configure</tt> method can be used. For example :<p>
<p>
<blockquote><pre>% l configure -length 10     # Change length to 10 (probably not a good idea, but
                             # possible).

</pre></blockquote>
In a structure such as the following :<p>
<blockquote><pre>
struct Vector {
	double x, y, z;
};

</pre></blockquote>
you can change the value of all or some of the members as follows :<p>
<p>
<blockquote><pre>% v configure -x 3.5 -y 2 -z -1.0
</pre></blockquote>
<p>
The order of attributes does not matter.  <p>
<a name="n38"></a><h3> Relationship with pointers</h3>
The object oriented interface is mostly compatible with all of the functions that accept pointer values as arguments. Here are a couple of things to keep in mind :<p>
<p>
<ul>
<li>If you explicitly gave a name to an object, the pointer value can be retrieved using the `<tt>cget -this</tt>' method. The pointer value is what you should give to other SWIG generated functions if necessary.
<li>If you let SWIG generate the name of an object for you, then the name of the object is the same as the pointer value. This is the preferred approach.
<li>If you have a pointer value but it's not a Tcl object, you can turn it into one by calling the constructor with the `<tt>-this</tt>' option.
</ul>
<p>
Here is a script that illustrates how these things work :<p>
<p>
<blockquote><pre># Example 1 : Using a named object

List l                       # Create a new list
l insert Dave                # Call some methods
l insert Jane	
l insert Pat
List_print [l cget -this]    # Call a static method (which requires the pointer value)

# Example 2: Let SWIG pick a name

set l [List]                 # Create a new list
$l insert Dave               # Call some methods
$l insert Jane
$l insert Pat
List_print $l                # Call static method (name of object is same as pointer)

# Example 3: Already existing object
set l [new_List]             # Create a raw object using low-level interface
List_insert $l Dave          # Call some methods (using low-level functions)
List -this $l                # Turn it into a Tcl object instead
$l insert Jane
$l insert Part
List_print $l                # Call static method (uses pointer value as before).
</pre></blockquote>
<p>
<a name="n39"></a><h3> Performance concerns and disabling the object oriented interface</h3>
The object oriented interface is mainly provided for ease of programming at the expense of introducing more overhead and increased code size (C code that is). If you are concerned about these issues use the basic SWIG interface instead. It provides direct access and is much faster. As it turns out, it is possible to build an object oriented interface directly in Tcl as well--an example we'll return to a little later.<p>
<p>
To disable the object oriented interface, run SWIG with the <tt>-noobject</tt> option. This will strip out all of the extra code and produce only the low-level interface.<p>
<a name="n5"></a><h2> About the examples</h2>
The next few sections cover Tcl examples of varying complexity. These are primarily designed to illustrate how SWIG can be used to integrate C/C++ and Tcl in a variety of ways. Some of the things that will be covered are :<p>
<p>
<ul>
<li>Controlling C programs with Tcl
<li>Building C data structures in Tcl.
<li>Use of C objects with Tk
<li>Wrapping a C library (OpenGL in this case)
<li>Accessing arrays and other common data structures
<li>Using Tcl to build new Tcl interfaces to C programs.
<li>Modifying SWIG's handling of datatypes.
<li>And a bunch of other cool stuff.
</ul>
<a name="n6"></a><h2> Binary trees in Tcl</h2>
In this example, we show Tcl can be used to manipulate binary trees implemented in C. This will involve accessing C data structures and functions.<p>
<a name="n40"></a><h3> C files</h3>
We will build trees using the following C header file :<p>
<p>
<blockquote><pre>/* tree.h */
typedef struct Node Node;
struct Node {
	char   *key;
	char   *value;
	Node   *left;
	Node   *right;
};

typedef struct Tree {
	Node   *head;  /*  Starting node */
	Node   *z;     /* Ending node (at leaves) */
} Tree;

extern Node *new_Node(char *key, char *value);
extern Tree *new_Tree();
</pre></blockquote>
<p>
The C functions to create new nodes and trees are as follows :<p>
<p>
<blockquote><pre>/* File : tree.c */
#include &lt;string.h&gt;
#include "tree.h"
Node *new_Node(char *key, char *value) {
	Node *n;
	n = (Node *) malloc(sizeof(Node));
	n-&gt;key = (char *) malloc(strlen(key)+1);
	n-&gt;value = (char *) malloc(strlen(value)+1);
	strcpy(n-&gt;key,key);
	strcpy(n-&gt;value,value);
	n-&gt;left = 0;
	n-&gt;right = 0;
	return n;
};
Tree *new_Tree() {
	Tree *t;
	t = (Tree *) malloc(sizeof(Tree));
	t-&gt;head = new_Node("","__head__");
	t-&gt;z = new_Node("__end__","__end__");
	t-&gt;head-&gt;right = t-&gt;z;
	t-&gt;z-&gt;left = t-&gt;z;
	t-&gt;z-&gt;right = t-&gt;z;
	return t;
}
</pre></blockquote>
<a name="n41"></a><h3> Making a quick a dirty Tcl module</h3>
To make a quick Tcl module with these functions, we can do the following :<p>
<p>
<blockquote><pre>// file : tree.i
%module tree
%{
#include "tree.h"
%}
%include tree.h       // Just grab header file since it's fairly simple

</pre></blockquote>
To build the module, run SWIG as follows and compile the resulting output :<p>
<p>
<blockquote><pre>% swig -tcl -ltclsh.i tree.i
% gcc tree.c tree_wrap.c -I/usr/local/include -L/usr/local/lib -ltcl -lm -o my_tclsh
</pre></blockquote>
<p>
We can now try out the module interactively by just running the new `<tt>my_tclsh</tt>' executable.<p>
<p>
<blockquote><pre>unix &gt; my_tclsh
% set t [new_Tree]                  # Create a new tree
_8053198_Tree_p
% set n [Tree_head_get $t]          # Get first node
_80531a8_Node_p
% puts [Node_value_get $n]          # Get its value
__head__
% Node -this $n
% $n cget -value                   # Altenative method for getting value
__head__
</pre></blockquote>
<a name="n42"></a><h3> Building a C data structure in Tcl</h3>
Given our simple Tcl interface, it is easy to write Tcl functions for building up a C binary tree. For example :<p>
<p>
<blockquote><pre># Insert an item into a tree
proc insert_tree {tree key value} {
    set tree_head [Tree_head_get $tree]
    set tree_z [Tree_z_get $tree]
    set p $tree_head
    set x [Node_right_get $tree_head]
    while {[Node_key_get $x] != "__end__"} {
        set p $x
        if {$key &lt; [Node_key_get $x]} {
		set x [Node_left_get $x]
	 } {
	       set x [Node_right_get $x]
        }
    }
    set x [new_Node $key $value]
    if {$key &lt; [Node_key_get $p]} {
        Node_left_set $p $x
    } {
        Node_right_set $p $x
    }
    Node_left_set $x $tree_z
    Node_right_set $x $tree_z
}

# Search tree and return all matches
proc search_tree {tree key} {
    set tree_head [Tree_head_get $tree]
    set tree_z [Tree_z_get $tree]
    set found {}
    set x [Node_right_get $tree_head]
    while {[Node_key_get $x] != "__end__"} {
        if {[Node_key_get $x] == $key} {
            lappend found [Node_value_get $x]
        }
        if {$key &lt; [Node_key_get $x]} {
            set x [Node_left_get $x]
        } {
            set x [Node_right_get $x]
        }
    }
    return $found
}

</pre></blockquote>
While written in Tcl, these functions are building up a real C binary tree data structure that could be passed into other C function.  For example, we could write a function that globs an entire directory and builds a tree structure as follows :<p>
<p>
<blockquote><pre># Insert all of the files in pathname into a binary tree

proc build_dir_tree {tree pathname} {
    set error [catch {set filelist [glob -nocomplain $pathname/*]}]
    if {$error == 0} {
        foreach f $filelist {
            if {[file isdirectory $f] == 1} {
                insert_tree $tree [file tail $f] $f
                if {[file type $f] != "link"} {build_dir_tree $tree $f}
            } {
                insert_tree $tree [file tail $f] $f
            }
        }
    }
}

</pre></blockquote>
We can test out our function interactively as follows :<p>
<p>
<blockquote><pre>% source tree.tcl
% set t [new_Tree]       # Create a new tree
_80533c8_Tree_p
% build_dir_tree $t /home/beazley/SWIG/SWIG1.1
% search_tree $t tcl
/home/beazley/SWIG/SWIG1.1/Examples/tcl /home/beazley/SWIG/SWIG1.1/swig_lib/tcl
%
</pre></blockquote>
<a name="n43"></a><h3> Implementing methods in C</h3>
While our Tcl methods may be fine for small problems, it may be faster to reimplement the insert and search methods in C  :<p>
<p>
<blockquote><pre>void insert_tree(Tree *t, char *key, char *value) {
	Node *p;
	Node *x;
	
	p = t-&gt;head;
	x = t-&gt;head-&gt;right;
	while (x != t-&gt;z) {
		p = x;
		if (strcmp(key,x-&gt;key) &lt; 0)
			x = x-&gt;left;
		else
			x = x-&gt;right;
	}
	x = new_Node(key,value);
	if (strcmp(key,p-&gt;key) &lt; 0) 
		p-&gt;left = x;
	else
		p-&gt;right = x;
	x-&gt;left = t-&gt;z;
	x-&gt;right = t-&gt;z;
}

</pre></blockquote>
To use this function in Tcl, simply put a declaration into the file <tt>tree.h</tt> or <tt>tree.i</tt>.<p>
<p>
When reimplemented in C, the underlying Tcl script may not notice the difference.  For example, our directory subroutine would not care if <tt>insert_tree</tt> had been written in Tcl or C.   Of course, by writing this function C, we will get significantly better performance. <p>
<a name="n44"></a><h3> Building an object oriented C interface</h3>
So far our tree example has been using the basic SWIG interface.  With a little work in the interface file, we can improve the interface a little bit.<p>
<p>
<blockquote><pre>%module tree
%{
#include "tree.h"
%}

%include tree.h
%{

  /* Function to count up Nodes */
  static  int count_nodes(Node *n, Node *end) {
    if (n == end) return 0;
    return 1+count_nodes(n-&gt;left,end)+count_nodes(n-&gt;right,end);
  }

%}

// Attach some new methods to the Tree structure

%addmethods Tree {
   void insert(char *key, char *value) {
        insert_tree(self,key,value);
   }
   char *search(char *key) {
        return search_tree(self,key);
   }
   char *findnext(char *key) {
     return find_next(self,key);
   }
   int count() {
     return count_nodes(self-&gt;head-&gt;right,self-&gt;z);
   }
   Tree();        // This is just another name for new_Tree
}

</pre></blockquote>
The <tt>%addmethods</tt> directive can be used to attach methods to existing structures and classes.  In this case, we are attaching some methods to the <tt>Tree</tt> structure.   Each of the methods are simply various C functions we have written for accessing trees.   This type of interface file comes in particularly handy when using the Tcl object oriented interface. For example, we can rewrite our directory globber as follows :<p>
<p>
<blockquote><pre>proc build_dir_tree {tree pathname} {
    set error [catch {set filelist [glob -nocomplain $pathname/*]}]
    if {$error == 0} {
        foreach f $filelist {
            if {[file isdirectory $f] == 1} {
                $tree insert [file tail $f] $f      # Note new calling method
                if {[file type $f] != "link"} {build_dir_tree $tree $f}
            } {
                $tree insert [file tail $f] $f 
            }
        }
    }
}

</pre></blockquote>
Now using it :<p>
<blockquote><pre>% source tree.tcl
% Tree t                        # Create a new Tree object
_8054610_Tree_p
% build_dir_tree t /home/beazley/SWIG/SWIG1.1
% t count
1770
% t search glaux.i
/home/beazley/SWIG/SWIG1.1/Examples/OpenGL/glaux.i
% t search typemaps
/home/beazley/SWIG/SWIG1.1/Examples/perl5/typemaps
% t findnext typemaps
/home/beazley/SWIG/SWIG1.1/Examples/python/typemaps
% t findnext typemaps
/home/beazley/SWIG/SWIG1.1/Examples/tcl/typemaps
% t findnext typemaps
None
%
</pre></blockquote>
<p>
With a little extra work, we've managed to turn an ordinary C structure into a class-like object in Tcl. <p>
<a name="n7"></a><h2> Building C/C++ data structures with Tk</h2>
Given the direct access to C/C++ objects provided by SWIG, it can be possible to use Tk to interactively build a variety of interesting data structures.    To do this, it is usually useful to maintain a mapping between canvas items and an underlying  C data structure.  This is done using associative arrays to map C pointers to canvas items and canvas items back to pointers.<p>
<p>
Suppose that we have a C program for manipulating directed graphs and that we wanted to provide a Tk interface for building graphs using a ball-and-stick model such as the following :<p>
<p><center><img src="ch10.1.png"></center><p>
<p>
<p>
The SWIG interface file for this might look something like this :<p>
<p>
<blockquote><pre>%module graph
%{
#include "graph.h"
%}

/* Get a node's number */
int      GetNum(Node *n);               /* Get a node's number         */
AdjList *GetAdj(Node *n);               /* Get a node's adjacency list */
AdjList *GetNext(AdjList *l);           /* Get next node in adj. list  */
Node    *GetNode(AdjList *l);           /* Get node from adj. list     */
Node    *new_node();                    /* Make a new node             */
void     AddLink(Node *v1, Node *v2);   /* Add an edge                 */
... etc ...

</pre></blockquote>
The interface file manipulates <tt>Node</tt> and <tt>AdjList</tt> structures.  The precise implementation of these doesn't matter here--in fact SWIG doesn't even need it.  Within a Tcl/Tk script however, we can keep track of these objects as follows :<p>
<p>
<blockquote><pre># Make a new node and put it on the canvas
proc mkNode {x y} {
    global nodeX nodeY nodeP nodeMap nodeList edgeFirst edgeSecond
    set new [.c create oval [expr $x-15] [expr $y-15] \
		 [expr $x+15] [expr $y+15] -outline black \
		 -fill white -tags node]
    set newnode [new_node]                              ;# Make a new C Node
    set nnum [GetNum $newnode]                          ;# Get our node's number
    set id [.c create text [expr $x-4] [expr $y+10] \
	     -text $nnum -anchor sw -tags nodeid]
    set nodeX($new) $x			                                  ;# Save coords of canvas item
    set nodeY($new) $y
    set nodeP($new) $newnode                            ;# Save C pointer
    set nodeMap($newnode) $new                          ;# Map pointer to Tk widget
    set edgeFirst($new) {}
    set edgeSecond($new) {}
    lappend nodeList $new                               ;# Keep a list of all C
                                                        ;# Pointers we've made
}

# Make a new edge between two nodes and put an arrow on the canvas
proc mkEdge {first second new} {
    global nodeP edgeFirst edgeSecond
    set edge [mkArrow $first $second]                   ;# Make an arrow
    lappend edgeFirst($first) $edge                     ;# Save information 
    lappend edgeSecond($second) $edge
    if {$new == 1} {
# Now add an edge within our C data structure
	AddLink $nodeP($first) $nodeP($second)           ;# Add link to C structure
    }
} 
</pre></blockquote>
<p>
In these functions, the array <tt>nodeP()</tt> allows us to associate a particular canvas item with a C object.   When manipulating the graph, this makes it easy to move from the Tcl world to C.  A second array, <tt>nodeMap()</tt> allows us to go the other way--mapping C pointers to canvas items.  A  list <tt>nodeList</tt> keeps track of all of the nodes we've created just in case we want to examine all of the nodes.  For example, suppose a C function added more edges to the graph.  To reflect the new state of the graph, we would want to add more edges to the Tk canvas.  This might be accomplished as follows :<p>
<p>
<blockquote><pre># Look at the C data structure and update the canvas
proc mkEdges {} {
    global nodeX nodeY nodeP nodeMap nodeList edgeFirst edgeSecond
    unset edgeFirst 
    unset edgeSecond 
    .c delete arc              # Edges have been tagged with arc (not shown)

    foreach node $nodeList {   ;# clear old lists
	set edgeFirst($node) {}
	set edgeSecond($node) {}
    }
    foreach node $nodeList {                    ;# Go through all of the nodes
	set v $nodeP($node)                      ;# Get the node pointer 
	set v1 [GetAdj $v]                       ;# Get its adjacency list
	while {$v1 != "NULL"} {           
	    set v2 [GetNode $v1]                 ;# Get node pointer
	    set w $nodeMap($v2)                  ;# Get canvas item
	    mkEdge $node $w 0                    ;# Make an edge between them
	    set v1 [GetNext $v1]                 ;# Get next node
	}
    }
}

</pre></blockquote>
<p>
This function merely scans through all of the nodes and walks down the adjacency list of each one.   The <tt>nodeMap()</tt> array maps C pointers onto the corresponding canvas items.  We use this to construct edges on the canvas using the <tt>mkEdge</tt> function.<p>
<a name="n8"></a><h2> Accessing arrays</h2>
In some cases, C functions may involve arrays and other objects.  In these instances, you may have to write helper functions to provide access.  For example, suppose you have a C function like this :<p>
<p>
<blockquote><pre>// Add vector a+b -&gt; c
void vector_add(double *a, double *b, double *c, int size);

</pre></blockquote>
SWIG is quite literal in its interpretation of <tt>double *</tt>--it is a pointer to a <tt>double</tt>. To provide access, a few helper functions can be written such as the following :<p>
<p>
<blockquote><pre>// SWIG helper functions for double arrays
%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;
}
%}
</pre></blockquote>
<p>
Using our C functions might work like this :<p>
<p>
<blockquote><pre># Tcl code to create some arrays and add them

set a [new_double 200]
set b [new_double 200]
set c [new_double 200]

# Fill a and b with some values
for {set i 0} {$i &lt; 200} {incr i 1} {
	set_double $a $i 0.0
	set_double $b $i $i
}

# Add them and store result in c
vector_add $a $b $c 200

</pre></blockquote>
The functions <tt>get_double</tt> and <tt>set_double</tt> can be used to access individual elements of an array.   To convert from Tcl lists to C arrays, one could write a few functions in Tcl such as the following :<p>
<p>
<blockquote><pre># Tcl Procedure to turn a list into a C array
proc Tcl2Array {l} {
	set len [llength $l]
	set a [new_double $len]
	set i 0
	foreach item $l {
		set_double $a $i $item
		incr i 1
	}
	return $a
}

# Tcl Procedure to turn a C array into a Tcl List
proc Array2Tcl {a size} {
	set l {}
	for {set i 0} {$i &lt; size} {incr i 1} {
		lappend $l [get_double $a $i]
	}
	return $l
}

</pre></blockquote>
While not optimal, one could use these to turn a Tcl list into a C representation.   The C representation could be used repeatedly in a variety of  C functions without having to repeatedly convert from strings (Of course, if the Tcl list changed one would want to update the C version).  Likewise, it is relatively simple to go back from C into Tcl.   This is not the only way to manage arrays--typemaps can be used as well.   The SWIG library file `<tt>array.i</tt>' also contains a variety of pre-written helper functions for managing different kinds of arrays.<p>
<a name="n9"></a><h2> Building a simple OpenGL module</h2>
In this example, we consider building a SWIG module out of the OpenGL graphics library.  The OpenGL library consists of several hundred functions for building complex 3D images.   By wrapping this library, we will be able to play with it interactively from a Tcl interpreter.<p>
<a name="n45"></a><h3> Required files</h3>
To build an OpenGL module, you will need to have some variant of OpenGL installed on your machine.  If unavailable, the Mesa graphics library is an OpenGL clone that runs on most machines that support X11.   We will use the "GL/gl.h", "GL/glu.h", and the GL Auxilliary libraries.<p>
<a name="n46"></a><h3> Wrapping gl.h</h3>
The first step is to build an interface from the gl.h file.  To do this, follow these steps :<p>
<p>
<ul>
<li>Copy the file <tt>gl.h</tt> to a file <tt>gl.i</tt> which will become the interface.
<li>Edit the <tt>gl.i</tt> file by taking out unneeded C preprocessor directives and any other clutter that you find.
<li>Put the following code at the beginning of the<tt> gl.i</tt> file
<blockquote><pre>
// gl.i : SWIG file for OpenGL
%module gl
%{
#include &lt;GL/gl.h&gt;
%}

... Rest of edited gl.h file here ...

</pre></blockquote>
</ul>
<p>
A critical part of this first step is making sure you have the proper set of typedefs in the <tt>gl.i</tt> file.  The first part of the file should include definitions such as the following :<p>
<blockquote><pre>
typedef unsigned int GLenum;
typedef unsigned char GLboolean;
typedef unsigned int GLbitfield;
typedef signed char GLbyte;
typedef short GLshort;
typedef int GLint;
typedef int GLsizei;
typedef unsigned char GLubyte;
typedef unsigned short GLushort;
typedef unsigned int GLuint;
typedef float GLfloat;
typedef float GLclampf;
typedef double GLdouble;
typedef double GLclampd;
typedef void GLvoid;
</pre></blockquote>
<a name="n47"></a><h3> Wrapping glu.h</h3>
Next we write a module for the glu library.   The procedure is essentially identical to <tt>gl.h</tt>--that is, we'll copy the header file and edit it slightly.    In this case, <tt>glu.h</tt> contains a few functions involving function pointers and arrays.   These may generate errors or warnings.  As a result, we can simply edit those declarations out.  Fortunately, there aren't many declarations like this.   If access is required later, the problem can often be fixed with typemaps and helper functions. The final <tt>glu.i</tt> file will look something like this :<p>
<p>
<blockquote><pre>%module glu
%{
#include &lt;GL/glu.h&gt;
%}

... rest of edited glu.h file here ...

</pre></blockquote>
Given these two files, we have a fairly complete OpenGL package. Unfortunately, we still don't have any mechanism for opening a GL window and creating images.   To to this, we can wrap the OpenGL auxilliary library which contains functions to open windows and draw various kinds of objects (while not the most powerful approach, it is the simplest to implement and works on most machines).<p>
<a name="n48"></a><h3> Wrapping the aux library</h3>
Wrapping the aux library follows exactly the same procedure as before.   You will create a file <tt>glaux.i</tt> such as the following :<p>
<p>
<blockquote><pre>// File :glaux.i
%module glaux
%{
#include "glaux.h"
%}

... Rest of edited glaux.h file ...

</pre></blockquote>
<a name="n49"></a><h3> A few helper functions</h3>
Finally, to make our library a little easier to use, we need to have a few functions to handle arrays since quite a few OpenGL calls use them as arguments.  Small 4 element arrays are particularly useful so we'll create a few helper functions in a file called <tt>help.i.</tt><p>
<p>
<blockquote><pre>// help.i : OpenGL helper functions

%inline %{
GLfloat *newfv4(GLfloat a,GLfloat b,GLfloat c,GLfloat d) {
  GLfloat *f;
  f = (GLfloat *) malloc(4*sizeof(GLfloat));
  f[0] = a; f[1] = b; f[2] = c; f[3] = d;
  return f;
}
void setfv4(GLfloat *fv, GLfloat a, GLfloat b, GLfloat c, GLfloat d) {
  fv[0] = a; fv[1] = b; fv[2] = c; fv[3] = d;
}
%}
%name(delfv4) void free(void *);
</pre></blockquote>
<a name="n50"></a><h3> An OpenGL package</h3>
Whew, we're almost done now.   The last thing to do is to package up all of our interface files into a single file called <tt>opengl.i</tt>.  <p>
<p>
<blockquote><pre>
//
// opengl.i.    SWIG Interface file for OpenGL
%module opengl

%include gl.i         // The main GL functions
%include glu.i        // The GLU library
%include glaux.i      // The aux library
%include help.i       // Our helper functions

</pre></blockquote>
To build the module, we can simply run SWIG as follows :<p>
<blockquote><pre>
unix &gt; swig -tcl opengl.i           #  Build a dynamicly loaded extension

</pre></blockquote>
or<p>
<p>
<blockquote><pre>unix &gt; swig -tcl -lwish.i opengl.i  # Build a statically linked wish executable

</pre></blockquote>
Compile the file <tt>opengl_wrap.c</tt> with your C compiler and link with Tcl, Tk, and OpenGL to create the final module.<p>
<a name="n51"></a><h3> Using the OpenGL module</h3>
The module is now used by writing a Tcl script such as the following :<p>
<p>
<blockquote><pre>load ./opengl.so
auxInitDisplayMode [expr {$AUX_SINGLE | $AUX_RGBA | $AUX_DEPTH}]
auxInitPosition 0 0 500 500
auxInitWindow "Lit-Sphere"

# set up material properties
set mat_specular [newfv4 1.0 1.0 1.0 1.0]
set mat_shininess [newfv4 50.0 0 0 0]
set light_position [newfv4 1.0 1.0 1.0 0.0]

glMaterialfv $GL_FRONT $GL_SPECULAR $mat_specular
glMaterialfv $GL_FRONT $GL_SHININESS $mat_shininess
glLightfv $GL_LIGHT0 $GL_POSITION $light_position
glEnable $GL_LIGHTING
glEnable $GL_LIGHT0
glDepthFunc $GL_LEQUAL
glEnable $GL_DEPTH_TEST

# Set up view
glClearColor 0 0 0 0
glColor3f 1.0 1.0 1.0
glMatrixMode $GL_PROJECTION
glLoadIdentity
glOrtho -1 1 -1 1 -1 1
glMatrixMode $GL_MODELVIEW
glLoadIdentity

# Draw it
glClear $GL_COLOR_BUFFER_BIT
glClear $GL_DEPTH_BUFFER_BIT
auxSolidSphere 0.5

# Clean up
delfv4 $mat_specular
delfv4 $mat_shininess
delfv4 $light_position
</pre></blockquote>
<p>
In our interpreted interface, it is possible to interactively change parameters and see the effects of various OpenGL functions.  This a great way to figure out what various functions do and to try different things without having to recompile and run after each change.<p>
<a name="n52"></a><h3> Problems with the OpenGL interface</h3>
While the OpenGL interface we have generated is fully usable, it is not without problems.<p>
<p>
<ul>
<li>OpenGL constants are installed as global variables.  As a result, it is necessary to use the global keyword when writing Tcl subroutines.  For example :
<blockquote><pre>
proc clear_screan { } {
	global GL_COLOR_BUFFER_BIT, GL_DEPTH_BUFFER_BIT
	glClear $GL_COLOR_BUFFER_BIT
	glClear $GL_DEPTH_BUFFER_BIT
}

</pre></blockquote>
<li>Arrays need to be accessed via helper functions such as our <tt>newfv4</tt>() function.   This approach certainly works and its easy enough to implement, but it may be preferable to call certain OpenGL functions with a Tcl list instead.  For example :
<blockquote><pre>
glMaterialfv $GL_FRONT $GL_SPECULAR {1.0 1.0 1.0 1.0}
</pre></blockquote>
</ul>
<p>
While these are only minor annoyances, it turns out that you can address both problems using SWIG typemaps (which are discussed shortly).<p>
<a name="n10"></a><h2> Exception handling </h2>
The <tt>%except</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 exception handling contains more details, but suppose you extended the array example into a C++ class like the following :<p>
<blockquote><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></blockquote>
<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>
<p>
<blockquote><pre>%except(tcl) {
  try {
    $function                // Gets substituted by actual function call
  }
  catch (RangeError) {
    interp-&gt;result = "Array index out-of-bounds";
    return TCL_ERROR;
  }
}

</pre></blockquote>
or in Tcl 8.0<p>
<p>
<blockquote><pre>%except(tcl8) {
  try {
    $function                // Gets substituted by actual function call
  }
  catch (RangeError) {
    Tcl_SetStringObj(tcl_result,"Array index out-of-bounds");
    return TCL_ERROR;
  }
}

</pre></blockquote>
When the C++ class throws a <tt>RangeError</tt> exception, our wrapper functions will catch it, turn it into a Tcl exception, and allow a graceful death as opposed to just having some sort of mysterious program crash.     We are not limited to C++ exception handling.   Please see the chapter on exception handling for more details on other possibilities, including a method for language-independent exception handling..<p>
<a name="n11"></a><h2> Typemaps</h2>
This section describes how SWIG's treatment of various C/C++ datatypes can be remapped using the <tt>%typemap</tt> directive.   While not required, this section assumes some familiarity with  Tcl's C API.   The reader is advised to consult  a Tcl book.  A glance at the chapter on SWIG typemaps will also be useful.  <p>
<a name="n53"></a><h3> What is a typemap?</h3>
A typemap is mechanism by which SWIG's processing of a particular C datatype can be changed.   A simple typemap might look like this :<p>
<p>
<blockquote><pre>%module example

%typemap(tcl,in) int {
	$target = (int) atoi($source);
	printf("Received an integer : %d\n",$target);
}
...
extern int fact(int n);
</pre></blockquote>
<p>
Typemaps require a language  name,  method name, datatype, and conversion code.  For Tcl, "tcl" should be used as the language name.  For Tcl 8.0, "tcl8" should be used if you are using the native object interface. The "in" method in this example refers to an input argument of a function. The datatype `int' tells SWIG that we are remapping integers.  The supplied code is used to convert from a Tcl string to the corresponding C datatype.  Within the supporting C code, the variable <tt>$source</tt> contains the source data (a string in this case) and <tt>$target</tt> contains the destination of a conversion (a C local variable).  <p>
<p>
When the example is compiled into a Tcl module, it will operate as follows :<p>
<p>
<blockquote><pre>% fact 6
Received an integer : 6
720
%
</pre></blockquote>
<p>
A full discussion of typemaps can be found in the main SWIG users reference.  We will primarily be concerned with Tcl typemaps here.<p>
<a name="n54"></a><h3> Tcl typemaps</h3>
The following typemap methods are available to Tcl modules :<p>
<p>
<tt>%typemap(tcl,in)</tt>	Converts a string to input function arguments<p>
<tt>%typemap(tcl,out)</tt>	Converts return value of a C function to a string<p>
<tt>%typemap(tcl,freearg)</tt>	Cleans up a function argument (if necessary)<p>
<tt>%typemap(tcl,argout)</tt>	Output argument processing<p>
<tt>%typemap(tcl,ret)</tt>	Cleanup of function return values<p>
<tt>%typemap(tcl,const)</tt>	Creation of Tcl constants<p>
<tt>%typemap(memberin)</tt>	Setting of C++ member data<p>
<tt>%typemap(memberout)</tt>	Return of C++ member data<p>
<tt>%typemap(tcl, check)</tt>	Check value of function arguments.<p>
<a name="n55"></a><h3> Typemap variables</h3>
The following variables may be used within the C code used in a typemap:<p>
<p>
<tt>$source</tt>	Source value of a conversion<p>
<tt>$target</tt>	Target of conversion (where the result should be stored)<p>
<tt>$type</tt>	C datatype being remapped<p>
<tt>$mangle</tt>	Mangled version of data (used for pointer type-checking)<p>
<tt>$value</tt>	Value of a constant (const typemap only)<p>
<tt>$arg</tt>	Original function argument (usually a string)<p>
<a name="n56"></a><h3> Name based type conversion</h3>
Typemaps are based both on the datatype and an optional name attached to a datatype.   For example :<p>
<p>
<blockquote><pre>%module foo

// This typemap will be applied to all char ** function arguments
%typemap(tcl,in) char ** { ... }

// This typemap is applied only to char ** arguments named `argv'
%typemap(tcl,in) char **argv { ... }

</pre></blockquote>
In this example, two typemaps are applied to the <tt>char **</tt> datatype.  However, the second typemap will only be applied to arguments named `<tt>argv</tt>'.  A named typemap will always override an unnamed typemap.<p>
<p>
Due to the name-based nature of typemaps, it is important to note that typemaps are independent of typedef declarations.  For example :<p>
<p>
<blockquote><pre>%typemap(tcl, in) double {
	... get a double ...
}
void foo(double);            // Uses the above typemap
typedef double Real;
void bar(Real);              // Does not use the above typemap (double != Real)

</pre></blockquote>
To get around this problem, the <tt>%apply</tt> directive can be used as follows :<p>
<blockquote><pre>
%typemap(tcl,in) double {
	... get a double ...
}
void foo(double);

typedef double Real;         // Uses typemap
%apply double { Real };      // Applies all "double" typemaps to Real.
void bar(Real);              // Now uses the same typemap.
</pre></blockquote>
<a name="n57"></a><h3> Converting  a Tcl list to a char ** </h3>
A common problem in many C programs is the processing of command line arguments, which are usually passed in an array of NULL terminated strings.   The following SWIG interface file allows a Tcl list to be used as a <tt>char **</tt> object.<p>
<p>
<blockquote><pre>%module argv

// This tells SWIG to treat char ** as a special case
%typemap(tcl,in) char ** {
        int tempc;
        if (Tcl_SplitList(interp,$source,&amp;tempc,&amp;$target) == TCL_ERROR) 
		return TCL_ERROR;
}

// This gives SWIG some cleanup code that will get called after the function call
%typemap(tcl,freearg) char ** {
        free((char *) $source);
}

// Return a char ** as a Tcl list
%typemap(tcl,out) char ** {
        int i = 0;
        while ($source[i]) {
             Tcl_AppendElement(interp,$source[i]);
             i++;
        }
}

// Now a few test functions
%inline %{
int print_args(char **argv) {
    int i = 0;
    while (argv[i]) {
         printf("argv[%d] = %s\n", i,argv[i]);
         i++;
    }
    return i;
}


// Returns a char ** list
char **get_args() {
    static char *values[] = { "Dave", "Mike", "Susan", "John", "Michelle", 0};
    return &amp;values[0];
}

// A global variable
char *args[] = { "123", "54", "-2", "0", "NULL", 0 };

%}
%include tclsh.i

</pre></blockquote>
When compiled, we can use our functions as follows :<p>
<p>
<blockquote><pre>% print_args {John Guido Larry}
argv[0] = John
argv[1] = Guido
argv[2] = Larry
3
% puts [get_args]
Dave Mike Susan John Michelle
% puts [args_get]
123 54 -2 0 NULL
%
</pre></blockquote>
<p>
Perhaps the only tricky part of this example is the implicit memory allocation that is performed by the <tt>Tcl_SplitList</tt> function.  To prevent a memory leak, we can use the SWIG "freearg" typemap to clean up the argument value after the function call is made. In this case, we simply free up the memory that <tt>Tcl_SplitList</tt> allocated for us.<p>
<a name="n58"></a><h3> Remapping constants</h3>
By default, SWIG installs C constants as Tcl read-only variables.  Unfortunately, this has the undesirable side effect that constants need to be declared as "global" when used in subroutines.  For example :<p>
<p>
<blockquote><pre>proc clearscreen { } {
	global GL_COLOR_BUFFER_BIT
	glClear $GL_COLOR_BUFFER_BIT
}

</pre></blockquote>
If you have hundreds of functions however, this quickly gets annoying.   Here's a fix using hash tables and SWIG typemaps :<p>
<p>
<blockquote><pre>// Declare some Tcl hash table variables
%{
static Tcl_HashTable  constTable;      /* Hash table          */
static int           *swigconst;       /* Temporary variable  */
static Tcl_HashEntry *entryPtr;        /* Hash entry          */
static int            dummy;           /* dummy value         */
%}

// Initialize the hash table (This goes in the initialization function)

%init %{
  Tcl_InitHashTable(&amp;constTable,TCL_STRING_KEYS);
%}

// A Typemap for creating constant values
// $source = the value of the constant
// $target = the name of the constant

%typemap(tcl,const) int, unsigned int, long, unsigned long {
  entryPtr = Tcl_CreateHashEntry(&amp;constTable,"$target",&amp;dummy);
  swigconst = (int *) malloc(sizeof(int));
  *swigconst = $source;
  Tcl_SetHashValue(entryPtr, swigconst);
  /* Make it so constants can also be used as variables */
  Tcl_LinkVar(interp,"$target", (char *) swigconst, TCL_LINK_INT | TCL_LINK_READ_ONLY);
};

// Now change integer handling to look for names in addition to values
%typemap(tcl,in) int, unsigned int, long, unsigned long {
  Tcl_HashEntry *entryPtr;
  entryPtr = Tcl_FindHashEntry(&amp;constTable,$source);
  if (entryPtr) {
    $target = ($type) (*((int *) Tcl_GetHashValue(entryPtr)));
  } else {
    $target = ($type) atoi($source);
  }
}

</pre></blockquote>
In our Tcl code, we can now access constants by name without using the "global" keyword as follows :<p>
<p>
<blockquote><pre>proc clearscreen { } {
	glClear GL_COLOR_BUFFER_BIT
}

</pre></blockquote>
<a name="n59"></a><h3> Returning values in arguments</h3>
The "argout" typemap can be used to return a value originating from a function argument. For example :<p>
<p>
<blockquote><pre>// A typemap defining how to return an argument by appending it to the result
%typemap(tcl,argout) double *outvalue {
        char dtemp[TCL_DOUBLE_SPACE];
        Tcl_PrintDouble(interp,*($source),dtemp);
        Tcl_AppendElement(interp, dtemp);
}

// A typemap telling SWIG to ignore an argument for input
// However, we still need to pass a pointer to the C function
%typemap(tcl,ignore) double *outvalue {
	static double temp;         /* A temporary holding place */
	$target = &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></blockquote>
When wrapped, SWIG matches the <tt>argout</tt> typemap to the "<tt>double *outvalue</tt>" argument. The "ignore" typemap 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>
<p>
<blockquote><pre>% mypow 2 3     # Returns two values, a status value and the result
0 8
%
</pre></blockquote>
<p>
An alternative approach to this is to return values in a Tcl variable as follows :<p>
<p>
<blockquote><pre>%typemap(tcl,argout) double *outvalue {
	char temp[TCL_DOUBLE_SPACE];
	Tcl_PrintDouble(interp,*($source),dtemp);
	Tcl_SetVar(interp,$arg,temp,0);
}
%typemap(tcl,in) double *outvalue {
	static double temp;
	$target = &amp;temp;
}

</pre></blockquote>
Our Tcl script can now do the following :<p>
<p>
<blockquote><pre>% set status [mypow 2 3 a]
% puts $status
0
% puts $a
8.0
%
</pre></blockquote>
Here, we have passed the name of a Tcl  variable to our C wrapper function which then places the return value in that variable.   This is now very close to the way in which a C function calling this function would work.<p>
<a name="n60"></a><h3> Mapping C structures into Tcl Lists</h3>
Suppose you have a C structure like this :<p>
<p>
<blockquote><pre>typedef struct {
  char  login[16];            /* Login ID  */
  int   uid;                  /* User ID   */
  int   gid;                  /* Group ID  */
  char  name[32];             /* User name */
  char  home[256];            /* Home directory */
} User;

</pre></blockquote>
By default, SWIG will simply treat all occurrences of "<tt>User</tt>" as a pointer.   Thus, functions like this :<p>
<p>
<blockquote><pre>extern void add_user(User u);
extern User *lookup_user(char *name);

</pre></blockquote>
will work, but they will be weird.   In fact, they may not work at all unless you write helper functions to create users and extract data.    A typemap can be used to fix this problem however.  For example :<p>
<p>
<blockquote><pre>// This works for both "User" and "User *"
%typemap(tcl,in) User * {
	int tempc;
	char **tempa;
	static User temp;
	if (Tcl_SplitList(interp,$source,&amp;tempc,&amp;tempa) == TCL_ERROR) return TCL_ERROR;
	if (tempc != 5) {
		free((char *) tempa);
		interp-&gt;result = "Not a valid User record";
		return TCL_ERROR;
	}
	/* Split out the different fields */
	strncpy(temp.login,tempa[0],16);
	temp.uid = atoi(tempa[1]);
	temp.gid = atoi(tempa[2]);
	strncpy(temp.name,tempa[3],32);
	strncpy(temp.home,tempa[4],256);
	$target = &amp;temp;
	free((char *) tempa);
}

// Describe how we want to return a user record
%typemap(tcl,out) User * {
	char temp[20];
	if ($source) {
	Tcl_AppendElement(interp,$source-&gt;login);
	sprintf(temp,"%d",$source-&gt;uid);
	Tcl_AppendElement(interp,temp);
	sprintf(temp,"%d",$source-&gt;gid);
	Tcl_AppendElement(interp,temp);
	Tcl_AppendElement(interp,$source-&gt;name);
	Tcl_AppendElement(interp,$source-&gt;home);
	}
}
</pre></blockquote>
<p>
These function marshall Tcl lists to and from our <tt>User</tt> data structure. This allows a more natural implementation that we can use as follows :<p>
<p>
<blockquote><pre>% add_user {beazley 500 500 "Dave Beazley" "/home/beazley"}
% lookup_user beazley
beazley 500 500 {Dave Beazley} /home/beazley

</pre></blockquote>
This is a much cleaner interface (although at the cost of some performance). The only caution I offer is that the pointer view of the world is pervasive throughout SWIG. Remapping complex datatypes like this will usually work, but every now and then you might find that it breaks. For example, if we needed to manipulate arrays of Users (also mapped as a "<tt>User *</tt>"), the typemaps defined here would break down and something else would be needed.  Changing the representation in this manner may also break the object-oriented interface. <p>
<a name="n61"></a><h3> Useful functions</h3>
The following tables provide some functions that may be useful in writing Tcl typemaps. Both Tcl 7.x and Tcl 8.x are covered.  For Tcl 7.x, everything is a string so the interface is relatively simple. For Tcl 8, everything is now a Tcl object so a more precise set of functions is required. Given the alpha-release status of Tcl 8, the functions described here may change in future releases.<p>
<center>
<img src="ch10.table.1.png"><br>
<img src="ch10.table.2.png"><br>
<img src="ch10.table.3.png"><br>
<img src="ch10.table.4.png"><br>
<img src="ch10.table.5.png"><br>
<img src="ch10.table.6.png"><br>
<img src="ch10.table.7.png">
</center><p>
<p>
<a name="n62"></a><h3> Standard  typemaps</h3>
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>
<center>
<img src="ch10.table.8.png"><br>
<img src="ch10.table.9.png"><br>
<img src="ch10.table.10.png"><br>
<img src="ch10.table.11.png">
</center><p>
<p>
<a name="n63"></a><h3> Pointer handling</h3>
SWIG pointers are mapped into Python strings containing the hexadecimal value and type.  The following functions can be used to create and read pointer values.<p>
<center><img src="ch10.table.12.png"></center><p>
<p>
These functions can be used in typemaps as well. For example, the following typemap makes an argument of "<tt>char *buffer</tt>" accept a pointer instead of a NULL-terminated ASCII string.<p>
<p>
<blockquote><pre>%typemap(tcl,in) char *buffer {
	if (SWIG_GetPtr($source, (void **) &amp;$target, "$mangle")) {
		Tcl_SetResult(interp,"Type error. Not a pointer", TCL_STATIC);
		return TCL_ERROR;
	}
}

</pre></blockquote>
Note that the <tt>$mangle</tt> variable generates the type string associated with the datatype used in the typemap.<p>
<p>
By now you hopefully have the idea that typemaps are a powerful mechanism for building more specialized applications.  While writing typemaps can be technical, many have already been written for you.  See the SWIG library reference for more information.<p>
<a name="n12"></a><h2> Configuration management with SWIG</h2>
After you start to work with Tcl for awhile, you suddenly realize that there are an unimaginable number of extensions, tools, and other packages.  To make matters worse, there are about 20 billion different versions of Tcl, not all of which are compatible with each extension (this is to make life interesting of course).<p>
<p>
While SWIG is certainly not a magical solution to the configuration management problem, it can help out alot in a number of key areas :<p>
<p>
<ul>
<li>SWIG generated code can be used with all versions of Tcl/Tk newer than 7.3/3.6. This includes the Tcl Netscape Plugin and Tcl 8.0a2.
<li>The SWIG library mechanism can be used to manage various code fragments and initialization functions.
<li>SWIG generated code usually requires no modification so it is relatively easy to switch between different Tcl versions as necessary or upgrade to a newer version when the time comes (of course, the Sun Tcl/Tk team might have changed other things to keep you occupied)
</ul>
<a name="n64"></a><h3> Writing a main program and Tcl_AppInit()</h3>
The traditional method of creating a new Tcl extension required a programmer to write a special function called <tt>Tcl_AppInit()</tt> that would initialize your extension and start the Tcl interpreter.  A typical <tt>Tcl_AppInit()</tt> function looks like the following :<p>
<p>
<blockquote><pre>/* main.c */
#include &lt;tcl.h&gt;

main(int argc, char *argv[]) {
	Tcl_Main(argc,argv);
	exit(0);
}

int Tcl_AppInit(Tcl_Interp *interp) {
	if (Tcl_Init(interp) == TCL_ERROR) {
		return TCL_ERROR;
	}
	
	/* Initialize your extension */
	if (Your_Init(interp) == TCL_ERROR) {
		return TCL_ERROR;
	}

	tcl_RcFileName = "~/.myapp.tcl";
	return TCL_OK;
}

</pre></blockquote>
While relatively simple to write, there are tons of problems with doing this.  First, each extension that you use typically has their own <tt>Tcl_AppInit()</tt> function.   This forces you to write a special one to initialize everything by hand.   Secondly, the process of writing a main program and initializing the interpreter varies between different versions of Tcl and different platforms.  For example, in Tcl 7.4, the variable "<tt>tcl_RcFileName</tt>" is a C variable while in Tcl7.5 and newer versions its a Tcl variable instead.   Similarly, the <tt>Tcl_AppInit</tt> function written for a Unix machine might not compile correctly on a Mac or Windows machine.<p>
<p>
In SWIG, it is almost never necessary to write a <tt>Tcl_AppInit()</tt> function because this is now done by  SWIG library  files such as <tt>tclsh.i</tt> or <tt>wish.i</tt>.    To give a better idea of what these files do, here's the code from the SWIG <tt>tclsh.i</tt> file which is roughly comparable to the above code<p>
<blockquote><pre>
// tclsh.i : SWIG library file for rebuilding tclsh
%{

/* A TCL_AppInit() function that lets you build a new copy
 * of tclsh.
 *
 * The macro SWIG_init contains the name of the initialization
 * function in the wrapper file.
 */

#ifndef SWIG_RcFileName
char *SWIG_RcFileName = "~/.myapprc";
#endif

int Tcl_AppInit(Tcl_Interp *interp){

  if (Tcl_Init(interp) == TCL_ERROR)
    return TCL_ERROR;

  /* Now initialize our functions */
  if (SWIG_init(interp) == TCL_ERROR)
    return TCL_ERROR;

#if TCL_MAJOR_VERSION &gt; 7 || TCL_MAJOR_VERSION == 7 &amp;&amp; TCL_MINOR_VERSION &gt;= 5
   Tcl_SetVar(interp,"tcl_rcFileName",SWIG_RcFileName,TCL_GLOBAL_ONLY);
#else
   tcl_RcFileName = SWIG_RcFileName;
#endif
  return TCL_OK;
}

#if TCL_MAJOR_VERSION &gt; 7 || TCL_MAJOR_VERSION == 7 &amp;&amp; TCL_MINOR_VERSION &gt;= 4
int main(int argc, char **argv) {
  Tcl_Main(argc, argv, Tcl_AppInit);
  return(0);

}
#else
extern int main();
#endif

%}
</pre></blockquote>
<p>
This file is essentially the same as a normal <tt>Tcl_AppInit()</tt> function except that it supports a variety of Tcl versions.  When included into an interface file, the symbol <tt>SWIG_init</tt> contains the actual name of the initialization function (This symbol is defined by SWIG when it creates the wrapper code).   Similarly, a startup file can be defined by simply defining the symbol <tt>SWIG_RcFileName</tt>.   Thus, a typical interface file might look like this :<p>
<p>
<blockquote><pre>%module graph
%{
#include "graph.h"
#define SWIG_RcFileName "graph.tcl"
%}

%include tclsh.i

... declarations ...


</pre></blockquote>
By  including the <tt>tclsh.i</tt>, you automatically get a <tt>Tcl_AppInit()</tt> function.   A variety of library files are also available.  <tt>wish.i</tt> can be used to build a new wish executable, <tt>expect.i</tt> contains the main program for Expect, and <tt>ish.i</tt>, <tt>itclsh.i</tt>, <tt>iwish.i</tt>, and <tt>itkwish.i</tt> contain initializations for various incarnations of [incr Tcl].<p>
<a name="n65"></a><h3> Creating a new package initialization library</h3>
If a particular Tcl extension requires special initialization, you can create a special SWIG library file to initialize it.  For example, a library file to extend Expect looks like the following :<p>
<p>
<blockquote><pre>
// expect.i : SWIG Library file for Expect
%{

/* main.c - main() and some logging routines for expect

Written by: Don Libes, NIST, 2/6/90

Design and implementation of this program was paid for by U.S. tax
dollars.  Therefore it is public domain.  However, the author and NIST
would appreciate credit if this program or parts of it are used.
*/

#include "expect_cf.h"
#include &lt;stdio.h&gt;
#include INCLUDE_TCL
#include "expect_tcl.h"

void
main(argc, argv)
int argc;
char *argv[];
{
        int rc = 0;
        Tcl_Interp *interp = Tcl_CreateInterp();
        int SWIG_init(Tcl_Interp *);

        if (Tcl_Init(interp) == TCL_ERROR) {
                fprintf(stderr,"Tcl_Init failed: %s\n",interp-&gt;result);
                exit(1);
        }
        if (Exp_Init(interp) == TCL_ERROR) {
                fprintf(stderr,"Exp_Init failed: %s\n",interp-&gt;result);
                exit(1);
        }

        /* SWIG initialization. --- 2/11/96  */
        if (SWIG_init(interp) == TCL_ERROR) {
                fprintf(stderr,"SWIG initialization failed: %s\n", interp-&gt;result);
                exit(1);
        }

        exp_parse_argv(interp,argc,argv);
        /* become interactive if requested or "nothing to do" */
        if (exp_interactive)
                (void) exp_interpreter(interp);
        else if (exp_cmdfile)
                rc = exp_interpret_cmdfile(interp,exp_cmdfile);
        else if (exp_cmdfilename)
                rc = exp_interpret_cmdfilename(interp,exp_cmdfilename);

        /* assert(exp_cmdlinecmds != 0) */
        exp_exit(interp,rc);
        /*NOTREACHED*/
}
%}
</pre></blockquote>
<p>
In the event that you need to write a new library file such as this, the process usually isn't too difficult.  Start by grabbing the original <tt>Tcl_AppInit()</tt> function for the package.  Enclose it in a <tt>%{,%}</tt> block.   Now add a line that makes a call to <tt>SWIG_init()</tt>.    This will automatically resolve to the real initialization function when compiled.<p>
<a name="n66"></a><h3> Combining Tcl/Tk Extensions</h3>
A slightly different problem concerns the mixing of various extensions.  Most extensions don't require any special initialization other than calling their initialization function.  To do this, we also use SWIG library mechanism.  For example :<p>
<p>
<blockquote><pre>// blt.i : SWIG library file for initializing the BLT extension
%{
#ifdef __cplusplus 
extern "C" {
#endif
extern int Blt_Init(Tcl_Interp *);
#ifdef __cplusplus
}
#endif
%}
%init %{
	if (Blt_Init(interp) == TCL_ERROR) {
		return TCL_ERROR;
	}
%}


// tix.i : SWIG library file for initializing the Tix extension
%{
#ifdef __cplusplus 
extern "C" {
#endif
extern int Tix_Init(Tcl_Interp *);
#ifdef __cplusplus
}
#endif
%}
%init %{
	if (Tix_Init(interp) == TCL_ERROR) {
		return TCL_ERROR;
	}
%}

</pre></blockquote>
Both files declare the proper initialization function (to be C++ friendly, this should be done using <tt>extern "C"</tt>).    A call to the initialization function is then placed inside a <tt>%init %{ ... %}</tt> block.  <p>
<p>
To use our library files and build a new version of wish, we might now do the following :<p>
<p>
<blockquote><pre>// mywish.i : wish with a bunch of stuff added to it
%include wish.i
%include blt.i
%include tix.i

... additional declarations ...

</pre></blockquote>
Of course, the really cool part about all of this is that the file `<tt>mywish.i</tt>' can itself, serve as a library file.   Thus, when building various versions of Tcl, we can place everything we want to use a special file and use it in all of our other interface files :<p>
<p>
<blockquote><pre>// interface.i
%module mymodule

%include mywish.i              // Build our version of Tcl with extensions

... C declarations ...

</pre></blockquote>
or we can grab it on the command line :<p>
<p>
<blockquote><pre>unix &gt; swig -tcl -lmywish.i interface.i

</pre></blockquote>
<a name="n67"></a><h3> Limitations to this approach</h3>
This interface generation approach is limited by the compatibility of each extension you use.  If any one extension is incompatible with the version of Tcl you are using, you may be out of luck.  It is also critical to pay careful attention to libraries and include files.  An extension library compiled against an older version of Tcl may fail when linked with a newer version.  <p>
<a name="n68"></a><h3> Dynamic loading </h3>
Newer versions of Tcl support dynamic loading.   With dynamic loading, you compile each extension into a separate module that can be loaded at run time.   This simplifies a number of compilation and extension building problems at the expense of creating new ones.  Most notably, the dynamic loading process varies widely between machines and is not even supported in some cases.   It also does not work well with C++ programs that use static constructors.   Modules linked with older versions of Tcl may not work with newer versions as well (although SWIG only really uses the basic Tcl C interface).  As a result, I usually find myself using both dynamic and static linking as appropriate. <p>
<a name="n69"></a><h3> Turning a SWIG module into a Tcl Package.</h3>
Tcl 7.4 introduced the idea of an extension package.   By default, SWIG does not create "packages", but it is relatively easy to do.   To make a C extension into a Tcl package, you need to provide a call to <tt>Tcl_PkgProvide() </tt>in the module initialization function<tt>.</tt>   This can be done in an interface file as follows :<p>
<p>
<blockquote><pre>%init %{
        Tcl_PkgProvide(interp,"example","0.0");
%}
</pre></blockquote>
<p>
Where "example" is the name of the package and "0.0" is the version of the package.  <p>
<p>
Next, after building the SWIG generated module, you need to execute the "<tt>pkg_mkIndex</tt>" command inside tclsh.   For example :<p>
<blockquote><pre>
unix &gt; tclsh
% pkg_mkIndex . example.so
% exit

</pre></blockquote>
This creates a file "<tt>pkgIndex.tcl</tt>" with information about the package.    To use your<p>
package, you now need to move it to its own subdirectory which has the same name as the package. For example :<p>
<p>
<blockquote><pre>./example/
	   pkgIndex.tcl           # The file created by pkg_mkIndex
	   example.so             # The SWIG generated module

</pre></blockquote>
<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>
<blockquote><pre>
unix &gt; tclsh
% package require example
% fact 4
24
%
</pre></blockquote>
<p>
If  you're working with an example in the current directory and this doesn't work, do this instead :<p>
<p>
<blockquote><pre>unix &gt; tclsh
% lappend auto_path .
% package require example
% fact 4
24

</pre></blockquote>
<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>
<a name="n13"></a><h2> Building new kinds of Tcl interfaces (in Tcl)</h2>
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>
<p>
<blockquote><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></blockquote>
While these could be called directly, we could also write a Tcl script like this :<p>
<p>
<blockquote><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 "get_$type $parms"]}
            set {return [eval "set_$type $parms"]}
            delete {eval "delete_$type $ptr; rename $ptr {}"}
        }
    }
    # Create a procedure
    uplevel "proc $ptr args {set ptr $ptr; set type $type;$code}"
    return $ptr
}
</pre></blockquote>
<p>
Our script allows easy array access as follows :<p>
<p>
<blockquote><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></blockquote>
<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>
<a name="n70"></a><h3> Shadow classes</h3>
A similar approach can be applied to 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>
<p>
<blockquote><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 "handle_r".
    #
    # Also creates a procedure for the object and a trace on
    # the handle variable that deletes the object when the
    # handle varibale 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} "eval ${objectType}_\$cmd $handle \$args"
    #
    # And the trace ...
    #
    uplevel trace variable $handle_r uw "{deleteObject $objectType $handle}"
    #
    # 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 "deleteObject: not a valid object handle: $handle"
    }
    #
    # 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></blockquote>
<p>
To use this file, we simply source it and execute commands such as "new" and "delete" to manipulate objects.  For example :<p>
<p>
<blockquote><pre>// list.i
%module List
%{
#include "list.h"
%}

// 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></blockquote>
<p>
Now a Tcl script using the interface...<p>
<p>
<blockquote><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></blockquote>
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>
<a name="n14"></a><h2> Extending the Tcl Netscape Plugin</h2>
SWIG can be used to extend the Tcl Netscape plugin with C functions. As of this writing it has only been tested with version 1.0 of the plugin on Solaris and Irix 6.2.  It may work on other machines as well. However, first a word of caution --- doing this might result in serious injury as you can add just about any C function you want.   Furthermore, it's not portable (hey, we're talking C code here).    It seems like the best application of this would be creating a browser interface to a highly specialized application.  Any scripts that you would write would not work on other machines unless they also installed the C extension code as well.  Perhaps we should call this a plugin-plugin...<p>
<p>
To use the plugin, use the <tt>-plugin</tt> option :<p>
<p>
<blockquote><pre>swig -tcl -plugin interface.i

</pre></blockquote>
This adds a "safe" initialization function compatible with the plugin (in reality, it just calls the function SWIG already creates).    You also need to put the following symbol in your interface file for it to work :<p>
<p>
<blockquote><pre>%{
#define SAFE_SWIG
%}

</pre></blockquote>
The folks at Sun are quite concerned about the security implications of this sort of extension and originally wanted the user to modify the wrapper code by hand to "remind" them that they were installing functions into a safe interpreter.   However, having seen alot of SWIG generated wrapper code, I hated that idea (okay, so the output of SWIG is just a little messy).    This is compromise--you need to put that <tt>#define</tt> into your C file someplace.  You can also just make it a compiler option if you would like.<p>
<a name="n71"></a><h3> The step-by-step process for making a plugin extension.</h3>
Making a plugin extension is relatively straightforward but you need to follow these steps :<p>
<p>
<ul>
<li>Make sure you have Tcl7.6/Tk4.2 installed on your machine.   We're going to need the header files into order to compile the extension.
<li>Make sure you have the Netscape plugin properly installed.
<li>Run SWIG using the `<tt>-tcl -plugin</tt>' options. 
<li>Compile the extension using the Tcl 7.6/Tk4.2 header files, but linking against the plugin itself.  For example :
<blockquote><pre>
unix &gt; gcc -I/usr/local/include -c example.o interface_wrap.c 
unix &gt; ld -shared example.o interface_wrap.o \
       -L/home/beazley/.netscape/plugins/libtclplugin.so -o example.so 

</pre></blockquote>
<li>Copy the shared object file to the <tt>~/.tclplug/tcl7.7</tt> directory.
</ul>
<a name="n72"></a><h3> Using the plugin</h3>
To use the plugin, place the following line in your Tcl scripts :<p>
<p>
<blockquote><pre>load $tcl_library/example.so example

</pre></blockquote>
With luck, you will now be ready to run (at least that's the theory).<p>
<a name="n15"></a><h2> Tcl8.0 features</h2>
SWIG 1.1 now supports Tcl 8.0.  However, considering the beta release nature of Tcl 8.0, anything presented here is subject to change.  Currently only Tcl 8.0b1 is supported.  None of the alpha releases are supported due to a change in the C API. <p>
<p>
The Tcl 8.0 module uses the new Tcl 8.0 object interface whenever possible.  Instead of using strings, the object interface provides more direct access to objects in their native representation. As a result, the performance is significantly better.     The older Tcl SWIG module is also compatible with Tcl 8.0, but since it uses strings it will be much slower than the new version.<p>
<p>
In addition to using native Tcl objects, the Tcl8.0 manipulates pointers directly in in a special Tcl object.   On the surface it still looks like a string, but internally its represented a (value,type) pair.   This too, should offer somewhat better performance.<p>
<p>
<p>

<p><hr>

<address>SWIG 1.1 - Last Modified : Mon Aug  4 10:47:12 1997</address>
</body>
</html>