Skip to content

Instantly share code, notes, and snippets.

@kyujin-cho
Last active December 21, 2019 11:48
Show Gist options
  • Save kyujin-cho/fb7358c174111863f812641ec0eee31a to your computer and use it in GitHub Desktop.
Save kyujin-cho/fb7358c174111863f812641ec0eee31a to your computer and use it in GitHub Desktop.
C struct to Python ctype
decl_regex = re.compile(r' *([a-zA-Z0-9_\* \[\]]+ : [0-9]+);')
arr_regex = re.compile(r'([a-zA-Z][0-9a-zA-Z]*)\[([0-9]+)\]')
type_table = {
'int': 'ctypes.c_int',
'char': 'ctypes.c_char',
'size_t': 'ctypes.c_size_t',
'unsigned': 'ctypes.c_uint',
'unsigned int*': 'POINTER(ctypes.c_uint)'
}
classname = 'hipDeviceArch_t'
TAB = ' '
ss = '''
// 32-bit Atomics
unsigned hasGlobalInt32Atomics : 1; ///< 32-bit integer atomics for global memory.
unsigned hasGlobalFloatAtomicExch : 1; ///< 32-bit float atomic exch for global memory.
unsigned hasSharedInt32Atomics : 1; ///< 32-bit integer atomics for shared memory.
unsigned hasSharedFloatAtomicExch : 1; ///< 32-bit float atomic exch for shared memory.
unsigned hasFloatAtomicAdd : 1; ///< 32-bit float atomic add in global and shared memory.
// 64-bit Atomics
unsigned hasGlobalInt64Atomics : 1; ///< 64-bit integer atomics for global memory.
unsigned hasSharedInt64Atomics : 1; ///< 64-bit integer atomics for shared memory.
// Doubles
unsigned hasDoubles : 1; ///< Double-precision floating point.
// Warp cross-lane operations
unsigned hasWarpVote : 1; ///< Warp vote instructions (__any, __all).
unsigned hasWarpBallot : 1; ///< Warp ballot instructions (__ballot).
unsigned hasWarpShuffle : 1; ///< Warp shuffle operations. (__shfl_*).
unsigned hasFunnelShift : 1; ///< Funnel two words into one with shift&mask caps.
// Sync
unsigned hasThreadFenceSystem : 1; ///< __threadfence_system.
unsigned hasSyncThreadsExt : 1; ///< __syncthreads_count, syncthreads_and, syncthreads_or.
// Misc
unsigned hasSurfaceFuncs : 1; ///< Surface functions.
unsigned has3dGrid : 1; ///< Grid and group dims are 3D (rather than 2D).
unsigned hasDynamicParallelism : 1; ///< Dynamic parallelism.
'''
def parse(line):
parsed = decl_regex.match(line)
if parsed is None:
return None, None, None, None
decl_body = parsed.group(1)
left, bit_field = decl_body.split(' : ')
split = left.split(' ')
datatype, name = ' '.join(split[:-1]), split[-1]
if _type := type_table.get(datatype):
datatype = _type
arrlen = None
if '[' in name:
parsed = arr_regex.match(name)
name, arrlen = parsed.groups(1)
return datatype, name, arrlen, bit_field
print(f'class {classname}(ctypes.Structure):')
print(f'{TAB}_fields_ = [')
for line in ss.splitlines():
datatype, name, arrlen, bit_field = parse(line)
if datatype is None:
continue
if arrlen is not None:
datatype = datatype + ' * ' + str(arrlen)
print(f'{TAB}{TAB}(\'{name}\', {datatype}, {bit_field}), ')
print(f'{TAB}]')
print('')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment