How to dereference an address into an integer in python?

2.5k views Asked by At

I have an address like 0x6041f0. I know there's an integer sitting out there. In C, I would have simply done *(int *)0x6041f0 to get the integer value present at that address.

How to achieve the same in Python?

PS: I am writing a Python script that uses the gdb module. The actual program being debugged is in C++. As such a lot of low level manipulation is required.

1

There are 1 answers

0
James Mills On

Something like this:

$ python
Python 2.7.9 (default, Mar 19 2015, 22:32:11) 
[GCC 4.8.4] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from ctypes import *
>>> c_int_p = POINTER(c_int)
>>> x = c_int(4)
>>> cast(addressof(x), c_int_p).contents
c_int(4)

With that artbitrary address :)

>>> cast(0x6041f0, c_int_p)
<__main__.LP_c_int object at 0x7f44d06ce050>
>>> cast(0x6041f0, c_int_p).contents
Segmentation fault

See: ctypes for reference