summaryrefslogtreecommitdiff
path: root/Doc/Manual/COM.html
blob: 00ea22634478e0ebdef26bc8dd147974802ef8a5 (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
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>SWIG and COM</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body bgcolor="#FFFFFF">
<H1><a name="COM"></a>17 SWIG and COM</H1>
<!-- INDEX -->
<div class="sectiontoc">
<ul>
<li><a href="#com_overview">Overview</a>
<li><a href="#com_preliminaries">Preliminaries</a>
<ul>
<li><a href="#com_running_swig">Running SWIG</a>
<li><a href="#com_commandline">Additional Commandline Options</a>
<li><a href="#com_compiling_dynamic">Compiling a dynamic module</a>
<li><a href="#com_using_module">Using your module</a>
</ul>
<li><a href="#com_practical_tips">Practical Tips for Using and Testing the COM Module</a>
<ul>
<li><a href="#com_tips_overview">Overview</a>
<li><a href="#com_compilation_using_various_toolchains">Compilation using various toolchains</a>
<ul>
<li><a href="#com_microsoft_visual_studio">Microsoft Visual Studio</a>
<li><a href="#com_mingw_cywin_on_windows_using_midl">MinGW/Cygwin on Windows (using MIDL)</a>
<li><a href="#com_digital_mars_cpp_on_windows">Digital Mars C++ on Windows (using MIDL)</a>
<li><a href="#com_mingw_on_linux_usin_widl">MinGW on Linux (using WIDL)</a>
<li><a href="#com_winegcc">WineGCC</a>
</ul>
<li><a href="#com_testing_environment_windows_cygwin_midl">Testing environment (Windows/Cygwin and MIDL)</a>
<ul>
<li><a href="#com_using_cygwin_default_compiler">Using Cygwin's default C/C++ compiler</a>
<li><a href="#com_using_microsoft_visual_cpp">Using Microsoft Visual C++</a>
<li><a href="#com_using_digital_mars_cpp">Using Digital Mars C++</a>
</ul>
<li><a href="#com_testing_environment">Testing environment (Unix/Linux, using WINE and possibly MinGW)</a>
<li><a href="#com_winegcc2">Winegcc</a>
<li><a href="#com_mingw">MinGW</a>
<ul>
<li><a href="#com_vbscript_run_tests_on_linux">VBScript run tests on Linux</a>
</ul>
</ul>
<li><a href="#com_basic_tour">A tour of basic C/C++ wrapping</a>
<ul>
<li><a href="#com_functions">Global functions</a>
<li><a href="#com_global_variables">Global variables</a>
<li><a href="#com_constants">Constants</a>
<li><a href="#com_enumerations">Enumerations</a>
<li><a href="#com_pointers">Pointers</a>
<li><a href="#com_structures">Structures</a>
<li><a href="#com_classes">C++ classes</a>
<li><a href="#com_inheritance">C++ inheritance</a>
<li><a href="#com_pointers_refs_arrays">Pointers, references, arrays and pass by value</a>
<ul>
<li><a href="#com_null_pointers">Null pointers</a>
</ul>
<li><a href="#com_overloaded_functions">C++ overloaded functions</a>
<li><a href="#com_default_arguments">C++ default arguments</a>
<li><a href="#com_namespaces">C++ namespaces</a>
<li><a href="#com_constructors">Constructors</a>
<li><a href="#com_templates">C++ templates</a>
<li><a href="#com_smart_pointers">C++ Smart Pointers</a>
</ul>
<li><a href="#com_further_details">Further details on COM wrapping</a>
<ul>
<li><a href="#com_classes_and_interfaces">Classes and interfaces</a>
<li><a href="#com_module_class">Module class and class objects</a>
<li><a href="#com_guids">GUID handling</a>
<li><a href="#com_class_factories">Class factories and aggregation</a>
<li><a href="#com_hresult">IDispatch and HRESULT as return value</a>
<li><a href="#com_iswigwrappedobject">ISWIGWrappedObject interface</a>
<li><a href="#com_memory">Memory management</a>
<li><a href="#com_exception">Exceptions</a>
</ul>
<li><a href="#com_customization">Customization features</a>
<ul>
<li><a href="#com_typemaps">Typemaps</a>
</ul>
</ul>
</div>
<!-- INDEX -->



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


<H2><a name="com_overview"></a>17.1 Overview</H2>


<p>
COM is a component technology included in the Windows operating system. It is supported by a wide range of tools - scripting languages
(VBScript, Perl, Python), compiled languages (Delphi, Visual Basic, C#) and even complex applications (MS Office, OpenOffice.org). Thus
writing a COM component is a good way to extend all of these applications at one time. Unfortunately writing COM components in C/C++
is a non-trivial task which is even harder if you do not use Microsoft's tools (especially if you use one of GCC compilers).
</p>

<p>
SWIG's COM extension allows you to easily make your C/C++ code accessible to COM-aware tools using the compiler of your choice. It takes care
of many low-level tasks like component registration, memory management, object layout, etc. It preserves the class hierarchy contained in
the C++ code with some limitations - notably only single inheritance is supported. You should try using the COM extension if you have
a large code base using a custom programming interface. On the other hand if you need to implement a fixed COM interface (e.g. a 'visual component'
or a DirectShow filter) then SWIG will probably not be the right tool for you.
</p>

<p>
This chapter is focused mostly on COM-aware scripting languages. The examples - unless noted otherwise - are provided in a subset of Basic
which should work in Visual Basic (including VBA), VBScript and OpenOffice.org Basic. This should not discourage you if you plan to use another language -
the code should be very similar, if not identical, in other scripting languages. The code generated by the COM extension has also been verified to work well in
Delphi and C#.
</p>


<H2><a name="com_preliminaries"></a>17.2 Preliminaries</H2>


<p>
To compile the generated code you will need a compiler that supports generating DLLs and understands the __stdcall calling convention.
The compilers that have been tested extensively are MS Visual C++ and MinGW. OpenWatcom, Digital Mars C++, Borland C++ and Cygwin are
tested occasionally and should have no problems. Winegcc can be used on Unix systems but has some limitations. Please note that the
code has only been tested on 32-bit x86 processors. You will also need an IDL compiler - most probably this will
be MIDL (shipped with the Windows SDK, previously known as Platform SDK) but WIDL (shipped with WINE) can be used
too.
</p>


<H3><a name="com_running_swig"></a>17.2.1 Running SWIG</H3>


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

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


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

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

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

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

<p>
This will generate four files: <tt>example_wrap.c</tt> (or <tt>example_wrap.cxx</tt>),
<tt>example.idl</tt>, <tt>example.def</tt> and <tt>example.rc</tt>. The first file
contains code responsible for object layout, reference counting, etc. The <tt>example.idl</tt>
file contains a description of the interface exposed to the client applications. The remaining
two files are used during compilation. All these files need to be linked with the rest of
your C/C++ application.
</p>

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

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

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


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

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

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

<tr>
<td>-namespace &lt;name&gt;</td>
<td>set name to be used as the prefix of your classes' IDispatch names (e.g. for use with CreateObject in Basic)</td>
</tr>

</table>

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

<H3><a name="com_compiling_dynamic"></a>17.2.3 Compiling a dynamic module</H3>


<p>
Before your module can be used by COM clients it needs to be built as a dynamically linked library (DLL).
This process is compiler specific. Examples are provided below for Visual C++:
</p>

<div class="code"><pre>
$ # MS Visual Studio 2008
$ midl example.idl
$ rc example.rc
$ cl /LD /Feexample.dll example_wrap.c example.def example.res ole32.lib uuid.lib advapi32.lib oleaut32.lib
</pre></div>

<p>
and for MinGW under Linux (using WIDL):
</p>

<div class="code"><pre>
$ # MinGW and WIDL
$ widl -t -I /usr/include/wine/windows example.idl
$ i586-mingw32msvc-windres example.rc example_rc.o
$ i586-mingw32msvc-gcc -shared -o example.dll example_wrap.c example.def example_rc.o -lole32 -luuid -ladvapi32 -loleaut32
</pre></div>

<p>
On a Windows installation of MinGW the names of the executables will most probably simply be <tt>windres</tt> and
<tt>gcc</tt>, and <tt>midl</tt> can be used in place of <tt>widl</tt>. Note that the output of <tt>windres</tt>
is an object file and may cause naming conflicts if you have a source file called <tt>example.c</tt> or
<tt>example.cpp</tt>. A simple solution is to rename the object file as was done above (e.g. to <tt>example_rc.o</tt>).
</p>

<p>
Build instructions for some other toolchains
may be found on <a href="http://www.dabeaz.com/cgi-bin/wiki.pl?DeveloperInfo/COMTesting">this page</a> of the
SWIG Wiki.
</p>

<p>
<b>Warning</b> <br>
A common source of mistakes is the omission of <tt>example.res</tt> (or <tt>example_rc.o</tt>) during compilation.
This produces no errors or warnings but results in a non-working module.
</p>

<p>
Before you can use your module you need to register it (on the machine where it will be used):
</p>

<div class="code"><pre>
$ regsvr32 example.dll
</pre></div>

<p>
This will create entries in the registry needed to locate your module. Please note that this will store
the filesystem path to <tt>example.dll</tt> so you should not move this file to another location. If
you wish to unregister your module simply type:
</p>

<div class="code"><pre>
$ regsvr32 /u example.dll
</pre></div>

<H3><a name="com_using_module"></a>17.2.4 Using your module</H3>


<p>
The precise approach to loading your module depends on the target language. In Basic you can use the
<tt>CreateObject</tt> subroutine:
</p>

<div class="code"><pre>
Dim example
Set example = CreateObject("example.example")
</pre></div>

<p>
The variable <tt>example</tt> now contains a reference to an object of the <i>module class</i> which
allows you to call global functions and access global variables defined in your module. It also
allows you to create instances of C++ classes and to call static member functions.
</p>

<H2><a name="com_practical_tips"></a>17.3 Practical Tips for Using and Testing the COM Module</H2>


<H3><a name="com_tips_overview"></a>17.3.1 Overview</H3>


<p>
Setting up the infrastructure needed for running the test-suite using the COM module is a bit more tricky than for other modules. This is because you need tools that are usually not present on POSIX systems, like a IDL and RC compiler. In addition often the compiler used for building SWIG itself is not appropriate for running the tests. This page shows some ways to set up an environment for running the test-suite.
<p>
<H3><a name="com_compilation_using_various_toolchains"></a>17.3.2 Compilation using various toolchains</H3>


<p>
This section lists the commands used for compiling the modules using various toolchains. This might be useful for verifying if the environment is set up correctly. We assume that we are using C++ and that the module is named 'example'.
<p>
<H4><a name="com_microsoft_visual_studio"></a>17.3.2.1 Microsoft Visual Studio</H4>


<p>
<div class="shell">
<pre>
$ midl example.idl
$ rc example.rc
$ cl /LD /GR /EHs /Feexample.dll example.cpp example_wrap.cxx example.def example.res ole32.lib uuid.lib advapi32.lib oleaut32.lib
</pre>
</div>
<p>
<H4><a name="com_mingw_cywin_on_windows_using_midl"></a>17.3.2.2 MinGW/Cygwin on Windows (using MIDL)</H4>


<p>
Please note that the MinGW linker does not understand .res files and the .rc file needs to be compiled to an object file before linking. To prevent potential name clashes you can rename the object file containing the resources, as shown below.
<p>
<div class="shell">
<pre>
$ midl example.idl
$ windres example.rc example_rc.o
$ g++ -shared -o example.dll example.cpp example_wrap.cxx example.def example_rc.o -lole32 -luuid -ladvapi32 -loleaut32
</pre>
</div>
<p>
<H4><a name="com_digital_mars_cpp_on_windows"></a>17.3.2.3 Digital Mars C++ on Windows (using MIDL)</H4>


<div class="shell">
<pre>
$ midl example.idl
$ rcc example.rc
$ dmc -WD -L/exetype:nt -oexample.dll example.cpp example_wrap.cxx example.def example.res ole32.lib uuid.lib advapi32.lib oleaut32.lib kernel32.lib user32.lib
</pre>
</div>
<p>
<H4><a name="com_mingw_on_linux_usin_widl"></a>17.3.2.4 MinGW on Linux (using WIDL)</H4>


<p>
Please note that the MinGW linker does not understand .res files and the .rc file needs to be compiled to an object file before linking. To prevent potential name clashes you can rename the object file containing the resources, as shown below.
<p>
<div class="shell">
<pre>
$ widl -t -I /usr/include/wine/windows example.idl
$ i586-mingw32msvc-windres example.rc example_rc.o
$ i586-mingw32msvc-g++ -shared -o example.dll example.cpp example_wrap.cxx example.def example_rc.o -lole32 -luuid -ladvapi32 -loleaut32
</pre>
</div>
<p>
<H4><a name="com_winegcc"></a>17.3.2.5 WineGCC</H4>


<p>
<div class="shell">
<pre>
$ widl -t -I /usr/include/wine/windows example.idl
$ wrc -i example.rc -o example.res
$ wineg++ -shared -o example.dll.so example.cpp example_wrap.cxx example.def example.res -lole32 -luuid -ladvapi32 -loleaut32
</pre>
</div>
<p>
You are welcome to add instructions for other toolchains to this page.
<p>
<H3><a name="com_testing_environment_windows_cygwin_midl"></a>17.3.3 Testing environment (Windows/Cygwin and MIDL)</H3>


<p>
This section shows how you can run the tests on Windows using Cygwin (using various C/C++ compilers). Other POSIX-like environments (UWIN, MS SFU, MKS Toolkit) might work too but have not been tested. We assume that you have the MIDL compiler (search for midl.exe) installed somewhere; it comes with Visual Studio and probably also with the Windows SDK (previously known as Platform SDK).
<p>
<H4><a name="com_using_cygwin_default_compiler"></a>17.3.3.1 Using Cygwin's default C/C++ compiler</H4>


<p>
The only thing not available in Cygwin is the IDL compiler, so you will need to set it up (unless you are lucky and midl works out of the box). You can use the following script to set up the paths needed by MIDL (you may need to adjust the actual paths):
<p>
<div class="code">
<pre>
# vars_cygwin.sh

# Path to midl.exe
export PATH=$PATH:/cygdrive/c/Program\ Files/Microsoft\ SDKs/Windows/v6.0A/bin

# Path to cl.exe (used as preprocessor)
export PATH=$PATH:/cygdrive/c/Program\ Files/Microsoft\ Visual\ Studio\ 9.0/VC/bin/

# Contains DLLs needed by cl.exe
export PATH=$PATH:/cygdrive/c/Program\ Files/Microsoft\ Visual\ Studio\ 9.0/Common7/IDE

# Platform includes, needed for MIDL
export INCLUDE=c:\\Program\ Files\\Microsoft\ SDKs\\Windows\\v6.0A\\Include 
</pre>
</div>
<p>
Now you can use the following options for configure:
<p>
<div class="shell">
<pre>
$ . ./vars_cygwin.sh
$ ./configure --with-com-cc=gcc --with-com-cxx=g++ --with-com-idl=midl --with-com-rc=windres
</pre>
</div>
<p>
<H4><a name="com_using_microsoft_visual_cpp"></a>17.3.3.2 Using Microsoft Visual C++</H4>


<p>
You can use the following script to set up the paths needed by MSVC and MIDL (you may need to adjust the actual paths):
<p>
<div class="code">
<pre>
# vars_vc.sh

# Path to midl.exe
export PATH=$PATH:/cygdrive/c/Program\ Files/Microsoft\ SDKs/Windows/v6.0A/bin

# Path to cl.exe (used as preprocessor)
export PATH=$PATH:/cygdrive/c/Program\ Files/Microsoft\ Visual\ Studio\ 9.0/VC/bin/

# Contains DLLs needed by cl.exe
export PATH=$PATH:/cygdrive/c/Program\ Files/Microsoft\ Visual\ Studio\ 9.0/Common7/IDE

# Includes
export INCLUDE=c:\\Program\ Files\\Microsoft\ SDKs\\Windows\\v6.0A\\Include\;c:\\Program\ Files\\Microsoft\ Visual\ Studio\ 9.0\\VC\\Include

# Libs
export LIB=c:\\Program\ Files\\Microsoft\ SDKs\\Windows\\v6.0A\\Lib\;c:\\Program\ Files\\Microsoft\ Visual\ Studio\ 9.0\\VC\\Lib
</pre>
</div>
<p>
Now you can use the following options for configure:
<p>
<div class="shell">
<pre>
$ . ./vars_vc.sh
$ ./configure --with-com-cc=cl --with-com-cxx=cl --with-com-idl=midl --with-com-rc=rc
</pre>
</div>
<p>
<H4><a name="com_using_digital_mars_cpp"></a>17.3.3.3 Using Digital Mars C++</H4>


<p>
You can use the following script to set up the paths needed by DMC and MIDL (you may need to adjust the actual paths):
<p>
<div class="code">
<pre>
# vars_dmc.sh

# Path to midl.exe
export PATH=$PATH:/cygdrive/c/Program\ Files/Microsoft\ SDKs/Windows/v6.0A/bin

# Path to cl.exe (used as preprocessor)
export PATH=$PATH:/cygdrive/c/Program\ Files/Microsoft\ Visual\ Studio\ 9.0/VC/bin/

# Path to Digital Mars installation
# Note: It is important that DMC's cl.exe does not override Visual Studio's
#       cl.exe which is used as the C preprocessor by midl.exe
export PATH=$PATH:/cygdrive/c/Program\ Files/dmc/bin

# Contains DLLs needed by cl.exe
export PATH=$PATH:/cygdrive/c/Program\ Files/Microsoft\ Visual\ Studio\ 9.0/Common7/IDE

# Platform includes, needed for MIDL
export INCLUDE=c:\\Program\ Files\\Microsoft\ SDKs\\Windows\\v6.0A\\Include
</pre>
</div>
<p>
Now you can use the following options for configure:
<p>
<div class="shell">
<pre>
$ . ./vars_dmc.sh
$ ./configure --with-com-cc=dmc --with-com-cxx=dmc --with-com-idl=midl --with-com-rc=rcc
</pre>
</div>
<p>
<H3><a name="com_testing_environment"></a>17.3.4 Testing environment (Unix/Linux, using WINE and possibly MinGW)</H3>


<p>
On Unix platforms you will definitely need WINE (for WIDL and for run-tests) - most recent versions should be OK (0.9.46, 1.0 and 1.1.0 are known to work). You may use WINE's gcc wrapper (winegcc) or the separate MinGW cross compiler. We assume that the binaries are present in your PATH.
<p>
<H3><a name="com_winegcc2"></a>17.3.5 Winegcc</H3>


<p>
If you have WINE installed properly you can just use the following options for configure:
<p>
<div class="shell">
<pre>
$ ./configure --with-com-runtool=wine --with-com-cc=winegcc --with-com-cxx=wineg++ --with-com-idl=widl --with-com-rc=wrc
</pre>
</div>
<p>
<H3><a name="com_mingw"></a>17.3.6 MinGW</H3>


<p>
For MinGW use the following options:
<p>
<div class="shell">
<pre>
$ ./configure --with-com-runtool=wine --with-com-cc=i586-mingw32msvc-gcc --with-com-cxx=i586-mingw32msvc-g++ --with-com-idl=widl --with-com-rc=i586-mingw32msvc-windres
</pre>
</div>
<p>
<H4><a name="com_vbscript_run_tests_on_linux"></a>17.3.6.1 VBScript run tests on Linux</H4>


<p>
The test suite contains run-tests written in C and in VBScript. The C tests should 'just work' as should the VBScript ones on Windows. If you want to use the VBScript tests on Linux you will first need to install the Windows Script Host (standalone or as part of Internet Explorer) under WINE. This procedure may depend on the version of WINE/WSH/IE and is outside of the scope of this page. After installing WSH you will need to create a wrapper script (let's call it cscript) and put it in your PATH. The script could look like this:
<p>
<div class="shell">
<pre>
#!/bin/sh

wine c:\\windows\\system32\\cscript.exe $*
</pre>
</div>
<p>
You can then add the following option to configure:
<p>
<div class="shell">
<pre>
--with-com-cscript=cscript
</pre>
</div>
<p>
On platforms other than Windows/Cygwin the presence of cscript is not autodetected (as it's highly unusual to have it) and you will need to specify it manually.

<H2><a name="com_basic_tour"></a>17.4 A tour of basic C/C++ wrapping</H2>


<p>
SWIG will try to create an interface as similar to the C/C++ code as possible. However because
of differences between C/C++ and COM there are some aspects that need
special attention. They are described in this section
</p>

<H3><a name="com_functions"></a>17.4.1 Global functions</H3>


<p>
In COM there are no global functions and therefore SWIG uses a workaround. It defines a class known as
the <i>module class</i> which contains the global functions and variables from your C/C++ module.
The example below shows how you can call a global function from a COM client:
</p>

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

<p>
From VB (and most other languages derived from Basic) you can invoke it as follows:
</p>

<div class="code"><pre>
Dim example
Set example = CreateObject("example.example")
Print example.fact(4)
</pre></div>


<H3><a name="com_global_variables"></a>17.4.2 Global variables</H3>


<p>
Global variables are wrapped as COM properties. This allows you to use them just as you would use them in
C/C++. For example this module:
</p>

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

<p>
Can be used in the following way:
</p>

<div class="code"><pre>
Dim example
Set example = CreateObject("example.example")

Rem Print out the value of a C global variable
Print example.My_variable

Rem Set the value of a C global variable
example.density = 0.8442
</pre></div>

<p>
If a variable is declared as <tt>const</tt>, it is wrapped as a read-only property.
This means that its value can be read, but cannot be modified. To make ordinary variables read-only,
you can use the <tt>%immutable</tt> directive. For example:
</p>

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

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

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

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


<H3><a name="com_constants"></a>17.4.3 Constants</H3>


<p>
C/C++ constants are wrapped as immutable properties. This applies both to constants
created using <tt>#define</tt> preprocessor directive and the SWIG <tt>%constant</tt>
directive. Examples are provided below:
</p>

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

<p>
Please note that SWIG can infer the C type from the <tt>#define</tt> directive - <tt>PI</tt>
is wrapped as a floating point value while <tt>VERSION</tt> is wrapped as a string.
</p>

<H3><a name="com_enumerations"></a>17.4.4 Enumerations</H3>


<p>
The COM module currently only supports type-unsafe enumerations, which are mapped to integers
in COM. Enum values are represented as immutable (read-only) integer constants. For example
assume you have the following code:
</p>

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

enum Beverage { ALE, LAGER=10, STOUT, PILSNER, PILZ=PILSNER };

int func(Beverage arg);
</pre>
</div>

<p>
You can use the wrapped code like this:
</p>

<div class="code">
<pre>
Dim example, res

Set example = CreateObject("example.example")
res = example.func(example.PILSNER)
</pre>
</div>

<p>
If your enum is defined inside a class its values will be accessible using the class, e.g.:
</p>

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

class MyClass {
public:
  enum Beverage { ALE, LAGER=10, STOUT, PILSNER, PILZ=PILSNER };
  static Beverage bev;
};
</pre>
</div>

<p>
The resulting COM object can be used as follows:
</p>

<div class="code">
<pre>
Dim example, res

Set example = CreateObject("example.example")
example.MyClass.bev = example.MyClass.PILSNER
</pre>
</div>

<H3><a name="com_pointers"></a>17.4.5 Pointers</H3>


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

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

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

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

<div class="code">
<pre>
Dim example
Dim f

Set example = CreateObject("example.example")
Set f = example.fopen("junk","w")
example.fputs("Hello World", f)
example.fclose(f)
</pre>
</div>

<p>
Since the <tt>FILE</tt> structure is not known to SWIG the pointer is stored as a <tt>void *</tt> pointer. You
can pass this pointer to other functions that expect to receive a pointer to <tt>FILE</tt>. You cannot dereference
the pointer or manipulate it in any other way.
</p>

<p>
To allow for static type checking a class is generated for each unknown type. In this case the <tt>FILE *</tt>
pointer is wrapped as an object implementing interface <tt>ISWIGTYPE_p_FILE</tt>.
</p>

<p>
If you need to perform any complex operations (like casting, dereferencing, etc. ) on the pointer consider creating some
helper functions. For example:
</p>

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

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

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

<p>
When working with C++ classes you should use the C++ style casts (<tt>static_cast</tt>, <tt>dynamic_cast</tt>).
This is especially important when you use a cast from a supertype to a subtype; in this
case only <tt>dynamic_cast</tt> is guaranteed to work reliably.
</p>

<H3><a name="com_structures"></a>17.4.6 Structures</H3>


<p>
A C structure will in most cases work as you would expect. For example,
</p>

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

</pre></div>

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

<div class="code"><pre>
Dim v
Set v = CreateObject("example.Vector")
v.x = 3.5
v.y = 7.2
Dim x, y
x = v.x
y = v.y
</pre></div>

<p>
Similar access is provided for unions and the public data members of C++ classes.
In fact structures are handled in exactly the same way as C++ classes. More details
about how SWIG handles C++ classes is provided in the next section.
</p>


<H3><a name="com_classes"></a>17.4.7 C++ classes</H3>


<p>
C++ classes are wrapped as COM interfaces. Additionally if a class is not abstract and has
a default (possibly implicit) constructor then a class definition and a class factory
are also generated. For example, if you have this class,
</p>

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

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

<div class="code"><pre>
Dim l
Set l = CreateObject("example.List")
l.insert("Ale")
l.insert("Stout")
l.insert("Lager")
Dim item
item = l.get(2)
Dim length
length = l.length
</pre></div>

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

<p>
Static class members can be accessed in two ways. Let us consider the following
class:
</p>

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

<p>
You can access <tt>Spam</tt>'s static members just like you would access any non-static members:
</p>

<div class="code">
<pre>
Dim Spam
Set Spam = CreateObject("example.Spam")
Spam.foo()
Dim bar
bar = Spam.bar
</pre>
</div>

<p>
In some circumstances it might be necessary to access <tt>Spam</tt>'s static members without
having an instance of <tt>Spam</tt>. This could be because <tt>Spam</tt> is an abstract class
or because creating it has some side effects. In this case you can use <tt>Spam</tt>'s static
members in the following way:
</p>

<div class="code">
<pre>
Dim example
Set example = CreateObject("example.example")
example.Spam.foo()
Dim bar
bar = example.Spam.bar
</pre>
</div>

<p>
The code above uses the module class object <tt>example</tt> and the class object <tt>example.Spam</tt>.
As was shown in the previous sections the module class object can be used for accessing global
functions and variables. The class object serves the same purpose but for static functions and
static variables of the class <tt>Spam</tt>. Please note that neither creating the module class object
nor creating the class object has any side effects. You should also note that SWIG does not provide any
synchronization of access for static functions and variables (or in fact for any other global/member
functions/variable). If you plan to create a multi-threaded program you should ensure synchronization
either within the wrapped C/C++ code or in the target language.
</p>

<H3><a name="com_inheritance"></a>17.4.8 C++ inheritance</H3>


<p>
SWIG's COM module currently only supports single inheritance. While it might be possible
to support multiple inheritance it would greatly increase the complexity of the code
generator and also of the generated code. If your C++ class has more than one superclass
then all but the first one will be ignored. If this is not what you want you can use
<tt>%feature("ignore")</tt> for the unwanted base classes.
</p>

<p>
SWIG generates a class hierarchy which mirrors that of the C++ code. Therefore,
if you have code like this
</p>

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

class Bar : public Foo {
...
};

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

<p>
you can use an instance of <tt>Bar</tt> as argument to <tt>spam</tt>:
</p>

<div class="code">
<pre>
Dim example, b
Set example = CreateInstance("example.example")
Set b = CreateInstance("example.Bar")
example.spam(b)
</pre>
</div>


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


<p>
COM expects all complex objects to be passed by pointer. Therefore if you define
your function in any of these ways:
</p>

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

<p>
COM will wrap the functions as if they would accept pointers to <tt>Foo</tt>.
Naturally in the case of <tt>spam3</tt> there is a difference in semantics
i.e. all changes made by the function will be done on a copy of the passed
object, just as you would expect in C++.
</p>

<p>
All of these functions are called in the same way:
</p>

<div class="code">
<pre>
Dim example, f

Set example = CreateObject("example.example")
Set f = CreateObject("example.Foo")
example.spam1(f)
example.spam2(f)
example.spam3(f)
example.spam4(f)
</pre>
</div>

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

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

<p>
then all three functions will return a pointer to some <tt>Foo</tt> object.
Since the third function (spam7) returns a value, newly allocated memory is used 
to hold the result and a pointer is returned (the generated COM code will free this
memory when the object is no longer needed, that is when its reference count reaches 0).
</p>

<H4><a name="com_null_pointers"></a>17.4.9.1 Null pointers</H4>


<p>
Null values may be passed to C/C++ functions when pointer parameters are expected. Also
if a C/C++ function returns NULL a null return value is returned by the wrapper.
You should not pass null to functions expecting a reference - in this case the
function call will fail with an E_INVALIDARG error.
</p>

<H3><a name="com_overloaded_functions"></a>17.4.10 C++ overloaded functions</H3>


<p>
Unfortunately COM does not support overloading functions (including constructors). Thus all
functions with the same name except for the first one will be ignored. If this is not what
you want you will need to either <a href="SWIG.html#SWIG_rename_ignore">rename or ignore</a>
some of the methods. For example:
</p>

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

<p>
or
</p>

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


<H3><a name="com_default_arguments"></a>17.4.11 C++ default arguments</H3>


<p>
In SWIG a function with a default argument is wrapped by generating an additional function for each argument
that is defaulted. However since COM does not support function overloading the additional functions
will be ignored. You can change this behavior using the <tt>%rename</tt> directive:
</p>

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

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


<H3><a name="com_namespaces"></a>17.4.12 C++ namespaces</H3>


<p>
SWIG is aware of C++ namespaces, but namespace names do not appear in
the module nor do namespaces result in a module that is broken up into
submodules or packages.  For example, if you have a file like this,
</p>

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

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

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

<div class="code">
<pre>
Dim example, f, v, y

Set example = CreateObject("example.example")
f = example.fact(3)
Set v = CreateObject("example.Vector")
v.x = 3.4
y = v.y
</pre>
</div>

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

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

namespace Foo {
    int spam();
}

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

<p>
If you have more than one namespace and you want to keep their
symbols separate, consider wrapping them as separate SWIG modules.
</p>

<H3><a name="com_constructors"></a>17.4.13 Constructors</H3>


<p>
COM has no specific support for constructors. Thus constructors are wrapped by SWIG's COM
module as methods inside of the class object. For example if you have the following definition:
</p>

<div class="code">
<pre>
class Vector {
public:
  double x, y;
  Vector(double a_x, double a_y): x(a_x), y(a_y) {}
};
</pre>
</div>

<p>
you can use the constructor in the following way:
</p>

<div class="code">
<pre>
Dim example, v

Set example = CreateObject("example.example")
Set v = example.Vector.new_Vector(1.42, 10)
</pre>
</div>

<p>
Remember that COM does not support method overloading and therefore if there are multiple
constructors that you would like to use then you will need to rename some of them.
</p>

<p>
If your class has a default constructor then you can also use an alternate way of creating
objects. In this case you can use the following code:
</p>

<div class="code">
<pre>
Dim v

Set v = CreateObject("example.Vector")
</pre>
</div>

<p>
Obviously there is no way to use this syntax for calling a constructor that expects to
receive parameters.
</p>

<H3><a name="com_templates"></a>17.4.14 C++ templates</H3>


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

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

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

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

<p>
In Basic:
</p>

<div class="code">
<pre>
Dim example, p, first, second

Set example = CreateObject("example.example")
Set p = example.pairii.new_pairii(3, 4)
first = p.first
second = p.second
</pre>
</div>

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

<H3><a name="com_smart_pointers"></a>17.4.15 C++ Smart Pointers</H3>


<p>
TODO
</p>


<H2><a name="com_further_details"></a>17.5 Further details on COM wrapping</H2>


<p>
The previous sections were meant as a quick start guide for wrapping C/C++ code as
COM objects. For users wanting to have a better understanding of how things work
beneath the surface this section provides some more details.
</p>

<H3><a name="com_classes_and_interfaces"></a>17.5.1 Classes and interfaces</H3>


<p>
There is no direct COM counterpart to a C++ class. COM defines two entities - the
interface which is comparable to a 'pure virtual' class, and the COM class which
is an implementation of one or more interfaces. There is no hierarchy of COM classes
but there is a hierarchy of interfaces. For each C++ class SWIG creates an interface
containing declarations of public functions and property getters and setters. If the
C++ class derives from a superclass then this relationship is preserved for their
corresponding interfaces (but as was stated before only single inheritance is supported).
The definition of a COM class serves the purpose of providing a way to locate a class's
factory object. Therefore the COM class is defined only when the class is not abstract
and has a default constructor. The following example shows two C++ classes
</p>

<div class="code">
<pre>
class A {
public:
  virtual int foo(A *) = 0;
};

class B : public A {
public:
  int foo(A *) { return 0; }
  int bar() { return 0; }
};
</pre>
</div>

<p>
and their corresponding definitions in the generated IDL file:
</p>

<div class="code">
<pre>
[ ... ]
interface IA : IDispatch {
  HRESULT foo(A *arg1, [ retval, out ] int *SWIG_result);
};

[ ... ]
interface IB : IA {
  HRESULT bar([ retval, out ] int *SWIG_result);
};

[ ... ]
coclass BImpl {
  interface IB;
  interface ISWIGWrappedObject;
};
</pre>
</div>

<p>
Some notable things above are the use of <tt>IDispatch</tt> as the base interface,
the use of <tt>HRESULT</tt> as return value along with the wrapping of the real return
value as an <tt>out</tt> parameter, and the <tt>ISWIGWrappedObject</tt> interface.
They will be described in later subsections.
</p>

<H3><a name="com_module_class"></a>17.5.2 Module class and class objects</H3>


<p>
Since COM does not support global functions and variables the module class is used as
a workaround. The name of the module class is the same as the name of the module itself.
There may be multiple objects of the module class but all of them will work on the
same data - your module's global variables. SWIG does not provide any synchronization
and therefore if you plan to use global variables from multiple threads you will need
to take care of multithreading issues either in the C/C++ code or in the target language.
</p>

<p>
Class objects serve a very similar purpose as the module class with regard to static
member functions and variables. Note: They should not be confused with what COM calls
'class objects' which is just another name for class factories.
Technically static functions and variables could be
a part of the module class and the class objects created by SWIG serve only the purpose of creating
a logical namespace layout. Class objects can be accessed as read-only properties
of the module class, e.g. if you have the following class:
</p>

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

class A {
public:
  static int func(void) { return 15; }
};
</pre>
</div>

<p>
then SWIG will define definitions in the IDL file similar to these:
</p>

<div class="code">
<pre>
[ ... ]
interface IAStatic : IDispatch {
  HRESULT func([ retval, out ] int *SWIG_result);
};

[ ... ]
interface Iexample : IDispatch {
  [ propget ]
  HRESULT A([ retval, out ] IAStatic **SWIG_result);
}
</pre>
</div>

<p>
The code can then be used in the following way:
</p>

<div class="code">
<pre>
Dim example

Set example = CreateObject("example.example")
Print example.A.func()
</pre>
</div>

<p>
The same considerations apply for class objects as for the module class object. Even though
there might be several objects for the class <tt>A</tt> defined above they will all be
accessing the same static variables. Please note that currently you cannot directly create
a class object (e.g. using <tt>CreateObject</tt> in Basic) and need to use the module
class. There is no good reason for it other than that it has not yet been implemented.
</p>

<H3><a name="com_guids"></a>17.5.3 GUID handling</H3>


<p>
COM uses 128-bit identifiers called GUIDs (or UUIDs) for uniquely identifying classes, interfaces
and type libraries. Ideally you should generate CLSIDs (class GUIDs) and IIDs (interface GUIDs)
for each wrapped class and change them each time that you make an incompatible change to a
class's public interface. Since this is a time consuming process you can delegate some of this
work to SWIG.
</p>

<p>
You can specify a CLSID and an IID for each class using the <tt>%feature</tt> directive:
</p>

<div class="code">
<pre>
%feature("iid"="12345678-1234-1234-1234-000000000000") A;
%feature("clsid"="12345678-1234-1234-1234-000000000001") A;
</pre>
</div>

<p>
For the module class you can define the CLSID and IID as part of the module directive:
</p>

<div class="code">
<pre>
%module(moduleiid="12345678-1234-1234-1234-000000000002", moduleclsid="12345678-1234-1234-1234-000000000003") example
</pre>
</div>

<p>
Finally there is also a GUID (called TLBID) for the type library which is the COM description of your
whole module. You can customize it in this way:
</p>

<div class="code">
<pre>
%module(tlbid="12345678-1234-1234-1234-000000000004") example
</pre>
</div>

<p>
If you do not want to provide all of the above GUIDs you can offload some work to SWIG. To do this
you can define a 'master' GUID which will serve as a seed value for automatically generating GUIDs:
</p>

<div class="code">
<pre>
%module(masterguid="12345678-1234-1234-1234-000000000005") example
</pre>
</div>

<p>
When SWIG wraps a class for which no IID or CLSID has been specified it will concatenate the
binary representation of the master GUID, the module name, the class name and a suffix
specifying whether the GUID is generated for a class, interface or type library. Then it
will compute the SHA-1 hash of this string and use the resulting bits for generating a GUID
(this process has been described in RFC 4122 as variant 5 of the generation algorithm).
</p>

<p>
This process reduces the number of GUIDs you need to generate to only one - the master GUID.
You can generate it in various ways, e.g. by using guidgen from Microsoft's SDK or
one of many GUID/UUID generators available on the web. The procedure described above ensures
that your GUIDs will remain the same when you re-run SWIG. If for some reason you need to
change the public interface of some of your wrapped classes you can do this either by
manually specifying their new CLSIDs and IIDs, or by changing the master GUID.
</p>

<H3><a name="com_class_factories"></a>17.5.4 Class factories and aggregation</H3>


<p>
SWIG creates class factories for all defined COM classes. This means that class factories
are created for proxies of non-abstract classes with a default destructor and also for the
module class.
</p>

<p>
SWIG supports COM aggregation for proxy classes. The module class currently cannot be
aggregated.
</p>

<H3><a name="com_hresult"></a>17.5.5 IDispatch and HRESULT as return value</H3>


<p>
All interfaces generated by SWIG are dual interfaces - this means that they support
both early binding (sometimes called VTBL binding - used mostly by compiled languages)
and late binding (sometimes called 'name binding' - used in scripting languages) by
implementing the IDispatch interface. As a result the return values of all interface
functions need to be instances of HRESULT. This is used for reporting whether the
function call succeeded or failed (e.g. when the call is made remotely using DCOM).
The 'real' return value, if any, needs to be therefore transformed to an <tt>out</tt> parameter
of the function. If you use the generated COM object from a scripting language then most
likely you will not see any difference - you will be able to use the function just as
it would be returning a value. However if you use a compiled language (like C, C++ or Delphi)
then you will need to explicitly provide a pointer to the address where the return value
is to be stored.
</p>

<H3><a name="com_iswigwrappedobject"></a>17.5.6 ISWIGWrappedObject interface</H3>


<p>
Every COM object created by SWIG implements the interface <tt>ISWIGWrappedObject</tt> with
the interface ID <tt>{1a3a5cc8-9a61-4681-ae9c-d04293f35734}</tt>. This interface has one
method (apart from the methods present in the <tt>IUnknown</tt> interface):
</p>

<div class="code">
<pre>
void * getCPtr();
</pre>
</div>

<p>
This method is used for accessing the COM object's underlying C/C++ object. The
<tt>ISWIGWrappedObject</tt> interface may change in a future version of SWIG
(speaking precisely it may be replaced by another interface with another IID)
so you should not rely on its presence. However it may be useful for debugging
purposes.
</p>

<H3><a name="com_memory"></a>17.5.7 Memory management</H3>


<p>
Every COM proxy object keeps a count of references. If this reference count
reaches zero then the proxy object is unused and can be deallocated. SWIG takes
care of allocating and deallocating memory for proxy objects. By default
the underlying C/C++ object is left intact when the proxy is destroyed. The
exceptions are when the proxy object has been created using the class factory
(this includes <tt>CreateObject</tt> in Basic and the <tt>CoCreateInstance</tt>
Win32 API call), using a constructor from the class object or using a function
marked as <tt>%newobject</tt>. In these cases the proxy 'owns' the underlying
C/C++ object which is destroyed together with the proxy. C++ objects are
deallocated using <tt>delete</tt>; this means that the destructor
will be called, just as it would be called in C++.
</p>

<H3><a name="com_exception"></a>17.5.8 Exceptions</H3>


<p>
For now if a C++ exception is thrown the function returns with the error
code <tt>E_ABORT</tt>. The handling of this error code depends on the
language that you are using. For example VBScript will exit with an error
by default; if you need to handle errors more gracefully you can use
code similar to this:
</p>

<div class="code">
<pre>
Rem Prevent aborting the script
On Error Resume Next

Rem Call method that might throw an exception
example.callDangerousMethod()

If Err.Number <> 0 Then
  Rem Handle error
End If
</pre>
</div>

<p>
You can customize the exception handling process by modifying the
<tt>throws</tt> typemap.
</p>

<H2><a name="com_customization"></a>17.6 Customization features</H2>


<H3><a name="com_typemaps"></a>17.6.1 Typemaps</H3>


<p>
The COM module uses four typemaps for wrapping types. These are
<tt>comtype</tt> (the type that should be used in the generated
IDL file ), <tt>ctype</tt> (the corresponding C/C++ type),
<tt>in</tt> (used when handling a parameter to a function - basically
it needs to convert from the type specified by <tt>ctype</tt> to
the C/C++ type expected by the function) and <tt>out</tt> (used
when handling return values). You can also use standard SWIG typemaps
such as <tt>freearg</tt> and <tt>argout</tt>.
</p>

<p>
A good example how the typemaps work is the <tt>char *</tt>
typemap. Its <tt>comtype</tt> is <tt>BSTR</tt> - the de facto standard
string type in COM, essentially an array of wide characters with
a four byte length prefix. The corresponding <tt>ctype</tt> is
<tt>WCHAR *</tt>. The typemaps for handling <tt>char *</tt> strings could
look like this:
</p>

<div class="code">
<pre>
%typemap(ctype) char *, char[], char[ANY] "WCHAR *"
%typemap(comtype) char *, char[], char[ANY] "BSTR"

%typemap(in) char *, char[], char[ANY] {
  if ($input) {
    int SWIG_len = WideCharToMultiByte(CP_ACP, 0, $input, -1, 0, 0, 0, 0);
    $1 = ($1_ltype) malloc(SWIG_len);
    WideCharToMultiByte(CP_ACP, 0, $input, -1, (char *) $1, SWIG_len, 0, 0);
  }
}

%typemap(freearg) char *, char[], char[ANY] {
  if ($input) {
    free($1);
  }
}

%typemap(out) char *, char[], char[ANY] %{
  if ($1) {
    int SWIG_len = MultiByteToWideChar(CP_ACP, 0, (char *) $1, -1, 0, 0);
    WCHAR *SWIG_res = (WCHAR *) CoTaskMemAlloc((SWIG_len + 2) * sizeof(WCHAR));
    /* First 4 bytes contain length in bytes */
    *((unsigned int *) SWIG_res) = (unsigned int) (SWIG_len - 1) * sizeof(WCHAR);
    MultiByteToWideChar(CP_ACP, 0, (char *) $1, -1, SWIG_res + 2, SWIG_len);
    $result = SWIG_res + 2;
  }
%}
</pre>
</div>

</body>
</html>