如何判断Windows模块句柄是否仍然有效? [英] How can I tell if a Windows module handle is still valid?

查看:773
本文介绍了如何判断Windows模块句柄是否仍然有效?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以卸载模块,那么如何确定该模块是否仍在内存中?我有一个从GetModuleHandle获取的句柄.当我尝试对其调用GetHandleInformation时,看到错误0xc0000008-指定了无效的HANDLE."这是在没有将其卸载之前发生的.

A module can be unloaded, so how can I tell for sure if it is still in memory? I have a handle to it, obtained from GetModuleHandle. When I tried calling GetHandleInformation on it I see error 0xc0000008 - "An invalid HANDLE was specified." This happened before it could have been unloaded.

推荐答案

术语句柄"在这里有点重载-Win32 API中许多不同类的对象称为句柄".

The term "handle" is a bit overloaded here - lots of different classes of objects in the Win32 API are called "Handles".

GetHandleInformation用于处理内核对象(文件,注册表项,互斥对象等)的句柄.

GetHandleInformation is used for handles to kernel objects - files, registry keys, mutexes, etc.

由GetModuleHandle返回的HMODULE由加载程序使用,并且不是实际的内核对象,因此GetHandleInformation失败.不过,在GetHandleInformation中获得的两个标志都对HMODULE没有意义.

The HMODULE returned by GetModuleHandle is used by the loader and is not an actual kernel object, hence GetHandleInformation fails. Neither of the flags you get in GetHandleInformation makes sense for HMODULE though.

如果要检查HMODULE是否仍在内存中加载,则可以只调用GetModuleHandle-此API应该足够快才能调用多次.但是,GetModuleHandle的结果在返回时可能是无效的-另一个线程可能调用了FreeLibrary.最好确保DLL确实保持加载状态.您可以自己调用LoadLibrary或调用GetModuleHandleEx来执行此操作,这将增加DLL的引用计数.

If you want to check if the HMODULE is still loaded in memory, you can just call GetModuleHandle - this API should be quick enough to call many times. However, the result of GetModuleHandle can be invalid the moment it returns - another thread could have called FreeLibrary. It is better to ensure that the DLL does stay loaded. You can do this by calling LoadLibrary yourself, or by calling GetModuleHandleEx which will increment the reference count of the DLL.

这篇关于如何判断Windows模块句柄是否仍然有效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆