XML to Python Class to C Struct -
i need advice. 2 questions, exist this, modules should use develop this.
i have structures come xml file. want represent them in python classes (maybe using factory create class per structure). want these classes have function emit structure c struct.
from research ctypes seems recommended thing use represent structures in python classes, don't see methods emit c stucts creation of header file.
from op's comment think minimal solution set of helper functions instead of classes. xmltodict library makes easy turn xml data nested dictionaries, more or less json. set of helpers parse contents , generate appropriate c-struct strings that's needed. if can work dictionaries :
{ "name": "my_struct", "members": { [ "name": "intmember", "ctype": "int" }, { "name": "floatmember", "ctype": "float" } ] }
you can like:
from string import template struct_template_string = ''' typedef $structname struct { $defs } $structname; ''' struct_template = template(struct_template_string) member_template = template(" $ctype $name;") def spec_to_struct(spec_dict): structname = spec_dict['name'] member_data = spec_dict['members'] members = [member_template.substitute(d) d in member_data] return struct_template.substitute(structname = structname, defs = "\n".join(members))
which produce like:
typedef my_struct struct { int intmember; float floatmember; } my_struct;
i'd try working basic functions first before trying build class scaffold. pretty easy hide details in class using property descriptors:
class data_property(object): def __init__(self, path, wrapper = none): self.path = path self.wrapper = wrapper def __get__(self, instance, owner): result = instance[self.path] if self.wrapper: if hasattr(result, '__iter__'): return [self.wrapper(**i) in result] return self.wrapper(**result) return result class memberwrapper(dict): name = data_property('name') type = data_property('ctype') class structwrapper(dict): name = data_property('name') members = data_property('members', memberwrapper ) test = structwrapper(**example) print test.name print test.members member in test.members: print member.type, member.name # my_struct # [{'name': 'intmember', 'ctype': 'int'}, {'name': 'floatmember', 'ctype': 'float'}] # int intmember # float floatmember
Comments
Post a Comment