Skip to content

Instantly share code, notes, and snippets.

@csm10495
Last active May 8, 2016 06:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save csm10495/cba20eb6abb316c876e6e6de763ff349 to your computer and use it in GitHub Desktop.
Save csm10495/cba20eb6abb316c876e6e6de763ff349 to your computer and use it in GitHub Desktop.
Script to make a ctypes Structure from C++ enum
"""
Brief:
This file can be used to make a ctypes Structure from a c++ struct.
Simply copy-paste the structure from typedef to end as input and
out.txt will be created with it as a Structure
You may need to make some type fixes...
Author:
Charles Machalow
"""
try:
raw_input
except:
raw_input = input
WINAPI_TYPE_TO_CTYPES = {
'WORD' : 'c_uint16',
'DWORD' : 'c_uint32',
'ULONG' : 'c_uint32',
'LONG' : 'c_int32',
'UCHAR' : 'c_char', # Note this is done for character representation
'USHORT': 'c_uint16',
'SHORT' : 'c_int16',
'BOOLEAN': 'c_uint8',
'BOOL' : 'c_uint8',
}
with open('out.txt', 'w') as f:
while True:
line = raw_input()
if line.strip() != "quit":
if 'typedef' in line:
structName = line.replace("typedef struct", "").replace("{", "").strip().strip("_")
f.write("class %s(Structure):\n" % structName)
f.write(" _pack_ = 1\n")
f.write(" _fields_ = [\n")
elif '}' in line:
f.write(" ]\n")
break
else:
line = line.replace(";", "")
myType, name = line.split()[:2]
if '_' not in myType:
myType = WINAPI_TYPE_TO_CTYPES.get(myType, "c_" + myType.lower())
if ":" in line:
myType += ", %s" % line[line.find(":") + 1:]
if '[' in name:
name = name[:name.find('[')]
try:
arraySizeString = line[line.find("[") + 1:line.find(']')]
arraySize = int(arraySizeString)
except:
arraySize = 1
myType = '%s * %d' % (myType, arraySize)
spacing = 30 - len(name)
if spacing < 0:
spacing = 0
f.write(" (\"%s\", %s %s),\n" % (name, " " * spacing, myType))
else:
break
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment