Skip to content

Instantly share code, notes, and snippets.

@disconnect3d
Created May 8, 2017 12:47
Show Gist options
  • Save disconnect3d/ec5775630bccab3891cf2290b696a0c0 to your computer and use it in GitHub Desktop.
Save disconnect3d/ec5775630bccab3891cf2290b696a0c0 to your computer and use it in GitHub Desktop.
Example showing that ctypes might be tricky... (the bytes buffer gets garbage collected so we get weird results)
In [8]: import ctypes
...:
...:
...: class Foo(ctypes.LittleEndianStructure):
...: _fields_ = (('bar', ctypes.c_uint64),)
...:
...: def __str__(self):
...: return 'Foo .bar={}'.format(self.bar)
...:
...: @classmethod
...: def from_bytearray(cls, buf):
...: assert len(buf) == ctypes.sizeof(cls), 'Bytearray and structure size mismatch'
...: return ctypes.cast(bytes(buf), ctypes.POINTER(cls)).contents
...:
...:
...: f = Foo.from_bytearray(bytearray(8))
...: print(f)
...:
...: print(Foo.from_bytearray(bytearray(8)))
...:
...:
...:
Foo .bar=21474836480
Foo .bar=0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment