The IUnknown Interface
COM allows different programming languages to communicate with each other via the universal language of computers: ones and zeroes.
It does that primarily through a single interface–from which all other interfaces flow–the IUnknown Interface. The IUknown Interface contains three methods:
AddRef
Release
QueryInterface
COM Objects Self-Destruct
To understand the purpose of the first two IUnknown methods, you need to know a little bit about how COM cleans up after itself (i.e., how it manages memory).
Let me explain.
A COM object keeps track of the number of variables that references it. Every time a new VBA variable references an object, the object's internal reference count goes up by one. When the variable goes out of scope or is explicitly set to Nothing, the object's internal reference count goes down by one. When the internal reference count reaches zero, the COM object is responsible for cleaning up after itself.
This is a very brief overview of COM's reference-counting memory management system, but it's important to understand for the .AddRef
and .Release
methods to make any sense.
AddRef
The .AddRef
method is responsible for incrementing the object's reference count.
As a VBA developer, you don't call the .AddRef
method directly. Rather, VBA does that itself behind the scenes. When you call CreateObject()
or GetObject()
or Set ... = New ...
or Set ... = ...
or reference a variable declared As New
, then VBA calls .AddRef
on your behalf.
Release
The .Release
method is responsible for decrementing the object's reference count.
As a VBA developer, you don't call the .Release
method directly, either. VBA calls .Release
for you whenever you Set ... = Nothing
or the object variable goes out of scope.
It is the COM object's responsibility to destroy itself when a call to .Release
brings the internal reference count down to zero.
QueryInterface
The .QueryInterface
method is a directory into the rest of the COM object.
It provides the calling code with the means to find the methods and properties that make the object useful. Because COM is a binary standard, the steps to get to these methods and properties involve multiple memory pointers. The good news for you as a VBA developer is that the VBA language takes care of all those messy details.
UPDATE [2022-03-08]: Inserted the word "VBA" into the phrase "Every time a new VBA variable references an object" to clarify that this is a feature of VBA itself, as other languages (such as C++) are responsible for calling .AddRef
and .Release
explicitly. (h/t Ben Clothier)