Need a notification that DLL is shutting down before getting DLL_PROCESS_DETACH

382 Views Asked by At

We have a DLL built in Visual Studio using C++11. Our DLL has a fixed API at this point, and it includes an open and close function (among others). We allow our users to open and close multiple times without closing the app. Inside our DLL, we are using a 3rd party library that has not only an open and close, but also an initialize and uninitialize.

The open and close map closely to our open and close, but the initialize and uninitialize are to be called only once each, at start up and shut down. I am able to call their initialize only once from our open function, but I cannot find a place to call the uninitialize, as I don't know when the app is about to be shut down. The most logical place to call it from is in the DllMain function under the DLL_PROCESS_DETACH, and while this works when running under debug, when I run under release we get an unhandled exception, "Fatal program exit requested." If I just give up and remove their uninitialize call, I still get an unhandled exception and in neither case do I cleanly shut down.

Is there any way to get a signal/notification that the application is shutting down prior to DLL_PROCESS_DETACH?

1

There are 1 best solutions below

0
On

There is no such notification inside a DLL. DllMain() is the only place the DLL knows what is going on. Its lpReserved parameter will tell you whether DLL_PROCESS_DETACH is due to a call to FreeLibrary() or not. That is about all you get from the system.

Either debug the code to find out why the exception is occurring, and then fix it or catch it.

Or, keep track of how many times your DLL's open() and close() are called. Call the lib's initialize() on the 1st open(), and call the lib's uninitialize() on the last matching close(). And then make sure the app calls your close() on shutdown.

Or, add your own initialize() and uninitialize() to your DLL to call the lib's corresponding functions, and then make the app call your initialize() at startup/open and your uninitialize() at shutdown.