Skip to content

Instantly share code, notes, and snippets.

@mydreambei-ai
Last active July 7, 2016 02:05
Show Gist options
  • Select an option

  • Save mydreambei-ai/5a0a1e84fd46c8c51429a848d415b041 to your computer and use it in GitHub Desktop.

Select an option

Save mydreambei-ai/5a0a1e84fd46c8c51429a848d415b041 to your computer and use it in GitHub Desktop.
python read binary structure from file
from ctypes import *
libc = cdll.LoadLibrary("libc.so.6")
class POINT(Structure):
_fields_ = ("x", c_int), ("y", c_int)
f = open("test_structure", "w")
p = POINT(10, 20)
libc.write(f.fileno(), pointer(p), sizeof(POINT))
libc.close(f.fileno())
del f
f = open("test_structure", "rb")
p = POINT()
#use libc read
libc.read(f.fileno(), byref(p), sizeof(POINT))
print(p.x, p.y)
libc.close(f.fileno())
del f
f = open("test_structure", "rb")
import struct
# use struct module
x, y = struct.unpack("ii", f.read())
print(x, y)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment