以编程方式检索没有硬编码成员名称的C结构成员的内存偏移量 [英] Programmatically retrieve memory offset of C struct members w/o hard-coding member names

查看:136
本文介绍了以编程方式检索没有硬编码成员名称的C结构成员的内存偏移量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个小程序,用于使用 offsetof()运算符打印struct成员的偏移量。

I have a small program which I use to print the offset of struct members using the offsetof() operator.

我在许多情况下使用这个程序,所讨论的结构不同,所以我需要重新编程每个项目的代码(以及我对结构进行的每个修改)。由于这些结构往往非常大(控制和状态结构),所以更新会花费很多时间。

I use this program in many contexts, where the structs in question are different and so I need to reprogram the code for each project (and for each modification I make to the structure). Since these structures tend to be pretty big (control and state structs), the update consumes lots of time.

我想要的是一种可以使用的方法 offsetof()等效,但第二个参数是成员的名字,以字符串的形式给出,而不是在语句中硬编码。

What I would like to have is a method where I can use offsetof() equivalent, but where the 2nd parameter would be the member's name, given as a string, instead of hard-coding it in the statement.

为简单起见,我们假设这些结构由32位单字和数组组成,所以偏移量总是4的倍数。

To simplify, lets assume that the structures are comprised of single- and arrays of- 32-bit words, so the offset is always a multiple of 4.

另外,也可以使用其他方法替代名称字符串。

Also, instead of name strings, an alternative method is welcome.

[注意,尽管成员都是字号,但仍然由于编译器可能会在成员之间添加填充,因此仅通过计算成员来计算地址并不是一个好的解决方案。作为一个回答(已被删除),使用packed属性可以通过删除填充来解决问题,但这不是一个有效的解决方案,因为定义结构的实际应用程序可能会使用填充来优化内存访问。]

推荐答案

您可以制作以下形式的符号表数组:

You make "symbol table" arrays of the form:

#define S struct mystruct
#define X(m) { #m, offsetof(S, m) }
static const struct table {
    const char *name;
    size_t offset;
} table[] = {
    X(member1),
    X(member2),
    /* ... */
};

然后你可以有一个函数循环搜索给定的名字,并获得偏移量。您可以拥有多个这样的表格,每个结构一个,全部使用相同的搜索功能。如果您拥有如此多的成员以致线性搜索性能成为问题,则可以进行二进制搜索或添加散列。

Then you can have a function which loops over table searching for a given name, and obtains the offset. You can have multiple such tables, one for each structure, all using the same search function. If you have so many members that the linear search performance becomes a problem, you can binary-search or add a hash.

这篇关于以编程方式检索没有硬编码成员名称的C结构成员的内存偏移量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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