COM Fundamentals
COM Fundamentals
COM (Component Object Model) is Microsoft's binary standard for inter-component communication. It enables language-independent, location-transparent object creation and method invocation.
Core Concepts
- Interface: A contract — a set of related methods. Interfaces are immutable once published. Every COM object implements at least
IUnknown(withQueryInterface,AddRef,Release). - CLSID: A 128-bit GUID that uniquely identifies a COM class. Registered in
HKEY_CLASSES_ROOT\CLSID. - ProgID: A human-readable name for a COM class (e.g.,
ADODB.Connection). Mapped to a CLSID in the registry. - IDispatch: The interface for late-bound (Automation) access. VBScript and JScript use IDispatch exclusively.
- Type Library: A binary file (
.tlb) describing the interfaces, methods, and properties of a COM component. Used for early binding in VB6 and C++.
Object Creation
' Late binding (uses ProgID → CLSID lookup → IDispatch)
Set obj = CreateObject("Scripting.FileSystemObject")
' Early binding in VB6 (requires reference to type library)
Dim fso As New Scripting.FileSystemObject
COM Object Lifecycle
COM uses reference counting for memory management:
CoCreateInstancecreates the object. Reference count = 1.- Each assignment calls
AddRef. Count goes up. - Setting a reference to
NothingcallsRelease. Count goes down. - When count reaches 0, the object destroys itself.
Set obj = CreateObject("ADODB.Connection") ' Ref count = 1
Set obj2 = obj ' Ref count = 2
Set obj = Nothing ' Ref count = 1
Set obj2 = Nothing ' Ref count = 0, object destroyed
Threading Models
| Model | Description | Use Case |
|---|---|---|
| Single-Threaded | All calls on the main thread | Legacy components |
| Apartment (STA) | Each thread has its own apartment | UI components, VB6 (default) |
| Free (MTA) | Any thread can call any object | Performance-critical C++ components |
| Both | Works in STA or MTA | Flexible components |