WriteProcessMemory and ReadProcessMemory are Windows API functions that allow you to read and write to the memory of another process. These functions are useful for debugging and testing purposes, as well as for creating programs that need to manipulate the memory of other processes.
To use WriteProcessMemory and ReadProcessMemory in Delphi, you will need to include the Windows unit in your program and call the functions as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
uses Windows; var ProcessHandle: THandle; Address: Pointer; Buffer: array[0..1023] of Byte; BytesWritten: SIZE_T; begin ProcessHandle = OpenProcess(PROCESS_ALL_ACCESS, False, 12345); if ProcessHandle = 0 then raise Exception.Create(‘Cannot open process’); Address := VirtualAllocEx(ProcessHandle, nil, 1024, MEM_COMMIT, PAGE_EXECUTE_READWRITE); if Address = nil then raise Exception.Create(‘Cannot allocate memory in process’); FillChar(Buffer, 1024, 0); WriteProcessMemory(ProcessHandle, Address, @Buffer, 1024, BytesWritten); ... end; |
In this example, OpenProcess is used to obtain a handle to the process with the specified process ID (12345 in this case). VirtualAllocEx is then used to allocate memory in the process, and WriteProcessMemory is called to write to that memory.
To read from the process’s memory, you can use ReadProcessMemory in a similar way
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
uses Windows; var ProcessHandle: THandle; Address: Pointer; Buffer: array[0..1023] of Byte; BytesRead: SIZE_T; begin ProcessHandle = OpenProcess(PROCESS_ALL_ACCESS, False, 12345); if ProcessHandle = 0 then raise Exception.Create(‘Cannot open process’); Address = VirtualAllocEx(ProcessHandle, nil, 1024, MEM_COMMIT, PAGE_EXECUTE_READWRITE); if Address = nil then raise Exception.Create(‘Cannot allocate memory in process’); ReadProcessMemory(ProcessHandle, Address, @Buffer, 1024, BytesRead); //Buffer now contains the data read from the process’s memory ... end; |
You should be aware that using WriteProcessMemory and ReadProcessMemory can be dangerous, as it allows you to manipulate the memory of another process in potentially harmful ways. Use these functions with caution and only when necessary.
Leave a Reply