Question : Writing directly to memory.

I just spent an hour trying to find this on Google. So you guys really are my last resort :)

Is it possible to read and write directly to a memory address using Python? And if it is possible, how?


Thanks.

Answer : Writing directly to memory.

You'll need to use ctypes (http://starship.python.net/crew/theller/ctypes/) to drive the Win32 API.  Below is an example that uses ReadProcessMemory to read another process's memory.  There's an equivalent WriteProcessMemory for going the other way.

from ctypes import *
from ctypes.wintypes import *

OpenProcess = windll.kernel32.OpenProcess
ReadProcessMemory = windll.kernel32.ReadProcessMemory
CloseHandle = windll.kernel32.CloseHandle

PROCESS_ALL_ACCESS = 0x1F0FFF

pid = 4044   # I assume you have this from somewhere.
address = 0x1000000  # Likewise; for illustration I'll get the .exe header.

buffer = c_char_p("The data goes here")
bufferSize = len(buffer.value)
bytesRead = c_ulong(0)

processHandle = OpenProcess(PROCESS_ALL_ACCESS, False, pid)
if ReadProcessMemory(processHandle, address, buffer, bufferSize, byref(bytesRead)):
    print "Success:", buffer
else:
    print "Failed."

CloseHandle(processHandle)
Random Solutions  
 
programming4us programming4us