COM Programming

From D Wiki
Revision as of 09:37, 8 May 2016 by Giles Bathgate (talk | contribs) (Added content regarding COM programming from 'Win32 DLLs in D')
Jump to: navigation, search

COM interfaces are all derived from std.c.windows.com.IUnknown.


Many Windows API interfaces are in terms of COM (Common Object Model) objects (also called OLE or ActiveX objects). A COM object is an object who's first field is a pointer to a vtbl[], and the first 3 entries in that vtbl[] are for QueryInterface(), AddRef(), and Release().

For understanding COM, Kraig Brockshmidt's Inside OLE is an indispensible resource.

COM objects are analogous to D interfaces. Any COM object can be expressed as a D interface, and every D object with an interface X can be exposed as a COM object X. This means that D is compatible with COM objects implemented in other languages.

While not strictly necessary, the Phobos library provides an Object useful as a super class for all D COM objects, called ComObject. ComObject provides a default implementation for QueryInterface(), AddRef(), and Release().

Windows COM objects use the Windows calling convention, which is not the default for D, so COM functions need to have the attribute extern (Windows).

So, to write a COM object:

import std.c.windows.com;

class MyCOMobject : ComObject
{
    extern (Windows):
	...
}

The sample code includes an example COM client program and server DLL.