C#调用 kernel32.dll 在64位环境下异常

2025-03-06 13:35:20
推荐回答(1个)
回答1:

64位系统IntPtr的Size是8字节,而32位的是4字节
可能因为这个问题出现错误
需要更详细的情况,比如调用的返回值
搜索P.Invoke能找到很多平台调用(DLL)的资料

[DllImport("kernel32.dll", SetLastError = true)]
static extern bool ReadProcessMemory(
IntPtr hProcess,
IntPtr lpBaseAddress,
[Out] byte[] lpBuffer,
int dwSize,
out int lpNumberOfBytesRead
);

[DllImport("kernel32.dll", SetLastError = true)]
static extern bool ReadProcessMemory(
IntPtr hProcess,
IntPtr lpBaseAddress,
[Out, MarshalAs(UnmanagedType.AsAny)] object lpBuffer,
int dwSize,
out int lpNumberOfBytesRead
);

[DllImport("kernel32.dll", SetLastError = true)]
static extern bool ReadProcessMemory(
IntPtr hProcess,
IntPtr lpBaseAddress,
IntPtr lpBuffer,
int dwSize,
out int lpNumberOfBytesRead
);

//示例
public int ReadInt32(IntPtr hProcess, uint dwAddress)
{
byte[] buffer = new byte[4];
int bytesread;

Win32Api.ReadProcessMemory(hProcess, dwAddress, buffer, 4, out bytesread);
return BitConverter.ToInt32(buffer, 0);
}