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?
-
2Generally, dlls are subservient to executable that loads them. If that executable decides it doesn't need the dll anymore and calls FreeLibrary, why would you want your dll to hang around further? In other words: why are you looking for a way to do this? – TheUndeadFish Aug 10 '10 at 23:49
3 Answers
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...

- 1,902
- 15
- 24
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.

- 35,318
- 5
- 75
- 119
-
4
-
1
-
Of course you will have to keep calling LoadLibrary while FreeLibrary is happening, you can't guarantee that they only try and free once. – Greg Domjan Aug 27 '10 at 21:43
-
1It appears that using the `GetModuleHandleEx()` function with the `GET_MODULE_HANDLE_EX_FLAG_PIN` flag from the Windows API (available Windows XP and Windows Server 2003) is much preferable over this idea of trying to increase the reference count. – Richard Chambers Mar 12 '18 at 15:20
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.

- 13,943
- 6
- 43
- 59