COM Fundamentals

FDN » COM/DCOM » 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 (with QueryInterface, 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:

  1. CoCreateInstance creates the object. Reference count = 1.
  2. Each assignment calls AddRef. Count goes up.
  3. Setting a reference to Nothing calls Release. Count goes down.
  4. 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

ModelDescriptionUse Case
Single-ThreadedAll calls on the main threadLegacy components
Apartment (STA)Each thread has its own apartmentUI components, VB6 (default)
Free (MTA)Any thread can call any objectPerformance-critical C++ components
BothWorks in STA or MTAFlexible components
« Developer Network Creating COM Components in VB ›