Using COM in Your Windows-Based Program
Using COM in Your Windows-Based Program
What Is a COM Interface?
In C++, the nearest equivalent to an interface is a pure virtual class—that is, a class that contains only pure virtual methods and no other members.
Initializing the COM Library
Each thread that uses a COM interface must make a separate call to this function.
1 | HRESULT CoInitializeEx(LPVOID pvReserved, DWORD dwCoInit); |
For every successful call to CoInitializeEx, you must call CoUninitialize before the thread exits.
1 | CoUninitialize(); |
Error Codes in COM
This produces the following numeric ranges:
Success codes: 0x0–0x7FFFFFFF.
Error codes: 0x80000000–0xFFFFFFFF.
1 | HRESULT hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE); |
Creating an Object in COM
In general, there are two ways to create a COM object:
The module that implements the object might provide a function specifically designed to create instances of that object.
1 | // Not an actual Windows function. |
The Open Dialog Box
1 |
|
Managing the Lifetime of an Object
Release is called only after you test the HRESULT for success.
Asking an Object for an Interface
You can think of QueryInterface as a language-independent version of the dynamic_cast keyword in C++.
1 | HRESULT QueryInterface(REFIID riid, void **ppvObject); |
Memory Allocation in COM
The CoTaskMemAlloc function allocates a block of memory.
The CoTaskMemFree function frees a block of memory that was allocated with CoTaskMemAlloc.
COM Coding Practices
This topic describes ways to make your COM code more effective and robust.
1 | The __uuidof Operator |
Error Handling in COM
With these rules in mind, here are four patterns for handling errors.
1 | Nested ifs |



