Basic COM   «Prev 

In-process COM servers: DllCanUnloadNow

How DllCanUnloadNow is implemented

Conceptually, implementing DllCanUnloadNow is simple: Just check the global server-lock counter and each reference counter in each interface within each COM object. For convenience, many developers keep track of all outstanding objects using a global variable. Let's call this g_objcnt.
Whenever a new object is created, g_objcnt is incremented either in IClassFactory::CreateInstance or in the constructor of the C++ class that implements the new COM object. Recall that in IUnknown::Release, we check to see if the reference count goes to 0. If it is 0, we often delete the C++ class, effectively deleting the COM object.
We now decrement g_objcnt either in Release or in the destructor of the C++ class.
g_objcnt acts as a counter for active COM objects. It is incremented in the context of IClassFactory::CreateInstance when a new COM object is created, and it is decremented when the COM object is destroyed. DllCanUnloadNow can now check g_objcnt along with the server-lock count to determine if the server can be unloaded. Following is a typical implementation of DllCanUnloadNow.

//Global Reference Counters
ULONG g_server_locks = 0;
ULONG g_objcnt = 0;

STDAPI DllCanUnloadNow() {
   if (g_server_locks == 0 && g_objcnt == 0) 
         return TRUE;
   return FALSE;