读取进程内存不起作用给出错误尝试读取或写入受保护的内存

时间:2018-04-26 19:04:28

标签: c# readprocessmemory

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

    }
}

1 个答案:

答案 0 :(得分:0)

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

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