Skip to content

Instantly share code, notes, and snippets.

@ivpusic
Forked from tito/pointer.py
Created July 2, 2013 18:39
Show Gist options
  • Save ivpusic/5911902 to your computer and use it in GitHub Desktop.
Save ivpusic/5911902 to your computer and use it in GitHub Desktop.
import ctypes
class Point(ctypes.Structure):
_fields_ = (
("x", ctypes.c_int),
("y", ctypes.c_int))
p1 = Point(23, 4)
print 'Original point is', (p1.x, p1.y)
addr = ctypes.addressof(p1)
print 'C address is', addr
# read the memory address as a pointer to a Point structure
p_p2 = ctypes.cast(addr, ctypes.POINTER(Point))
# access to the content directly, we don't need the pointer anymore.
p2 = p_p2.contents
# values of the casted/memory pointer should be the same :)
print 'Memory point is', (p2.x, p2.y)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment