Created
June 19, 2018 05:27
-
-
Save SuoXC/1ec2f31f0bd2416318c8bfc480b46677 to your computer and use it in GitHub Desktop.
python ctypes to dict, recursively
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
| 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