Changing Windows DLL load order? (load order, not search order)

前端 未结 4 1439
半阙折子戏
半阙折子戏 2021-02-07 11:15

Say I have one executable: app.exe

I use 2 different 3rd party DLLs in this executable: foo.dll bar.dll and the Application must l

相关标签:
4条回答
  • 2021-02-07 11:54

    If you don't link the import library (foo.lib & bar.lib), then the loader will not automatically load the DLLs upon startup and you can call LoadLibrary() whenever you want.

    On a side note, I wrote a handy little library for encapsulating loading DLLs on the fly without having to deal with LoadLibrary/GetProcAddress directly. You can read about it here.

    0 讨论(0)
  • 2021-02-07 12:02

    Here's an idea: How about marking them as "Delay Loaded dlls" in the linker options of app.exe?

    Delay-loading will allow you to link "statically" (i.e. without LoadLibrary() et.al) but will not load the DLL and do the linking until it's actually needed.

    If that is an option, then (assuming you can wait so long, i.e. do not access foo/bar dll functions before main()), you could, in main(), access a function (just fetch a function ptr or something) in foo.dll first, which would load it and bind all "statically" linked functions?

    (Maybe LoadLibrary() triggers the same link-when-needed procedure. Not sure. It would look cleaner in your code though.)

    0 讨论(0)
  • 2021-02-07 12:14

    Just add foo.dll to the import table of bar.dll, the OS loader will handle the rest.

    You should be able to do this without the source code for bar.dll, not sure if the editbin tool has such an option, but this is a fairly trivial edit to the PE file.

    You might instead be able to use the registry setting that preloads DLLs, but I wouldn't do that, you don't want foo.dll getting loaded into other processes that don't need it.

    0 讨论(0)
  • 2021-02-07 12:16

    What I haven't found out yet is how to influence this load order ...

    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).


    0 讨论(0)
提交回复
热议问题