17 SWIG and COM

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.

17.1 Overview

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

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.

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

17.2 Preliminaries

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.

17.2.1 Running SWIG

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

/* File: example.i */
%module test
%{
#include "stuff.h"
%}
int fact(int n);

To build a COM module, run SWIG using the -com option :

%swig -com example.i

If building C++, add the -c++ option:

$ swig -c++ -com example.i

This will generate four files: example_wrap.c (or example_wrap.cxx), example.idl, example.def and example.rc. The first file contains code responsible for object layout, reference counting, etc. The example.idl 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.

The name of the wrapper file is derived from the name of the input file. For example, if the input file is example.i, the name of the wrapper file is example_wrap.c. To change this, you can use the -o option. It is also possible to change the output directory that the COM files are generated into using -outdir.

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

17.2.2 Additional Commandline Options

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

swig -com -help 
COM specific options
-namespace <name> set name to be used as the prefix of your classes' IDispatch names (e.g. for use with CreateObject in Basic)

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

17.2.3 Compiling a dynamic module

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

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

and for MinGW under Linux (using WIDL):

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

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

Build instructions for some other toolchains may be found on this page of the SWIG Wiki.

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

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

$ regsvr32 example.dll

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

$ regsvr32 /u example.dll

17.2.4 Using your module

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

Dim example
Set example = CreateObject("example.example")

The variable example now contains a reference to an object of the module class 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.

17.3 Practical Tips for Using and Testing the COM Module

17.3.1 Overview

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.

17.3.2 Compilation using various toolchains

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

17.3.2.1 Microsoft Visual Studio

$ 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

17.3.2.2 MinGW/Cygwin on Windows (using MIDL)

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.

$ 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

17.3.2.3 Digital Mars C++ on Windows (using MIDL)

$ 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

17.3.2.4 MinGW on Linux (using WIDL)

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.

$ 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

17.3.2.5 WineGCC

$ 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

You are welcome to add instructions for other toolchains to this page.

17.3.3 Testing environment (Windows/Cygwin and MIDL)

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

17.3.3.1 Using Cygwin's default C/C++ compiler

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

# 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 

Now you can use the following options for configure:

$ . ./vars_cygwin.sh
$ ./configure --with-com-cc=gcc --with-com-cxx=g++ --with-com-idl=midl --with-com-rc=windres

17.3.3.2 Using Microsoft Visual C++

You can use the following script to set up the paths needed by MSVC and MIDL (you may need to adjust the actual paths):

# 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

Now you can use the following options for configure:

$ . ./vars_vc.sh
$ ./configure --with-com-cc=cl --with-com-cxx=cl --with-com-idl=midl --with-com-rc=rc

17.3.3.3 Using Digital Mars C++

You can use the following script to set up the paths needed by DMC and MIDL (you may need to adjust the actual paths):

# 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

Now you can use the following options for configure:

$ . ./vars_dmc.sh
$ ./configure --with-com-cc=dmc --with-com-cxx=dmc --with-com-idl=midl --with-com-rc=rcc

17.3.4 Testing environment (Unix/Linux, using WINE and possibly MinGW)

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.

17.3.5 Winegcc

If you have WINE installed properly you can just use the following options for configure:

$ ./configure --with-com-runtool=wine --with-com-cc=winegcc --with-com-cxx=wineg++ --with-com-idl=widl --with-com-rc=wrc

17.3.6 MinGW

For MinGW use the following options:

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

17.3.6.1 VBScript run tests on Linux

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:

#!/bin/sh

wine c:\\windows\\system32\\cscript.exe $*

You can then add the following option to configure:

--with-com-cscript=cscript

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.

17.4 A tour of basic C/C++ wrapping

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

17.4.1 Global functions

In COM there are no global functions and therefore SWIG uses a workaround. It defines a class known as the module class 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:

%module example
int fact(int n);

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

Dim example
Set example = CreateObject("example.example")
Print example.fact(4)

17.4.2 Global variables

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:

// SWIG interface file with global variables
%module example
...
%inline %{
extern int My_variable;
extern double density;
%}
...

Can be used in the following way:

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

If a variable is declared as const, 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 %immutable directive. For example:

%{
extern char *path;
%}
%immutable;
extern char *path;
%mutable;

The %immutable directive stays in effect until it is explicitly disabled or cleared using %mutable. See the Creating read-only variables section for further details.

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

%{
extern char *path;
%}
%immutable path;
...
extern char *path;      // Read-only (due to %immutable)

17.4.3 Constants

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

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

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

17.4.4 Enumerations

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:

%module example

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

int func(Beverage arg);

You can use the wrapped code like this:

Dim example, res

Set example = CreateObject("example.example")
res = example.func(example.PILSNER)

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

%module example

class MyClass {
public:
  enum Beverage { ALE, LAGER=10, STOUT, PILSNER, PILZ=PILSNER };
  static Beverage bev;
};

The resulting COM object can be used as follows:

Dim example, res

Set example = CreateObject("example.example")
example.MyClass.bev = example.MyClass.PILSNER

17.4.5 Pointers

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

%module example

FILE *fopen(const char *filename, const char *mode);
int fputs(const char *, FILE *);
int fclose(FILE *);

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

Dim example
Dim f

Set example = CreateObject("example.example")
Set f = example.fopen("junk","w")
example.fputs("Hello World", f)
example.fclose(f)

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

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

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

%inline %{
/* C-style cast */
Bar *FooToBar(Foo *f) {
   return (Bar *) f;
}

/* C++-style cast */
Foo *BarToFoo(Bar *b) {
   return dynamic_cast<Foo*>(b);
}

Foo *IncrFoo(Foo *f, int i) {
    return f+i;
}
%}

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

17.4.6 Structures

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

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

is used as follows:

Dim v
Set v = CreateObject("example.Vector")
v.x = 3.5
v.y = 7.2
Dim x, y
x = v.x
y = v.y

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.

17.4.7 C++ classes

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,

class List {
public:
  List();
  ~List();
  int  search(char *item);
  void insert(char *item);
  void remove(char *item);
  char *get(int n);
  int  length;
};

you can use it in Basic like this:

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

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

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

class Spam {
public:
   static void foo();
   static int bar;
};

You can access Spam's static members just like you would access any non-static members:

Dim Spam
Set Spam = CreateObject("example.Spam")
Spam.foo()
Dim bar
bar = Spam.bar

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

Dim example
Set example = CreateObject("example.example")
example.Spam.foo()
Dim bar
bar = example.Spam.bar

The code above uses the module class object example and the class object example.Spam. 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 Spam. 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.

17.4.8 C++ inheritance

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 %feature("ignore") for the unwanted base classes.

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

class Foo {
...
};

class Bar : public Foo {
...
};

void spam(Foo *f);

you can use an instance of Bar as argument to spam:

Dim example, b
Set example = CreateInstance("example.example")
Set b = CreateInstance("example.Bar")
example.spam(b)

17.4.9 Pointers, references, arrays and pass by value

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

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

COM will wrap the functions as if they would accept pointers to Foo. Naturally in the case of spam3 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++.

All of these functions are called in the same way:

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)

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

Foo *spam5();
Foo &spam6();
Foo  spam7();

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

17.4.9.1 Null pointers

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.

17.4.10 C++ overloaded functions

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 rename or ignore some of the methods. For example:

%rename(spam_ushort) spam(unsigned short);
...
void spam(int);    
void spam(unsigned short);   // Now renamed to spam_ushort

or

%ignore spam(unsigned short);
...
void spam(int);    
void spam(unsigned short);   // Ignored

17.4.11 C++ default arguments

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 %rename directive:

%module example

%rename(defaults2) defaults(double);
%rename(defaults3) defaults();
void defaults(double d=10.0, int i=0);

17.4.12 C++ namespaces

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,

%module example

namespace foo {
   int fact(int n);
   struct Vector {
       double x,y,z;
   };
};

it works in Basic as follows:

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

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

%rename(Bar_spam) Bar::spam;

namespace Foo {
    int spam();
}

namespace Bar {
    int spam();
}

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

17.4.13 Constructors

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:

class Vector {
public:
  double x, y;
  Vector(double a_x, double a_y): x(a_x), y(a_y) {}
};

you can use the constructor in the following way:

Dim example, v

Set example = CreateObject("example.example")
Set v = example.Vector.new_Vector(1.42, 10)

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.

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:

Dim v

Set v = CreateObject("example.Vector")

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

17.4.14 C++ templates

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

%module example
%{
#include <utility>
%}

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

%template(pairii) pair<int,int>;

In Basic:

Dim example, p, first, second

Set example = CreateObject("example.example")
Set p = example.pairii.new_pairii(3, 4)
first = p.first
second = p.second

Obviously, there is more to template wrapping than shown in this example. More details can be found in the SWIG and C++ chapter.

17.4.15 C++ Smart Pointers

TODO

17.5 Further details on COM wrapping

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.

17.5.1 Classes and interfaces

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

class A {
public:
  virtual int foo(A *) = 0;
};

class B : public A {
public:
  int foo(A *) { return 0; }
  int bar() { return 0; }
};

and their corresponding definitions in the generated IDL file:

[ ... ]
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;
};

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

17.5.2 Module class and class objects

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.

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:

%module example

class A {
public:
  static int func(void) { return 15; }
};

then SWIG will define definitions in the IDL file similar to these:

[ ... ]
interface IAStatic : IDispatch {
  HRESULT func([ retval, out ] int *SWIG_result);
};

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

The code can then be used in the following way:

Dim example

Set example = CreateObject("example.example")
Print example.A.func()

The same considerations apply for class objects as for the module class object. Even though there might be several objects for the class A 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 CreateObject 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.

17.5.3 GUID handling

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.

You can specify a CLSID and an IID for each class using the %feature directive:

%feature("iid"="12345678-1234-1234-1234-000000000000") A;
%feature("clsid"="12345678-1234-1234-1234-000000000001") A;

For the module class you can define the CLSID and IID as part of the module directive:

%module(moduleiid="12345678-1234-1234-1234-000000000002", moduleclsid="12345678-1234-1234-1234-000000000003") example

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:

%module(tlbid="12345678-1234-1234-1234-000000000004") example

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:

%module(masterguid="12345678-1234-1234-1234-000000000005") example

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

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.

17.5.4 Class factories and aggregation

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.

SWIG supports COM aggregation for proxy classes. The module class currently cannot be aggregated.

17.5.5 IDispatch and HRESULT as return value

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

17.5.6 ISWIGWrappedObject interface

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

void * getCPtr();

This method is used for accessing the COM object's underlying C/C++ object. The ISWIGWrappedObject 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.

17.5.7 Memory management

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 CreateObject in Basic and the CoCreateInstance Win32 API call), using a constructor from the class object or using a function marked as %newobject. In these cases the proxy 'owns' the underlying C/C++ object which is destroyed together with the proxy. C++ objects are deallocated using delete; this means that the destructor will be called, just as it would be called in C++.

17.5.8 Exceptions

For now if a C++ exception is thrown the function returns with the error code E_ABORT. 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:

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

You can customize the exception handling process by modifying the throws typemap.

17.6 Customization features

17.6.1 Typemaps

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

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

%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;
  }
%}