blob: 00ea22634478e0ebdef26bc8dd147974802ef8a5 [file] [log] [blame]
<!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>