├── LICENSE ├── README.md ├── header2.py ├── parse_type.py ├── parserfile.py ├── pycompiler.py └── requirements.txt /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## Overview 2 | 3 | **CxxHeader2Py** is a powerful Python tool designed to streamline the process of parsing C/C++ header files and extracting valuable information such as defines, enums, structs, and variables. By harnessing the capabilities of **CxxHeader2Py**, developers can effortlessly convert this extracted data into Python objects, saving time and effort in the translation process. 4 | 5 | 6 | ## Usage: 7 | The CxxHeader2Py tool accepts the following arguments: 8 | 9 | -a : Specifies the path to the directory where C/C++ header files are located. CxxHeader2Py will scan the specified directory and its subdirectories to extract the necessary information. 10 | 11 | -f : Specifies the path to a specific C/C++ header file. CxxHeader2Py will parse the specified file to extract the required information. 12 | 13 | -c : Provides compiler options as common defines. These options are used during the parsing process to ensure accurate extraction of information from the header files. 14 | 15 | --version: set the version of the output python file. 16 | 17 | -o : Specifies the path and filename of the output Python file. CxxHeader2Py will generate the Python code with equivalent objects and save it to the specified file. 18 | 19 | Example Usage: 20 | ``` 21 | CxxHeader2Py -a /path/to/headers/ -c "-DOPTION1 -I/path/to/includes" -o output.py --version=1 22 | CxxHeader2Py -f /path/to/header/file.h -c "-DOPTION2 -I/path/to/includes" -o output.py 23 | CxxHeader2Py --version=2 24 | ``` 25 | -------------------------------------------------------------------------------- /header2.py: -------------------------------------------------------------------------------- 1 | # 2 | import argparse 3 | import os 4 | import platform 5 | import sys 6 | import glob 7 | import textwrap 8 | 9 | from parserfile import ParseHeader, PyText 10 | 11 | version = 0.1 12 | 13 | parser = argparse.ArgumentParser(prog='header2py', 14 | description='Version %s. Generate python code from C headers' % (version)) 15 | 16 | parser.add_argument("-a", "--add-dir", 17 | dest="dirs", 18 | help="add dir with header", 19 | action="append", 20 | default=[]) 21 | 22 | parser.add_argument("-f", "--add-header-file", 23 | dest="files", 24 | help="add header files", 25 | action="append", 26 | default=[]) 27 | 28 | parser.add_argument("-s", "--add-sets-of-files", 29 | dest="sets_of_files", 30 | help="add header files bundles", 31 | action="append", 32 | default=[]) 33 | 34 | parser.add_argument("-c", "--compile-options", 35 | dest="compile_options", 36 | help="add header files", 37 | default="" ) 38 | 39 | parser.add_argument("-i", "--include-string", 40 | dest="include_string", 41 | help="add string in begin test code", 42 | default="" ) 43 | 44 | parser.add_argument("-o", "--output-file", 45 | dest="output", 46 | default="output.py") 47 | 48 | parser.add_argument("-d", "--debug-level", 49 | dest="debug_level", 50 | default=0) 51 | 52 | parser.add_argument("--version", 53 | dest="version", 54 | default="undef_version") 55 | 56 | files = [] 57 | 58 | options = parser.parse_args() 59 | #files.extend(options.files) 60 | files.extend(map(lambda x: os.path.abspath(x), options.files)) 61 | 62 | for set_of_files in options.sets_of_files: 63 | set_of_files = set_of_files.split(" ") 64 | files.extend(set_of_files) 65 | 66 | compile_options = options.compile_options 67 | 68 | for d in options.dirs: 69 | f_list = glob.glob(d + "/*.h") 70 | f_list = map(lambda x: os.path.abspath(x), f_list) 71 | files.extend(f_list) 72 | compile_options += " -I" + d 73 | 74 | #print(files) 75 | pytext = PyText() 76 | 77 | compile_options = compile_options.split(" ") 78 | 79 | include_string = options.include_string 80 | 81 | debug = int(options.debug_level) > 0 82 | 83 | version = '"%s"' % options.version 84 | 85 | print(files) 86 | 87 | pytext.text = """# -*- coding: utf-8 -*- 88 | # 89 | # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, 90 | # INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 91 | # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 92 | # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 93 | # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 94 | # WHETHER IN CONTRACT, STRICT LIABILITY,OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 95 | # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 96 | # 97 | # To improve the quality of the software, users are encouraged to share modifications, enhancements or bug fixes with 98 | # remotemcu.com (remcu@remotemcu.com) 99 | # 100 | # It is python header file for using REMCU library 101 | # 102 | # 103 | # word size : 32 bit 104 | # 105 | # 106 | 107 | 108 | import ctypes 109 | 110 | \n\n""" 111 | 112 | pytext.addValue('__version__' , version) 113 | pytext.addValue('__RUN' , 0) 114 | pytext.addValue('__HALT' , 1) 115 | pytext.addValue('__ERROR' , 0) 116 | pytext.addValue('__WARNING' , 1) 117 | pytext.addValue('__INFO' , 2) 118 | pytext.addValue('__DEBUG' , 3) 119 | pytext.addValue('__ALL_LOG' , 4) 120 | pytext.addValue('DEFAULT_OPENOCD_PORT' , 6666) 121 | pytext.addValue('DEFAULT_GDB_PORT' , 3333) 122 | 123 | 124 | 125 | for f in files: 126 | base_name = os.path.basename(f) 127 | pytext.addComment("file %s : \n" % base_name) 128 | parser = ParseHeader(f, compile_options, include_string, debug) 129 | pt = parser.parse() 130 | pytext.add(pt) 131 | pytext.addComment(20*"--" + "\n") 132 | 133 | source_text = pytext.text 134 | 135 | source_text += "\n__all__ = " 136 | 137 | text = "[%s]" % ", ".join([repr(str(n)) for n in pytext.all]) 138 | wrapper = textwrap.TextWrapper(break_long_words=False, width=88, initial_indent=" ", 139 | subsequent_indent=" ") 140 | for line in wrapper.wrap(text): 141 | source_text += line + "\n" 142 | 143 | if debug: 144 | print(source_text) 145 | 146 | output_file = options.output 147 | 148 | with open(output_file, 'w+') as f: 149 | f.write(source_text) 150 | f.flush() 151 | -------------------------------------------------------------------------------- /parse_type.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from pycompiler import runtimeOutput, CPP_GPP 3 | 4 | ctypes_set = {"c": "ctypes.c_char", 5 | "a" : "ctypes.c_int8", 6 | "h" : "ctypes.c_uint8", 7 | "s" : "ctypes.c_int16", 8 | "t" : "ctypes.c_uint16", 9 | "i" : "ctypes.c_int32", 10 | "j" : "ctypes.c_uint32", 11 | "l" : "ctypes.c_int64", 12 | "m" : "ctypes.c_uint64",} 13 | 14 | __c_void_p = "ctypes.c_void_p" 15 | __unknown = "unknown" 16 | 17 | 18 | def get_size_and_type(string_id): 19 | _p = string_id.index("_") 20 | _num_str = string_id[1:_p] 21 | try: 22 | size = int(_num_str) 23 | except Exception as e: 24 | raise Exception("size array error in result : " + string_id) 25 | 26 | _t_str = string_id[_p+1 : ] 27 | 28 | ctype_id = ctypes_set.get(_t_str, __unknown) 29 | if ctype_id == __unknown: 30 | raise Exception("strangly type of array : " + string_id + " / " + ctype_id) 31 | 32 | return size, ctype_id 33 | 34 | 35 | def parse_type_of_field(options, name_class, name_field): 36 | #ctext = '#include "%s" \n' % (options.filename) 37 | #ctext += '#include "stdio.h"\n' 38 | ctext = options.prepareSourceCode() 39 | 40 | ctext += '#include \n' 41 | ctext += 'int main(){ printf("%%s", typeid(((%s *)0)->%s).name()); return 0; }' % (name_class, name_field) 42 | rt_type_id, error = runtimeOutput(ctext, options.compile_options, options.debug, compiler=CPP_GPP) 43 | if error != "": 44 | raise Exception("rto error of the field / " + error) 45 | 46 | if len(rt_type_id) == 1: 47 | ctype_id = ctypes_set.get(rt_type_id, __unknown) 48 | if ctype_id == __unknown: 49 | return "", "unknown field" 50 | result = ctype_id 51 | elif rt_type_id[0] == 'P': 52 | result = __c_void_p 53 | elif rt_type_id[0] == 'A': 54 | size, ctype_id = get_size_and_type(rt_type_id) 55 | arr_type = "%s * %d" % (ctype_id, size) 56 | result = arr_type 57 | else: 58 | if options.debug: 59 | print("rt_type_id : " + rt_type_id) 60 | raise Exception("strangly type of field") 61 | 62 | return result 63 | 64 | 65 | 66 | if __name__ == "__main__": 67 | def options(): pass 68 | if len(sys.argv) == 1: 69 | print("set name file") 70 | exit() 71 | options.filename = sys.argv[1] 72 | options.compile_options = ['-w', '-I.'] 73 | options.debug = True 74 | name_class = sys.argv[2] 75 | name_field = sys.argv[3] 76 | print(parse_type_of_field(options, name_class, name_field)) 77 | -------------------------------------------------------------------------------- /parserfile.py: -------------------------------------------------------------------------------- 1 | import CppHeaderParser 2 | import sys 3 | from pycompiler import runtimeOutput 4 | from parse_type import parse_type_of_field 5 | 6 | _offset = " " 7 | 8 | class PyText(object): 9 | def __init__(self): 10 | self.text = "" 11 | self.all = [] 12 | 13 | def addValue(self, var, value): 14 | #chec value on int 15 | self.text += var + " = "+ str(value) + "\n" 16 | self.all.append(var) 17 | 18 | def addComment(self, comment): 19 | self.text += "# " + comment +"\n" 20 | 21 | def add(self, other): 22 | self.text += other.text 23 | self.all.extend(other.all) 24 | 25 | def addNameStruct(self, name): 26 | self.all.append(name) 27 | self.text += "\nclass " + name + "(ctypes.Structure):\n" 28 | self.text += _offset + "_pack_ = False\n" 29 | self.text += _offset + "_fields_ = [\n" 30 | 31 | def addFieldStruct(self, name, c_type): 32 | self.text += _offset*2 + "('" + name + "', " + c_type + "),\n" 33 | 34 | def releaseStruct(self): 35 | self.text += _offset + "]\n" 36 | self.text += _offset + "def ref(self):\n" 37 | self.text += _offset*2 + "return ctypes.byref(self)\n\n" 38 | 39 | def toStr(self): 40 | return self.text 41 | 42 | 43 | 44 | class ParseHeader(object): 45 | def __init__(self, filename, compile_options=[], include_string="", debug=False): 46 | self.filename = filename 47 | self.compile_options = compile_options 48 | self.pytext = PyText() 49 | self.debug = debug 50 | self.include_string = include_string 51 | 52 | def pEnums(self,enums): 53 | if len(enums) == 0: 54 | return PyText 55 | for e in enums: 56 | name = e['name'] 57 | self.pytext.addComment("Enum " + name) 58 | values = e['values'] 59 | if len(values) == 0: 60 | continue 61 | for v in values: 62 | enum_name = v['name'] 63 | #value = self.runtimeValue(enum_name) 64 | self.pushValue(enum_name) 65 | 66 | def pDefines(self, defines): 67 | if len(defines) == 0: 68 | return 69 | for d in defines: 70 | d = d.strip() #trim define/ del tabs and whsp 71 | first_space = d.find(" ") 72 | if first_space < 0: 73 | self.pytext.addComment("empty define %s" % d) 74 | continue 75 | name = d[:first_space] 76 | name = name.strip() #trim define/ del tabs and whsp 77 | if name.find("(") >= 0: 78 | #first_row = d.split('\n')[0] 79 | d = d.replace('\n', '\n#') 80 | self.pytext.addComment("fun define %s" % d) 81 | continue 82 | self.pushValue(name) 83 | 84 | def pVariable(self, variables): 85 | if len(variables) == 0: 86 | return PyText 87 | for v in variables: 88 | name_var = v['name'] 89 | if len(name_var) == 0: 90 | continue 91 | self.pushValue(name_var) 92 | 93 | def parse(self): 94 | header = CppHeaderParser.CppHeader(self.filename) 95 | self.pEnums(header.enums) 96 | self.pDefines(header.defines) 97 | self.pVariable(header.variables) 98 | self.pStruct(header.classes) 99 | #print(self.pytext.text) 100 | return self.pytext 101 | 102 | def pushValue(self, name): 103 | result, error = self.runtimeValue(name) 104 | if error == "" and result != "": 105 | self.pytext.addValue(name,result) 106 | return 107 | self.pytext.addComment("Skip " + name + " : " + error) 108 | 109 | def prepareSourceCode(self): 110 | ctext = self.include_string + "\n" 111 | ctext += '#include "%s" \n' % (self.filename) 112 | ctext += '#include "stdio.h"\n' 113 | return ctext 114 | 115 | def runtimeValue(self, value): 116 | ctext = self.prepareSourceCode() 117 | ctext += 'int main(){ printf("0x%%LX", %s); return 0; }' % value 118 | result, error = runtimeOutput(ctext, self.compile_options, self.debug) 119 | return result, error 120 | 121 | def sizeOfField(self, name_class, name_field): 122 | ctext = self.prepareSourceCode() 123 | ctext += 'int main(){ printf("%%d", sizeof(((%s *)0)->%s)); return 0; }' % (name_class, name_field) 124 | result, error = runtimeOutput(ctext, self.compile_options, self.debug) 125 | return result, error 126 | 127 | def checkStruct(self, class_, name_class): 128 | if class_['abstract']: 129 | return 'abstract' 130 | if class_['declaration_method'] != 'struct': 131 | return "declaration_method is not struct" 132 | if class_['inherits'] != []: 133 | return "inherits" 134 | if class_['parent'] != None: 135 | return "parent" 136 | prop = class_['properties'] 137 | if prop['private'] != [] or prop['protected'] != []: 138 | return "private or protected" 139 | public_fields = prop['public'] 140 | if len(public_fields) == 0: 141 | return "no public" 142 | for field in public_fields: 143 | name_field = field['name'] 144 | 145 | if field['class'] != 0: 146 | return "field is class : " + name_field 147 | #if field['array'] != 0: 148 | #return "field is array" 149 | #if field['pointer'] != 0: 150 | #return "field is pointer" 151 | 152 | result, error = self.sizeOfField(name_class, name_field) 153 | if error != "": 154 | if self.debug: 155 | print("runtime time error: " + error + " , name: " + name_field) 156 | continue 157 | size = int(result) 158 | if size == 0: 159 | return "error size of %s is %s " %(name_field, result) 160 | return "" 161 | 162 | def pStruct(self, classes): 163 | if len(classes) == 0: 164 | return 165 | for name_class in classes: 166 | class_ = classes[name_class] 167 | self.pytext.addComment("struct " + name_class) 168 | err = self.checkStruct(class_, name_class) 169 | if err != "": 170 | self.pytext.addComment("struct " + name_class + " : " + err) 171 | continue 172 | prop = class_['properties'] 173 | public_fields = prop['public'] 174 | self.pytext.addNameStruct(name_class) 175 | for field in public_fields: 176 | name_field = field['name'] 177 | result, error = self.sizeOfField(name_class, name_field) 178 | if error != "": 179 | continue 180 | 181 | try: 182 | ctype = parse_type_of_field(self, name_class, name_field) 183 | except Exception as e: 184 | if self.debug: 185 | print(e) 186 | size = int(result) 187 | ctypes = {1 : "ctypes.c_uint8", 188 | 2: "ctypes.c_uint16", 189 | 4: "ctypes.c_uint32", 190 | 8: "ctypes.c_uint64",} 191 | universal_size = "ctypes.c_uint8 * " + result 192 | ctype = ctypes.get(size, universal_size) 193 | 194 | self.pytext.addFieldStruct(name_field, ctype) 195 | self.pytext.releaseStruct() 196 | 197 | 198 | 199 | 200 | 201 | if __name__ == "__main__": 202 | if len(sys.argv) == 1: 203 | #print("set name file") 204 | sys.exit("set name file") 205 | 206 | compile_options = [] 207 | if len(sys.argv) >= 2: 208 | options = sys.argv[2] 209 | compile_options = options.split(" ") 210 | #print(compile_options) 211 | 212 | parser = ParseHeader(sys.argv[1], compile_options) 213 | #parser = ParseHeader("dff") 214 | pytext = parser.parse() 215 | print(pytext.text) 216 | -------------------------------------------------------------------------------- /pycompiler.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import subprocess 3 | 4 | _file = "/dev/shm/temp.c" 5 | #_file = "temp.c" 6 | _out = "/dev/shm/temp.out" 7 | 8 | #_CC = "gcc" 9 | _CC = "clang" 10 | 11 | #CPP_GPP = "g++" 12 | CPP_GPP = "clang++" 13 | 14 | def runtimeOutput(source, compilerOpt=[], debug=False, compiler = _CC): 15 | with open(_file, 'w') as f: 16 | f.write(source) 17 | f.flush() 18 | 19 | command = [compiler, _file, "-o", _out, '-Wfatal-errors'] 20 | command.extend(compilerOpt) 21 | str_command = " ".join(command) 22 | if debug: 23 | print(source) 24 | print(str_command) 25 | res = subprocess.call(command) 26 | if res != 0: 27 | return "", "no need parse" 28 | result = subprocess.run([_out], stderr=subprocess.DEVNULL, stdout=subprocess.PIPE) 29 | if result.returncode == 0: 30 | return result.stdout.decode("utf-8") , "" 31 | return "", "no time" 32 | 33 | 34 | if __name__ == "__main__": 35 | if len(sys.argv) == 1: 36 | print("set name file") 37 | exit() 38 | source = "" 39 | with open(sys.argv[1], 'r') as f: 40 | source = f.read() 41 | compilerOpt = [] 42 | if len(sys.argv) > 2: 43 | compilerOpt = [sys.argv[2]] 44 | debug = false 45 | if len(sys.argv) > 3: 46 | debug = bool(sys.argv[3]) 47 | 48 | out, err = runtimeOutput(source,compilerOpt,debug) 49 | print(out, err) -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | CppHeaderParser 2 | textwrap --------------------------------------------------------------------------------