When loading a DLL (either dynamically with LoadLibrary/Ex or statically) is it somehow possible to prevent Windows from using the PATH environment variable to look up the DLL/other DLLs the DLL to be loaded depends upon?
The docs I could find for the Dynamic-Link Library Search Order seem to imply there is no way to prevent PATH from being searched, but maybe I'm missing something?
The reason I am asking this is that we would like to have a fail-fast scenario, when a (statically) linked DLL is missing from the application folder but is possibly present (different version) on the PATH.
For dynamically loaded dlls: the easiest way to control which one is loaded is to not invoke the search logic. The search logic is only invoked if a partial path is supplied - provide a fully qualified path to the dll when calling LoadLibrary and the call will fail if the Dll doesn't exist in that location.
For statically loaded dlls: Dlls that are part of an assembly are searched for ONLY in WinSxS and the application's folder. So, create a "dummy" assembly to hold the dll. Which is as simple as creating a .manifest file with contents like this:
<!-- dummyassembly.manifest -->
<assembly manifestVersion="1.0">
<assemblyIdentity type="Win32" name="dummyassembly" version="1.0.0.0" processorArchitecture="x86"/>
<file name="thedll.dll"/>
</assembly>
Add this code to any project that needs to use the exact dll only:
#pragma comment(linker, "/manifestdependency:\"dummyassembly'"\
" processorArchitecture='*' version='1.0.0.0' type='win32'\"")
and it will fail to load if the dll doesn't exist in the same folder.
You could change the PATH environment variable from code before loading your dlls. And then possibly restore it afterwords.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With