Skip to content

Instantly share code, notes, and snippets.

@SuoXC
Created June 19, 2018 05:27
Show Gist options
  • Select an option

  • Save SuoXC/1ec2f31f0bd2416318c8bfc480b46677 to your computer and use it in GitHub Desktop.

Select an option

Save SuoXC/1ec2f31f0bd2416318c8bfc480b46677 to your computer and use it in GitHub Desktop.
python ctypes to dict, recursively
def getdict(struct):
result = {}
if not hasattr(struct,'_fields_'):
return struct
for field, _ in struct._fields_:
value = getattr(struct, field)
# if the type is not a primitive and it evaluates to False ...
if (type(value) not in [int, float, bool]) and not bool(value):
# it's a null pointer
value = None
elif hasattr(value, "_length_") and hasattr(value, "_type_"):
# Probably an array
value = [getdict(v) for v in list(value)]
elif hasattr(value, "_fields_"):
# Probably another struct
value = getdict(value)
result[field] = value
return result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment