Difference between revisions of "COM Programming"

From D Wiki
Jump to: navigation, search
(Added content regarding COM programming from 'Win32 DLLs in D')
Line 5: Line 5:
  
 
For understanding COM, Kraig Brockshmidt's [http://www.amazon.com/exec/obidos/ASIN/1556158432/classicempire Inside OLE] is an indispensible resource.
 
For understanding COM, Kraig Brockshmidt's [http://www.amazon.com/exec/obidos/ASIN/1556158432/classicempire Inside OLE] is an indispensible resource.
 +
 +
==Exporting==
 +
 +
To create objects in D that can be consumed by COM applications the following should be used.
  
 
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.
 
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.
Line 25: Line 29:
  
 
The sample code includes an example COM client program and server DLL.
 
The sample code includes an example COM client program and server DLL.
 +
 +
==Importing==
 +
 +
<syntaxhighlight lang="D">
 +
void main()
 +
{
 +
  CoInitialize(null);
 +
 +
  CoCreateInstance(...);
 +
}
 +
</syntaxhighlight>
  
 
[[Category:HowTo]]
 
[[Category:HowTo]]

Revision as of 10:58, 14 May 2016

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.

Exporting

To create objects in D that can be consumed by COM applications the following should be used.

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.

Importing

void main()
{
   CoInitialize(null);

   CoCreateInstance(...);
}