COM handles this problem by shifting responsibility to the DLL. The DLL needs to implement and export a function named DllCanUnloadNow
. COM calls it occasionally, and if it returns true, the DLL may be unloaded.
So how does the function know? The DLL keeps track of how many objects it gives out through calls to DllGetClassObject
, and it knows how many of those objects are still alive. In Delphi's default COM DLL implementation, it maintains a global object count, much the way each object maintains its own reference count. See the implementation in ComServ.pas, for example.
You can employ the same technique. Track what your GetInterface
function gives out, and what's been released. Export another function so host programs can ask whether it's safe to unload your library.
An alternative would be to change your DLL into a real COM DLL