C++ – Windows: Changing the DLL search order for an Exe

cdllexewindows

I have a C++ Exe in an application directory which contains the DLLs used by it. Now, for some testing purpose I need to modify an existing DLL and use that instead of the original one. But in order to not modify the existing installation I cannot backup the existing DLL and replace it with the modified one or move the existing one elsewhere. I also cannot change the Exe. The 2 DLLs need to exist side by side. The only change should be that the Exe should transparently load the modified DLL which is in some other folder rather than the existing DLL which is in the same folder as the Exe. Is there some elegant way of doing it?

I looked at some MSDN articles but could not find a way of doing this. The solution should work on Windows XP and up.

Best Answer

Windows will load at most one version of each DLL name per process. If it loads a DLL listed in HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion\Windows\AppInit_DLLs, it won't load a similarly-named DLL later. But in AppInit_DLLs you can list a DLL with an explicit path, overriding the normal LoadLibrary() order.

Hence, temporarily put your test DLL in AppInit_DLLs and it will override any other DLL with the same name.