Skip to content

Instantly share code, notes, and snippets.

@skrungly
Last active October 23, 2018 22:51
Show Gist options
  • Save skrungly/be63b24a919c2966edfa6e5eb49cfd01 to your computer and use it in GitHub Desktop.
Save skrungly/be63b24a919c2966edfa6e5eb49cfd01 to your computer and use it in GitHub Desktop.
Memory Manipulation Utilities
import ctypes
def size_of(obj):
cls = type(obj)
return cls.__sizeof__(obj)
def mem_replace(target, source):
target_size = size_of(target)
source_size = size_of(source)
ctypes.memmove(
id(target),
id(source),
max(target_size, source_size)
)
def mem_switch(obj1, obj2):
dummy = object()
mem_replace(dummy, obj1)
mem_replace(obj1, obj2)
mem_replace(obj2, dummy)
def mem_read_bytes(addr, amount):
char_array = (ctypes.c_char * amount)
mem_bytes = char_array.from_address(addr)
return bytes(mem_bytes)
def mem_read_object(target):
data = mem_read_bytes(
id(target),
size_of(target)
)
return data
def mem_equal(obj1, obj2):
if obj1 is obj2:
return True
obj1_bytes = mem_read_object(obj1)
obj2_bytes = mem_read_object(obj2)
return obj1_bytes == obj2_bytes
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment