Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access memory address in python

My question is: How can I read the content of a memory address in python? example: ptr = id(7) I want to read the content of memory pointed by ptr. Thanks.

like image 317
Academia Avatar asked Nov 23 '11 23:11

Academia


People also ask

Can you access memory address in Python?

In Python, you don't generally use pointers to access memory unless you're interfacing with a C application. If that is what you need, have a look at the ctypes module for the accessor functions.

How do I find the memory address in Python?

We can get an address using the id() function. id() function gives the address of the particular object.

How does Python access memory?

The memory is taken from the Python private heap. Object domain: intended for allocating memory belonging to Python objects. The memory is taken from the Python private heap.

How do you find the memory location of a variable?

We can see the location of the memory address of that value with the id() function. Think of that long number as a storage jar. I can check the location of the value associated with peanut_butter by passing my variable to the id() function.


2 Answers

Have a look at ctypes.string_at. Here's an example. It dumps the raw data structure of a CPython integer.

from ctypes import string_at from sys import getsizeof  a = 0x7fff  print(string_at(id(a),getsizeof(a)).hex()) 

Output:

0200000000000000d00fbeaafe7f00000100000000000000ff7f0000 

Note that this works with the CPython implementation because id() happens to return the virtual memory address of a Python object, but this is not guaranteed by the Python language itself.

like image 148
Mark Tolonen Avatar answered Oct 06 '22 15:10

Mark Tolonen


In Python, you don't generally use pointers to access memory unless you're interfacing with a C application. If that is what you need, have a look at the ctypes module for the accessor functions.

like image 20
Raymond Hettinger Avatar answered Oct 06 '22 15:10

Raymond Hettinger