提取C结构领域 [英] Extract the fields of a C struct

查看:158
本文介绍了提取C结构领域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常写code在与C结构相互作用其他语言。最典型的是,这涉及编写Python code与结构或的 ctypes的模块。

I often have to write code in other languages that interact with C structs. Most typically this involves writing Python code with the struct or ctypes modules.

因此​​,我将有一个.h文件中充满了结构的定义,我必须通过他们来手动读取和我的Python code复制这些定义。这是耗时且容易出错,而且很难保持两个定义同步时,他们经常改变。

So I'll have a .h file full of struct definitions, and I have to manually read through them and duplicate those definitions in my Python code. This is time consuming and error-prone, and it's difficult to keep the two definitions in sync when they change frequently.

有没有任何语言中的一些工具或库(并不一定是C或者Python),它可以采取.h文件并生成它的结构和各自领域的结构化列表?我很乐意能写一个脚本来生成我自动生成的Python我的结构定义,我不希望有处理任意的C code去做。普通的前pressions将工作的伟大约90%的时间,然后会导致无休止的头痛剩下的10%。

Is there some tool or library in any language (doesn't have to be C or Python) which can take a .h file and produce a structured list of its structs and their fields? I'd love to be able to write a script to generate my automatically generate my struct definitions in Python, and I don't want to have to process arbitrary C code to do it. Regular expressions would work great about 90% of the time and then cause endless headaches for the remaining 10%.

推荐答案

如果您编译C code。与调试( -g )的 pahole 混帐)可以给你所使用的确切结构布局。

If you compile your C code with debugging (-g), pahole (git) can give you the exact structure layouts being used.


$ pahole /bin/dd
…
struct option {
        const char  *              name;                 /*     0     8 */
        int                        has_arg;              /*     8     4 */

        /* XXX 4 bytes hole, try to pack */

        int *                      flag;                 /*    16     8 */
        int                        val;                  /*    24     4 */

        /* size: 32, cachelines: 1, members: 4 */
        /* sum members: 24, holes: 1, sum holes: 4 */
        /* padding: 4 */
        /* last cacheline: 32 bytes */
};
…

这应该是一个相当要好很多,比传统的C解析。

This should be quite a lot nicer to parse than straight C.

这篇关于提取C结构领域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆