views:

65

answers:

3

I have a dll which is actually a com service that is registered and then being loaded by another .exe process. I would like when the user exit from the .exe to execute some resource closing steps from within my dll before it is too late. I tried to intercept the DLLPROCESSDETACH or DLLTHREADDETACH from the DllMain of my DLL but it seems when it gets there, it is already too late as the threads started by my DLL (which I need to execute the closing steps) have already stopped?! Of course, I do not control the .exe code otherwise I would have invoked from there a call to execute those clean closing steps before it exits. I can only work on the DLL itself. It doesn't seem the DllCanUnloadNow or the DllUnregisterServer get called either.

Has any one a work around for this situation?

Thank you many in advance for any inputs.

+1  A: 

You can write a static object with dtor, the dtor will be called once the service is exiting and the cruntime is about to unload.

struct CDtorMyDll
{
  ~CDtorMyDll
  {
    // do cleanup stuff here.
  }
};

static CDtorMyDll dtorMyDll;
Shay Erlichmen
Wouldn't work, as they are called from `DLLPROCESSDETACH`
MSalters
A: 

Silly question: Why do you need to run down the threads you created? They're going to be destroyed anyway and all the resources used by the process cleaned up.

Having said that, if your object really is a COM object, you can add code to your DllCanUnloadNow call to detect if there are any outstanding instances of your objects and if there are none, clean up your resources. This won't work if the process leaks references to your objects or doesn't call CoUninitialize, but if the process hosting your object follows the rules, it gets you an opportunity to clean up before the process shuts down.

Larry Osterman
A: 

Trying to do this via DllMain or a destructor will result in weirdness, because the DLL itself will be in a weird state (read all of Raymond Chen's articles about DllMain and you'll see).

The real solution here is to have explicit MyDllInitialize() and MyDllTeardown() functions that are called before the process exits.

Paul Betts