tags:

views:

340

answers:

3

Does anyone know a spiffy way to use C header files in Python? For example I have a C program that includes a global variable:

typedef struct ImageInfo
{
    uint8_t revisionMajor;
    uint8_t revisionMinor;
    uint16_t checksum;    

} ImageInfo;

ImageInfo gImageInfo;   /* Placed at a specific address by the linker */

I would like to be able to take the binary generated by the C compiler/linker and parse this structure (and possibly modify it) with a Python script.

+4  A: 

Take a look at pygccxml. I use it to build in-memory graphs of my C / C++ source code that I can use as the basis for many code generation tasks.

PS: When I first started out with Python based code-generation I actually tried to write a parser myself: save yourself the pain and don't even go there! (looks like your are clued up already though...) pygccxml is everything you want and more :)

jkp
+4  A: 

Have a look at this C++ header parser written in Python. You can also write your own parser using any of these tools:

Vijay Mathew
Great references: I didn't know about a bunch of those modules. I'd like to know how full-featured they are compared to pygccxml (which clearly has a leg-up since it's backed by GCC). Writing a C++ parser is notoriously hard (though the question was about C parsing). It would be nice to use something lighter-weight than the full GCCXML based stack if possible.
jkp
+2  A: 

This was mentioned on SO yesterday; I haven't had a chance to check it out more thoroughly yet, but I'm meaning to. The pycparser, a "C parser and AST generator written in Python".

http://code.google.com/p/pycparser/

Matt Anderson