Read C++ enum in python

AggieDan04 danb_83 at
Wed Aug 19 08:17:55 CEST 2009

On Aug 18, 6:03 pm, Ludo
<olivier.anospamrnospamnnospamanospamenosp... at> wrote:
> Hello,
> I work in a very large project where we have C++ packages and pieces of
> python code.
> I've been googleing for days but what I find seems really too
> complicated for what I want to do.
> My business is, in python, to read enum definitions provided by the
> header file of an c++ package.
> Of course I could open the .h file, read the enum and transcode it by
> hand into a .py file but the package is regularly updated and thus is
> the enum.
> My question is then simple : do we have :
>         - either a simple way in python to read the .h file, retrieve the c++
> enum and provide an access to it in my python script

Try something like this:

file_data = open(filename).read()
# Remove comments and preprocessor directives
file_data = ' '.join(line.split('//')[0].split('#')[0] for line in
file_data = ' '.join(re.split(r'\/\*.*\*\/', file_data))
# Look for enums: In the first { } block after the keyword "enum"
enums = [text.split('{')[1].split('}')[0] for text in re.split(r'\benum
\b', file_data)[1:]]

for enum in enums:
    last_value = -1
    for enum_name in enum.split(','):
        if '=' in enum_name:
            enum_name, enum_value = enum_name.split('=')
            enum_value = int(enum_value, 0)
            enum_value = last_value + 1
        last_value = enum_value
        enum_name = enum_name.strip()
        print '%s = %d' % (enum_name, enum_value)

More information about the Python-list mailing list