Is there some way in Windows to prevent unloading of our dll via FreeLibrary? I.e. to "pin" it in memory for the life of the process?
问题:
回答1:
Yes. Call LoadLibrary() on that DLL. That will increase the internal reference count. FreeLibrary() only unloads a DLL when its internal reference count drops to zero. If you LoadLibrary and never FreeLibrary, the DLL will be stuck in memory for the lifetime of your process.
If you're running into a situation where somebody is calling FreeLibrary() on your DLL and causing it to be removed from memory while you're still using it, you probably have a bug - a disagreement or misunderstanding about who owns the DLL and is responsible for releasing it. A bug that should be fixed rather than worked around by a LoadLibrary hack.
回答2:
I know it's an old thread, but there is a 'proper' way to do this:
Call GetModuleHandleEx
with the GET_MODULE_HANDLE_EX_FLAG_PIN
flag.
From MSDN:
The module stays loaded until the process is terminated, no matter how many times FreeLibrary is called.
Just in case anyone else finds this thread...
回答3:
MSVC has options (at least in VC 2005+) for "Delay loaded DLL" and supporting "Delay Loaded DLL Unload" It may be worth also looking into these settings, ensuring Unload is not supported.