Created
July 2, 2013 15:37
-
-
Save tito/5910356 to your computer and use it in GitHub Desktop.
Exploration of ctypes to get C memory address from a ctypes object, and reuse the memory address to get back a ctypes object
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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