Created
May 8, 2017 12:47
-
-
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)
This file contains hidden or 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
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