Created
July 23, 2023 07:37
-
-
Save BDeliers/a6d1d4090bb9d52a779bf4355c2e9dca to your computer and use it in GitHub Desktop.
Parse an enum from a C file to a C array associating enum index to its corresponding string
This file contains 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
#!/usr/bin/python3 | |
""" | |
Parse an enum from a C file to a C array associating enum index to its corresponding string | |
BDeliers, July 2023 | |
""" | |
import re | |
if __name__ == "__main__": | |
INPATH = input("Enter the source file path: ") | |
OUTPATH = input("Enter the output file path: ") | |
with open(INPATH, 'r') as file: | |
enum = file.read() | |
file.close() | |
enum = enum.replace(' ', '') | |
enum_list = re.findall(r"\w{3,}=(?:(?:0x[0-9A-Fa-f]{2,8})|(?:\d+))", enum) | |
max = 0 | |
for elt in enum_list: | |
tmp = elt.split('=') | |
if tmp[1].find("0x") > -1: | |
tmp = int(tmp[1], 16) | |
else: | |
tmp = int(tmp[1]) | |
if (tmp > max): | |
max = tmp | |
outlist = [0] * (max+1) | |
for elt in enum_list: | |
tmp = elt.split('=') | |
val = 0 | |
if tmp[1].find("0x") > -1: | |
val = int(tmp[1], 16) | |
else: | |
val = int(tmp[1]) | |
outlist[val] = tmp[0] | |
outstring = "const char* enum_array[] = {\n" | |
for i in range(0, len(outlist)): | |
if (outlist[i] != 0): | |
outstring += "\"{}\",".format(outlist[i]) | |
else: | |
outstring += "NULL," | |
outstring += "\n};" | |
with open(OUTPATH, 'w') as file: | |
file.write(outstring) | |
file.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment