c# - 读取进程内存不起作用给出错误尝试读取或写入受保护的内存
问题描述
我目前正在尝试让我的 readProcessMemory 函数工作,但我不断收到错误“ Attempted to read or write protected memory. This is often an indication that other memory is corrupt
。” 我一直在努力解决它,但我就是做不到。我已阅读其他论坛和主题来解决问题,但没有任何效果。我一直试图在测试程序中读取一个整数变量以确保它有效,但我最初在记事本和突击立方体上尝试过,但没有任何效果。
这是我的代码:
const int PROCESS_VM_READ = 0x0010;
#region imports
[DllImport("kernel32.dll")]
public static extern IntPtr OpenProcess(int dwDesiredAccess, bool bInheritHandle, int dwProcessId);
[DllImport("kernel32.dll")]
public static extern bool ReadProcessMemory(int hProcess,
Int64 lpBaseAddress, byte[] lpBuffer, UInt64 dwSize, out IntPtr lpNumberOfBytesRead);
[DllImport("kernel32.dll", SetLastError = true)]
static extern bool WriteProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, byte[] lpBuffer, UInt32 dwSize, out IntPtr lpNumberOfBytesWritten);
#endregion
private static IntPtr processHandle;
static void Main(string[] args)
{
Console.WriteLine(readInt(0x003CECC4));
Console.Read();
}
static byte[] readMemory(int memoryAddress, int bytesToRead)
{
Process process = Process.GetProcessesByName("test")[0];
processHandle = OpenProcess(PROCESS_VM_READ, false, process.Id);
IntPtr bytesRead;
byte[] buffer = new byte[bytesToRead];
ReadProcessMemory((int)processHandle, memoryAddress, buffer, (uint)buffer.Length, out bytesRead);
return buffer;
}
static int readInt(int memoryAddress)
{
return BitConverter.ToInt32(readMemory(memoryAddress, 4), 0);
}
}
}
解决方案
您必须以管理员身份运行程序,右键单击您的项目并选择“添加新项目”并选择清单文件。将asInvoker改为requireAdministrator,重新编译执行即可。
其次,您使用的是动态地址,如果您重新启动游戏它将不再工作,您将尝试读取未初始化的或只是随机内存。您应该使用动态方法来解析指针链并获取模块的基地址,而不是硬编码动态地址。
推荐阅读
- python - 使用 PIL 在图片上绘制特殊文本
- javascript - 如何将鼠标移动存储在数组中
- presto - 从数组中删除空值
- javascript - 如何在使用材质 UI makeStyles 时默认导出与Router 做出反应
- javascript - 从 html 标签打印属性
- python - 使用 pyMongo 在 Flask 中获取 MongoDB 数据
- r - 如何为每行数据创建单独的 R 降价段落/页面
- docker - Docker 多阶段构建缓存
- laravel - 如何使用 eloquent 和 laravel 使用 softdeletes 创建子查询
- arrays - Firestore 更新后仅获取一次文档