.dll 的搜索顺序

来源:互联网 发布:什么是逻辑回归 知乎 编辑:程序博客网 时间:2024/05/21 15:06

《Windows 核心编程(第5版)》P522 

19.2.3 运行可执行模块:

由于导入段只包含 DLL 的名称,不包含 DLL 的路径,因此加载程序必须在用户的磁盘上搜索 DLL。下面是加载程序的搜索顺序:

(1) 包含可执行文件的路径;

(2) Windows 的系统目录,该目录通过 GetSystemDirectory 得到; 

(3) 16 位的系统目录,即 Windows 目录中的 system 子目录; 

(4) Windows 目录,该目录可通过 GetWindowsDirectory 得到;

(5) 进程的当前目录;

(6) PATH 环境变量中所列出的目录。

 

测试环境: Win7U + VS2008SP1 

上面顺序中的路径分别理解为:

【1】 VS2008生成的测试用 .exe 文件所在目录;

【2】 C:/Windows/system32; 

【3】 C:/Windows/system; 

【4】 C:/Windows; 

【5】 VS2008 中工程文件所在目录(.vcproj 文件所在目录,即工程默认路径); 

【6】 PATH 环境变量中所列出任一目录。 

 

经过测试,搜索顺序是从【1】到【6】的优先级。

 

P.S.: 以前听说环境变量设置后无须重启系统就能生效,在测试的过程中发现并不是这样的。


----[2011.08.12 更新]----

SetDllDirectory Function

The SetDllDirectory function affects all subsequent calls to the LoadLibrary and LoadLibraryEx functions. It also effectively disables safe DLL search mode while the specified directory is in the search path.

After calling SetDllDirectory, the standard DLL search path is:

1. The directory from which the application loaded.

2. The directory specified by the lpPathName parameter.(注:lpPathName是SetDllDirectory的参数。)

3. The system directory. Use the GetSystemDirectory function to get the path of this directory. The name of this directory is System32.

4. The 16-bit system directory. There is no function that obtains the path of this directory, but it is searched. The name of this directory is System.

5. The Windows directory. Use the GetWindowsDirectory function to get the path of this directory.

6. The directories that are listed in the PATH environment variable.

Each time the SetDllDirectory function is called, it replaces the directory specified in the previous SetDllDirectory call. To specify more than one directory, use the AddDllDirectory function and call LoadLibraryEx with LOAD_LIBRARY_SEARCH_USER_DIRS.

To revert to the standard search path used by LoadLibrary and LoadLibraryEx, call SetDllDirectory with NULL. This also restores safe DLL search mode based on the SafeDllSearchMode registry value.

To compile an application that uses this function, define _WIN32_WINNT as 0x0502 or later. For more information, see Using the Windows Headers.

原创粉丝点击