本文介绍了更改Windows DLL加载顺序? (加载顺序,而不是搜索顺序)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个可执行文件: / code>,但这些DLL需要静态链接(C ++ DLL与 __ declspec(dllexport)),所以我调用 LoadLibrary 没有任何意义,因为excutable加载器已经调用它。)



这两个DLL不有任何依赖彼此,也就是说,它们的加载顺序是未定义的,只要我能告诉(和应该不相关)。 (两者的依赖性基本上只在标准的windows dll(kernel32,msvcrt等)



我现在有问题,我想控制这些DLLs,这是我希望foo.dll总是加载( DLL_PROCESS_ATTACH )之前bar.dll。



是否有可能告诉Windows DLL Loader在另一个之前加载一个DLL?



编辑:要检查DLL加载顺序,可以使用 DUMPBIN.exe 实用程序:(只需启动Visual Studio命令提示符)



编辑:根据 / ,NT加载程序会顺序地导入部分(这将导致独立 DLL按照它们在导入部分。)

  C:\path\to\program> dumpbin / IMPORTS app.exe | grep -i \.dll 
MSVCR80D.dll
KERNEL32.dll
OLEAUT32.dll
MSVCP80D.dll
foo.dll
bar.DLL



此输出表示MSVCR80D.dll(及其依赖)将首先加载,并且bar.DLL将最后加载。

$

> ...






(注释)



]:这意味着,例如kernel32.dll将首先加载,因为msvcr80d.dll将依赖于kernel32.dll。






我为此添加了一个理由:

The Microsoft MFC DLL in it's debug version has memory leak detection built in. (As far as I can tell, it's the same mechanism used by _CrtSetDbgFlag and related tools.)

The MFC debug DLL will dump all unfreed memory when it is unloaded. Now, if you have a second DLL in your process, that is independent of MFC, and this second DLL deallocates memory on DLL_PROCESS_DETACH, the MFC reporting mechanism will report false memory leaks, if the MFC DLL is unloaded before the other dll.

If one could make sure that the debug MFC DLL is loaded first / unloaded last of all independent DLLs, then all other DLLs would already have cleaned up after themselves and MFC wouldn't report false leaks.

解决方案

I have no clue why I hadn't tried this, but it seems the import section order of the resulting module does depend on the order in which the lib files are provided to the linker.

Configuration Properties -> Linker -> Additional Dependencies ...

The lib files listed here first are also first in the import section, meaning the loader will import these in order (modulo dependencies).

So, to answer that part: Just provide the lib files in the correct order to the linker.

Note: I have tried that on VS2005 and it appears to work. I don't know whether that is documented somewhere or if it changed in newer versions of VC++.


Update: While it worked back then, today I hit the case that the load order was not to be influenced by the linker command line order of the lib files. (Still) No clue why. (Still VS2005)

I have however managed to make it work by adding the problematic DLLs to the list of delay loaded DLLs (like in Macke's answer).


这篇关于更改Windows DLL加载顺序? (加载顺序,而不是搜索顺序)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 05:35