URL1: http://technet.microsoft.com/zh-cn/library/ms885601
URL2: http://technet.microsoft.com/zh-cn/library/ms885202
BOOL FreeLibrary( HMODULE hLibModule);
本函数递减对已加载DLL模块的引用计数。如果引用计数为0,hLibModule句柄不再有效,模块从调用进程的地址空间中取消映射关系。
This function devrements the reference count of the loaded DLL module. When the reference count reaches zero, the module is unmapped from the address space of the calling process and the handle is no longer valid.
参数说明:hLibModule,[in] Handle to the loaded library module.
LoadLibrary(), LoadLibraryEx(), GetModuleHandle()三个函数返回该句柄。
返回值:成功,返回非0;失败返回0.
To get extended error information, call GetLastError()。
注意:
每个进程持有对其加载的library module的引用。LoadLibrary每被调用一次,引用计数增加。
Each process maintains a reference count for each loaded module. This reference count is incremented each time LoadLibrary is called and is decremented each time FreeLibrary is called.
A DLL module loaded at process initialization due to load-time dynamic linking as a reference count of one. This count is incremented if the same module is loaded by a call to LoadLibrary.
取消映射关系之前,如果DLL有DLLMain函数,系统允许DLL调用本身的DLLMain函数(参数:DLL_PROCESS_DETACH)使得其与进程分开。
Before unmapping a library module, the system enables the DLL to detach from the process by calling the DLL's DLLMain Function, if it has one, with the DLL_PROCESS_DETACH value. Doing so gives the DLL an opportunity to clean up resources allocated on behalf of the current process.
After the entry-point function returns, the library module is removed from the address space of the process.
在DllMain中调用FreeLibrary是不安全的。
It is not safe to call FreeLibrary from DLLMain. For more information, see the Remarks section in DllMain.
Calling FreeLibrary does ot affect other processes using the same library module.
---------------
下面我们来看为什么在DllMain中调用FreeLibrary是不安全的:
Do not call LoadLibrary in the entry-point function, because you might create dependency loops in the DLL loead order. This can cause a DLL to be used before the system executes its initialization code.Similary, do not call the FreeLibrary function in the entry-point function on detach, because this can cause a DLL to be used after the system executes its termination code.