【发布时间】:2021-03-12 08:22:11
【问题描述】:
我刚刚在 C# 中遇到了 DllImport 的奇怪行为,我无法解释。我想知道它是如何可能的以及我在哪里可以读到它。案例是通过 DllImport 可以调用并没有真正导出表单 dll 的函数。在我的情况下,它是 kernel32.dll 和函数 ZeroMemory(但具有复制/移动/填充内存这样的行为)。所以,我的代码:
[DllImport("kernel32", EntryPoint = "LoadLibraryW", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern IntPtr LoadLibrary(string libName);
[DllImport("kernel32.dll", CharSet = CharSet.Ansi, ExactSpelling = true, SetLastError = true)]
public static extern IntPtr GetProcAddress(IntPtr module, string procName);
//WTF???
[DllImport("kernel32.dll", SetLastError = true)]
public static extern bool ZeroMemory(IntPtr address, int size);
static void TestMemory()
{
IntPtr mem = Marshal.AllocHGlobal(100); //Allocate memory block of 100 bytes size
Marshal.WriteByte(mem, 55); //Write some value in the first byte
ZeroMemory(mem, 100); //Clearing block of memory
byte firstByte = Marshal.ReadByte(mem); //Read the first byte of memory block
Console.WriteLine(firstByte); //Output 0 (not 55) - ZeroMemory is working
//Getting address of ZeroMemory from kernel32.dll
IntPtr kernelHandle = LoadLibrary("kernel32.dll");
IntPtr address = GetProcAddress(kernelHandle, "ZeroMemory");
Console.WriteLine(address.ToString("X")); //Output 0 - Library kernel32.dll DOESN'T export function ZeroMemory!!!
//Testing GetProcAddress via getting address of some exported function
Console.WriteLine(GetProcAddress(kernelHandle, "AllocConsole").ToString("X")); //Output some address value - all is OK.
}
没有抛出 EntryPointNotFoundException - 代码工作正常。如果将 ZeroMemory 的名称更改为 ZeroMemory1 或类似的名称 - 将引发异常。但是在 kernel32.dll 的导出表中我们看到:
根本没有 ZeroMemory 功能! 如果我们查看msdn,我们会发现 ZeroMemory 只是 C++ 的 WinBase.h 头文件中的一个宏。我们看到的里面:
#define RtlMoveMemory memmove
#define RtlCopyMemory memcpy
#define RtlFillMemory(d,l,f) memset((d), (f), (l))
#define RtlZeroMemory(d,l) RtlFillMemory((d),(l),0)
#define MoveMemory RtlMoveMemory
#define CopyMemory RtlCopyMemory
#define FillMemory RtlFillMemory
#define ZeroMemory RtlZeroMemory
显然,在 C++ ZeroMemory 中实际上是通过 ntdll.dll 中的 RtlFillMemory 工作的。但它是在 C++ 中的!!!为什么它在 C# 中工作?在 DllImport 属性here 的官方文档中,我们可以阅读下一个:
作为最低要求,您必须提供 DLL 的名称 包含入口点。
但在这种情况下,kernel32.dll 无法连接 ZeroMemory 的入口点。到底是怎么回事??请帮忙。
【问题讨论】:
-
很明显,CLR 内置了很多 Windows API 知识。例如,您可以使用 P/Invoke API 调用,这些调用采用字符串,但仍然省略结尾的
A或W符号名称。如果这是另一个 CLR 试图提供帮助的案例,我不会感到惊讶(阅读:它正在做什么不透明)。 -
内部好像被重新映射了,见this: ".NET Framework 有特殊情况逻辑来保证MoveMemory、CopyMemory、FillMemory、ZeroMemory 正确映射到RtlMoveMemory、RtlCopyMemory、RtlFillMemory , 和 RtlZeroMemory 分别".
-
@dxiv 感谢您的链接!奇怪的是,这种情况没有记录在 .NET 文档中。特殊情况……嗯。
-
您可以在 clr.dll 中看到这里的 voodoo(很遗憾 .NET Framework 的那部分不是开源的):i.imgur.com/SQtTpMo.png
-
@dxiv - 你应该发布答案,另见:stackoverflow.com/questions/47014586/…
标签: c# .net winapi marshalling dllimport