首页 > 解决方案 > 读取进程内存不起作用给出错误尝试读取或写入受保护的内存

问题描述

我目前正在尝试让我的 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);
        }    

    }
}

标签: c#readprocessmemory

解决方案


您必须以管理员身份运行程序,右键单击您的项目并选择“添加新项目”并选择清单文件。将asInvoker改为requireAdministrator,重新编译执行即可。

其次,您使用的是动态地址,如果您重新启动游戏它将不再工作,您将尝试读取未初始化的或只是随机内存。您应该使用动态方法来解析指针链并获取模块的基地址,而不是硬编码动态地址。


推荐阅读