开发者

How to parse a C header file?

开发者 https://www.devze.com 2022-12-14 13:40 出处:网络
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:

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 revis开发者_开发知识库ionMajor;
    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.


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".

https://github.com/eliben/pycparser


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

  • pyparsing
  • ply
  • lepl

    and a lot more ...


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 :)


For the same purpose I'm considering pyclibrary, it is not a complete C parser but it is aimed at parsing C header files, so it is much easier to use than pycparser or some gccxml-based parser: although weakly documented, just try CParser.py testHeader.h and you'll see how it works.

Depends on pyparsing and, as far as I understand, it is pure python.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号