0

I'm able to get the right address of an object in Python 3.

Using hex(id(Object))

class TestObject:
    myMemberData = 5

obj = TestObject()

#Using repr
print(repr(obj))

#Getting address manually!
address = hex(id(obj))
print(address)

#I'd like something like this:
#@address.myMemberData = 6

#OUTPUT:
<__main__.TestObject object at 0x7f32f3a7f160>
0x7f32f3a7f160

But now I need to be able to do the reverse. I want to be able to manipulate and get to the object at that specific address. So I can access and mutate it's member-data for example.

I have did some research and got this:

>>> from ctypes import string_at
>>> from sys import getsizeof
>>> from binascii import hexlify
>>> a = 0
>>> print(hexlify(string_at(id(a), getsizeof(a))))
b'bc0100000000000040cf9c00000000000000000000000000'
>>> a = 1
>>> print(hexlify(string_at(id(a), getsizeof(a))))
b'fc0200000000000040cf9c0000000000010000000000000001000000'
>>> a = 2
>>> print(hexlify(string_at(id(a), getsizeof(a))))
b'5c0000000000000040cf9c0000000000010000000000000002000000'
>>> a = 3
>>> print(hexlify(string_at(id(a), getsizeof(a))))
b'2f0000000000000040cf9c0000000000010000000000000003000000'
>>> 

I thought that was close, because you can see the 7'th LSB changing regarding to the value of variable a. However that still didn't gave me a solution to manipulate the member data of an object!

I also read about CTypes which seemed very interesting and close to what I want. But lacked a basic example of how to do what I want, if CTypes even can do it.

TL;DR If I'm able to get the address of an object, how would I use that address to manipulate the member-data of that object by using it's address?

O'Niel
  • 1,622
  • 1
  • 17
  • 35
  • 2
    Why do you need to do this? There almost certainly is a better way. – Bailey Parker Jan 22 '18 at 15:16
  • High level languages work hard to abstract away implementation details such as memory addresses. Consequently, it is hard to dig through that abstraction to get at the bare metal. If you're dead-set on doing this, I suggest switching to a language that doesn't try to abstract it away in the first place. – Kevin Jan 22 '18 at 15:18
  • This sounds like an [X-Y problem](https://en.wikipedia.org/wiki/XY_problem). What is the real problem you are trying to solve? – Mark Tolonen Jan 23 '18 at 17:18

0 Answers0