是否可以将 dll 固定在内存中以防止卸载?
Windows 中是否有某种方法可以防止通过 FreeLibrary 卸载我们的 dll?即在进程的生命周期中将其“固定”在内存中?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我知道这是一个旧线程,但有一种“正确”的方法可以做到这一点:
使用
GET_MODULE_HANDLE_EX_FLAG_PIN
标志调用GetModuleHandleEx
。来自 MSDN:
以防万一其他人发现此线程...
I know it's an old thread, but there is a 'proper' way to do this:
Call
GetModuleHandleEx
with theGET_MODULE_HANDLE_EX_FLAG_PIN
flag.From MSDN:
Just in case anyone else finds this thread...
是的。在该 DLL 上调用 LoadLibrary()。这将增加内部引用计数。 FreeLibrary() 仅在 DLL 的内部引用计数降至零时才卸载该 DLL。如果您使用 LoadLibrary 而从不使用 FreeLibrary,则 DLL 将在进程的生命周期内卡在内存中。
如果您遇到这样的情况:有人在您的 DLL 上调用 FreeLibrary() 并导致它在您仍在使用它时从内存中删除,那么您可能遇到了错误 - 对谁拥有该 DLL 存在分歧或误解,并且负责释放它。这个错误应该被修复,而不是通过 LoadLibrary hack 来解决。
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.
MSVC 有“延迟加载 DLL”选项(至少在 VC 2005+ 中)并支持“延迟加载 DLL 卸载”。可能还值得研究一下这些设置,确保不支持卸载。
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.