Does DllImport obey SafeDllSearchMode when searching for DLLs?
Let's say I have a typical unmanaged call I want to make in some DLL:
[DllImport("unmanaged.dll")]
static extern int SomeFuncion1(int pa开发者_高级运维rm);
Does the DllImportAttribute search for the DLL according to the SafeDllSearchMode setting in the registry? I couldn't find anything in MSDN that indicates if indeed the search order follows the "standard search order".
Yes, the P/Invoke marshaller just uses LoadLibrary(). Which observes the setting. It is unprovable that it actually does in a SO post, until you try it yourself, I concluded this by being pretty sure there is no reasonable alternative. LoadLibrary squarely belongs in the category of the 'hard' API functions.
Fwiw, it will never find that DLL with your [DllImport] declaration. Unmanaged DLLs just have a path, they don't have managed assembly properties like version, culture, pkt. If this is in fact a managed assembly with those properties then you load it with Assembly.Load(). But you'll have a hard time calling a static function, the CLR doesn't support that, every method must belong to a class.
Use Dumpbin.exe /exports on that DLL to find out what is actually getting exported from that DLL.
Oh well, I was impatient and answered this on my own, but Hans answered it in the meantime.
First, I created a test tool:
[DllImport("SomeDllThatDoesntExist.dll")]
public static extern void Test();
static void Main()
{
string currentWorkingDirectory = Directory.GetCurrentDirectory();
Console.WriteLine(currentWorkingDirectory);
Directory.SetCurrentDirectory("E:\\foobar");
currentWorkingDirectory = Directory.GetCurrentDirectory();
Console.WriteLine(currentWorkingDirectory);
// Call method in DLL we know doesn't exist.
Test();
}
Then I monitored it with Procmon, and the search path order on the Test()
call was:
- Executing directory
- System32 directory
- System directory (16 bit)
- Windows directory
- Current directory ("E:\foobar")
- All my $PATH directories
This shows it obeying the "safe" search order, as the Current Directory is #5 and not #2, as it would be if SafeDllSearchMode were disabled. Then I added the HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\SafeDllSearchMode
registry value and set it 1 (disabled), and ran my test tool again. The search path then was actually the same. I don't know if I messed up adding the registry key or not, but really the only important thing I wanted to know is if, by default, it was following the "safe" search order path - which means the current directory isn't #2 in the order.
精彩评论