# _*_ coding: utf-8 _*_
import re
struct_str = """
struct RNCAP
{
UINT16 usTest1;
UINT32 ulTest2;
};
typedef struct
{
UINT16 usTest1;
UINT32 ulTest2;
UINT32 ulTest3;
RNCAP rncapStru;
UINT16 usTest6;
UINT8 ucTest7;
UINT16 usTest8;
} RNCAP_POOL;
"""
stream = "ABCDEF012345678912345"
#basic_tpye_list = ["UINT8", "UINT16", "UINT32", "UINT64"]
basic_type_dict = {"UINT8":1, "UINT16":2, "UINT32":4, "UINT64":8}
struct_type_dict = {}
class BasicType(object):
def __init__(self):
self.type = ""
self.struct_name = ""
self.var_name = ""
self.position = 0
self.size = 0
self.value = 0
self.sub_basic_type_list = []
def struct_2_basic_type(stream_str):
if "struct" not in stream_str or ";" not in stream_str or "{" not in stream_str or "}" not in stream_str:
print("struct format error!")
return
stream_lines = stream_str.splitlines()
type_is_typedef = False
type_position = 0
type_size = 0
for line in stream_lines:
if "struct" in line:
basic_type = BasicType()
basic_type.position = 0
type_position = 0
type_size = 0
type_is_typedef = False
if "typedef" not in line:
variables = line.split(" ", 1)
basic_type.struct_name = variables[1].strip()
else:
type_is_typedef = True
continue
if "}" in line and ";" in line:
if type_is_typedef:
m = re.search("[A-Za-z0-9_]+", line)
if m is not None:
basic_type.struct_name = m.group()
basic_type.size = type_size
basic_type_dict[basic_type.struct_name] = basic_type.size
struct_type_dict[basic_type.struct_name] = basic_type
continue
m = re.search("[A-Za-z0-9_]+[ ]+[A-Za-z0-9_]+;", line)
if m is None:
continue
variables = m.group()[:-1].split(" ", 1)
sub_basic_type = BasicType()
sub_basic_type.struct_name = variables[0].strip()
sub_basic_type.var_name = variables[1].strip()
sub_basic_type.position = type_position
sub_size = basic_type_dict.get(sub_basic_type.struct_name)
if sub_size is None:
continue
sub_basic_type.size = sub_size
type_position += sub_size
type_size += sub_size
struct_type = struct_type_dict.get(sub_basic_type.struct_name)
if struct_type is not None:
sub_basic_type.sub_basic_type_list = struct_type.sub_basic_type_list
basic_type.sub_basic_type_list.append(sub_basic_type)
return basic_type
def stream_2_struct(struct_info, stream_str):
if struct_info.size != len(stream_str):
print("struct size and len stream are not equal.")
return
for sub_struct in struct_info.sub_basic_type_list:
if len(sub_struct.sub_basic_type_list) == 0:
sub_struct.value = int(stream_str[sub_struct.position:sub_struct.position+sub_struct.size], 16)
else:
stream_2_struct(sub_struct, stream_str[sub_struct.position:sub_struct.position+sub_struct.size])
if __name__ == "__main__":
basic_type = struct_2_basic_type(struct_str)
stream_2_struct(basic_type, stream)
print basic_type.struct_name
pass