Direct memory access

Travis Oliphant oliphant.travis at
Wed Mar 7 21:25:35 CET 2007

Collin Stocks wrote:
> Does anyone know how to directly handle memory using python?
> I want to be able, for example, to copy the actual contents of a memory 
> address, or set the actual contents of a memory address.

This kind of thing is generally not what Python is used for, so it's not 
really easy to do.

Writing to arbitrary memory areas is an easy way to cause segmentation 
violations which Python and its extensions try to make segmentation 
violations (memory violations) as near impossible as they can.

If you really need to do this then you can use ctypes to do it.

Let N be the number of bytes you want to access, then

import ctypes
g = (ctypes.c_char*N).from_address(addr)

g is now a settable sequence of bytes that you can read and write to 
using strings.

g[0]  # read the first byte
g[1]  # read the second byte

g[0] = '\x24' # set the first byte to hexadecimal 24


If you don't have permission to write to addr then you will get memory 
violations and your program will crash if you try to read from or write 
to the resulting sequence.


More information about the Python-list mailing list