Skip to content

Instantly share code, notes, and snippets.

@pp4x
Created February 8, 2018 16:32
Show Gist options
  • Save pp4x/9b5671e36881543254ecf72436be0093 to your computer and use it in GitHub Desktop.
Save pp4x/9b5671e36881543254ecf72436be0093 to your computer and use it in GitHub Desktop.
C struct wrapper: this is what I believe to be simpler than ctypes
from struct import Struct
from recordtype import recordtype
def populate(value, mask):
mask = mask[-1]
if value:
return value
elif mask in 'bBhHiIlLqQfd':
return 0
elif mask in 'sp':
return ''
elif mask == '?':
return False
def encode(struct):
encoder = struct._struct
params = [populate(x, mask) for x, mask in zip(struct, struct._fieldTypes)]
return encoder.pack(*params)
def decode(struct, data):
decoder = struct._struct
values = decoder.unpack(data)
for x in zip(struct._fields, values):
setattr(struct, x[0], x[1])
def sizeof(struct):
return struct._struct.size
def create(name, description):
description = description.split(',')
fields = [field[:field.find(':')] for field in description]
typeList = [field[field.find(':') + 1:] for field in description]
types = ''.join(['@'] + typeList)
newType = recordtype(name, fields, default=None)
newType._struct = Struct(types)
newType._fieldTypes = typeList
newType.encode = encode
newType.decode = decode
newType.sizeof = sizeof
return newType
if __name__ == '__main__':
Point = create('Point', 'x:f,y:f')
print Point
p1 = Point(1, 2)
p2 = Point(0, 0)
print p1._asdict().values(), p2
p2.decode(p1.encode())
print p2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment