从网上浏览到这个网页http://topic.okbase.net/201006/2010060410/3849330.html,从这里面发现几个知识点,特此整理:
主 题: 对于系统dll,LoadLibrary和GetModuleHandle效果是一样的?? 作 者: Nospam 回复次数: 1 发表时间: 2010-6-4 10:29:21 正文内容: HINSTANCE hInst = LoadLibrary("Kernel32.dll"); HINSTANCE hInst2=::GetModuleHandle("Kernel32.dll"); GetModuleHandle 还有个好处,不用FreeLibrary啥的 |
首先说系统DLL,所谓的系统DLL,即是操作系统本身安装时自带的DLL文件,此类DLL与普通的DLL的区别主要在是由系统程序或服务调用的,当然这并不是说普通的用户程序不能调用系统DLL;就我个人理解而言,上面这位作者的本意应该是“对于已被系统服务或进程调用起来的系统DLL,LoadLibrary和GetModuleHandle效果是一样的”;
再说LoadLibrary和GetModuleHandle两个API,通过网络查询可以知道,LoadLibrary用来动态载入DLL文件,而GetModuleHandle则是用来得到指定模块的句柄,其实从这个两个API的定义就可以看出区别,LoadLibrary用来将一个普通的DLL文件载入到系统进程中,使之成为一个系统模块;而GetModuleHandle则是需要在DLL这个模块已经存在的情况下才能得到他的句柄;关于GetModuleHandle 的一些解释,从这个网页中即可看出 http://msdn.microsoft.com/en-us/library/windows/desktop/ms683199(v=vs.85).aspx,现摘录一下几个内容做为分析用:
Retrieves a module handle for the specified module. The module must have been loaded by the calling process.
意思是获得指定模块的模块句柄;此模块必须已经被调用进程载入; 这句话其实已经给出了提示,想获得一个已经被载入调用进程的模块的句柄。
对于GetModuleHandle有下面的说明:
This function must be used carefully in a multithreaded application. There is no guarantee that the module handle remains valid between the time this function returns the handle and the time it is used. For example, suppose that a thread retrieves a module handle, but before it uses the handle, a second thread frees the module. If the system loads another module, it could reuse the module handle that was recently freed. Therefore, the first thread would have a handle to a different module than the one intended.
重点就是说这个API在多线程下必须小心使用,因为他只是获得此模块的相关句柄,但并不会对此句柄的引用计数产生影响,相当于一个简单的get操作!
再回到上文作者提到的主题,按照我的理解,GetModuleHandle和LoadLibrary从本质上说不是一个原理,但是可以实现同样的效果,就是都能获得指定模块的句柄,但是区别还是很大的!
如果大家有什么意见,可以留言,将会非常感谢!