13

Can anyone point me to some documentation on how to write scripts in Python (or Perl or any other Linux friendly script language) that generate C++ code from XML or py files from the command line. I'd like to be able to write up some xml files and then run a shell command that reads these files and generates .h files with fully inlined functions, e.g. streaming operators, constructors, etc.

1

8 Answers 8

16

If you want to do this simply with just standard Python stuff you might try making template files that use the Python 3 style string formatting. For example, a class template might look something like this:

{className}::{className}()
{{
}}

{className}::~{className}()
{{
}}

{className}::{className}(const {className}& other)
{{
}}

{className}& {className}::operator=(const {className}& other)
{{
    return *this;
}}

Then your Python code is super simple:

d = {}
d['className'] = 'MyCPlusPlusClassName'
with open(yourTemplateFile, 'r') as ftemp:
    templateString = ftemp.read()
with open(generatedFile, 'w') as f:
    f.write(templateString.format(**d))

Of course you can add lots of other fields alongside 'className' using the same trick. If you don't need stuff like conditional code generation you can get a lot of mileage out of something this simple.

2

I'm afraid you will not find an already-built in solution that takes your particular xml or python files and transforms them onto your required output "out of the box".

You will have to implement the parsing, the data treatment and output yourself. Not all by yourself, though; here are some pointers regarding the parsing and output.

Python comes with 2 different XML parsers (SAX and DOM -scroll down to see some examples). You will have to use one of them in order to read the source files.

For generating the output more easily, you can probably use a templating library, such as StringTemplate, or just generate the code manually, if it's small.

1
  • In addition to StringTemplate there are plenty of other templating solutions originally aimed at templating web pages (for example Jinja2) that can be re-purposed for this relatively easily.
    – jleahy
    Jan 11, 2013 at 14:02
1

You could take a look at Shedskin, a project that generates C++ code from Python code.

Depending on what your reasons are, it may be a little pointless as Satanicpuppy pointed out.

2
  • I'm more interested in just writing up a few simple shell scripts to do basic parsing and code gen, if possible. If not, I'll just handwrite the basic classes myself.
    – user357525
    Jun 3, 2010 at 14:39
  • I'm not aware of anything more simple than Shedskin - you'd probably want to just roll your own, though some folks have mentioned XML parsers. I imagine it would be fairly trivial to get something fairly simple working. Jun 3, 2010 at 14:55
1

Have a look at Cheetah. It's a template engine written in Python.

1
  • I have looked at Cheetah a few time already. Even though it says that it is used for C++ generation, there are no examples of this and no documentation of how it is used for C++. I would like to write my own simple generator for basic data types. If this turns out to be too complicated, then I won't bother with any code-gen tool.
    – user357525
    Jun 3, 2010 at 14:37
1

A few years ago I worked on a project to simplify interprocess shared memory management for large scale simulation systems. We used a related approach where the layout of data in shared memory was defined in XML files and a code generator, written in python, read the XML and spit out a set of header files defining structures and associated functions/operators/etc to match the XML description. At the time, I looked at several templating engines and, to my surprise, found it was easier and very straight-forward to just do it "by hand".

As you read the XML, just populate a set of data structures that match your code. Header file objects contain classes and classes contain variables (which may be of other class types). Give each object a printSelf() method that iterates over its contents and calls printSelf() for each object it contains.

It seems a little daunting at first but once you get started, it's pretty straight-forward. Oh, and one tip that helps with the generated code, add an indentation argument to printSelf() and increase it at each level. It makes the generated code much easier to read.

2
  • 1
    Okay, I'll try this out and look at StringTemplate too.
    – user357525
    Jun 3, 2010 at 15:21
  • Indeed, using strings for templating bits of what you generate is essential. I did most of my code with the simple % operator and it worked out just fine but the new (yeah, the code is old ;-) StringTemplates should make it even easier.
    – Rakis
    Jun 3, 2010 at 17:20
1

Out of my own experience I can recommend Jinja2 (http://jinja.pocoo.org/docs/dev/). Even though the main target language of Jinja is HTML, it works quite well for C++. And that's not only my opinion, see https://www.chromium.org/developers/jinja :). There is a stand-alone version (https://github.com/filwaitman/jinja2-standalone-compiler) that might be useful, since Jinja2 itself is only an API. I'm using the stand-alone version for my project here https://github.com/TomSmartBishop/avl with customized environment settings so that the Jinja2 opening- and closing tags match more C++ style.

1
0

I actually do some work with a legacy "4GL" development environment that does something similar, and a lot of models on the old 4GL paradigm use C and C++ as the language that they output their generated code in.

That being said, 4GL is pretty much resigned to the dust heap of history. The problem is, when you're machine generating the C code, you're losing the performance gains that would have resulted from using C in the first place, and the code is extremely difficult to maintain. Might as well just write the program in Python in the first place.

1
  • I'm not looking for an program converter. I'm looking for a document on how to write up my own Python/Perl/etc script that would simply generate C++ datatypes with basic features like streaming operators based on a short data-type specification. The specification would just list the class name , its members , a base class and some simple documentation for each member. The output would be a header file with a fully inlined class definition. I think Python or Perl should be able to do this easily.
    – user357525
    Jun 3, 2010 at 14:28
0

Hope it will be useful for somebody (you can use win32 clipboard to read in data)

import sys, string
import win32clipboard
import re


data = '''
     enum FeedTypeT
     {
         AA,
         BB,
         DDD,
         F
     };
'''

def get_from_clippord():
    # get clipboard data
    win32clipboard.OpenClipboard()
    data = win32clipboard.GetClipboardData()
    win32clipboard.CloseClipboard()
    return data

def enum_type(inenum):
    inenum = inenum.replace('\r\n', '\n')
    inenum = re.sub( r'\s', r'', inenum )
    inenum = re.sub( r'^(.*)\{.*$', r'\1', inenum )
    return inenum

def cleanup_enum(inenum):
    inenum = inenum.replace('\r\n', '\n')
    # inenum = inenum.replace('enum', '')
    inenum = re.sub( r'\s', r'', inenum )
    # inenum = re.sub( r'^.*\{(.+)[|,]\}.*$', r'\1', inenum )
    inenum = re.sub( r'^.*\{(.+)\}.*$', r'\1', inenum )
    inenum = inenum.split(',')
    return inenum

def get_element(inlist):
    for element in inlist:
       [one, two] = element.split('=')
       print('{0:20} ==> {1:>20}'.format(one, two))         # right align
#      one = element.split('=')
#      print('{0:20} ==> {1:10}'.format(one[0], one[1]))

def print_switch(typename):
    retstr = 'const std::string toString( ' + typename + ' type )'
    retstr += '\n{\n   switch( type )\n   {'
    return retstr

def print_case_line(instr, w):
    retstr = '      case ' + '{:{fw}}'.format(instr + ':', fw = w) + ' return "' + instr + '";'
    return retstr

def print_switch_end(w):
    retstr = '      default: ' + ' '*(w-4) + ' return "undef";\n   }\n}\n'
    return retstr

def main():
    #data = get_from_clippord()

    ll = cleanup_enum(data)
    print ( ll )
    print ("="*80 + "\n\n")
    print ( print_switch( enum_type(data)) )

    w = 25
    # pick right with for formating, based on the lenght of elements of enum
    for line in ll:
       if w < len(line):
          w = len(line) + 2

    for line in ll:
       print ( print_case_line(line, w) )

    print ( print_switch_end(w) )


if __name__ == '__main__':
    main()

Output:

['AA', 'BB', 'DDD', 'F']
================================================================================


const std::string toString( enumFeedTypeT type )
{
   switch( type )
   {
      case AA:                       return "AA";
      case BB:                       return "BB";
      case DDD:                      return "DDD";
      case F:                        return "F";
      default:                       return "undef";
   }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.