tags:

views:

59

answers:

2

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?

+5  A: 

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.

dthorpe
Agreed. Call it about 60,000 times to be sure.
Hans Passant
Hell, call it a million times - "just to be sure."
JustBoo
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
A: 

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.

Greg Domjan