Which DLL is [DllImport] loading?

不羁岁月 提交于 2019-12-05 09:02:32

The File System Redirector will be kicking in:

The %windir%\System32 directory is reserved for 64-bit applications. Most DLL file names were not changed when 64-bit versions of the DLLs were created, so 32-bit versions of the DLLs are stored in a different directory. WOW64 hides this difference by using a file system redirector.

In most cases, whenever a 32-bit application attempts to access %windir%\System32, the access is redirected to %windir%\SysWOW64.

So even though the process thinks it loaded the DLL from System32, it probably loaded from SysWOW64 And yes, the numbers are the wrong way around from what you'd expect.

The actual source code behind DllImport is here:

https://github.com/gbarnett/shared-source-cli-2.0/blob/master/clr/src/vm/dllimport.cpp

As you can see, it first tries to find de unmanaged library in .Net's internal cache.

If that fails, but an absolute path is specified, it loads the library with that path.

If no absolute path is specified it looks in these locations:

1) The folder containing the manifest file of the assembly that contains the DllImport.

2) The folder specified in Assembly.CodeBase.

3) All the places where LoadLibraryExW looks.

If all that fails, it tries to interpret it as "filename, assemblyname".

Then it adds the library to its internal cache.

DLLImport searches through the following paths:

  1. Currently loaded DLLs (if it's already loaded, there is no need to search the file)
  2. The directory of the executable module for the current process
  3. The current directory.
  4. "System" directory. (i.e. c:\Windows\System32)
  5. The "Windows" directory. (i.e. c:\Windows)
  6. The directories listed in the PATH environment variable.

You want to read this - LoadLibrary function and, from that, you also want to read this Dynamic Link Library Search Order.

Note - these relate to a native Win32 API, but it is the one that's used by the [DllImport] attribute.

The file is possibly not showing in Explorer because you need to have Show All Files switched on - many common [DllImport] directives (e.g. kernel32) are targeting Win32 DLLs, which are classed as operating system files and are therefore hidden by default.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!