Is it possible to pin a dll in memory to prevent u

2019-05-02 11:27发布

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?

标签: c++ windows dll
3条回答
甜甜的少女心
2楼-- · 2019-05-02 12:07

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...

查看更多
Rolldiameter
3楼-- · 2019-05-02 12:12

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.

查看更多
兄弟一词,经得起流年.
4楼-- · 2019-05-02 12:20

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.

查看更多
登录 后发表回答