简体   繁体   English

需要获取结构与其在C中的字段之一之间的偏移量

[英]Need to get the offset between a struct and one of it's fields in C

The title of the topic may as well be "Is size_t enough to hold an address?" 主题的标题也可能是“ size_t是否足以容纳地址?”

I'm trying to get the offset between a struct and one of it's fields and I'm using a size_t variable to hold the offset: 我试图获得结构和它的字段之一之间的偏移量,并且我正在使用size_t变量来保存偏移量:

size_t offset = (size_t)&struct.field - (size_t)&struct;

I know this is kind of forced, I'm just wondering if I might encounter somekind of error later on because of this. 我知道这是强制的,我只是想知道以后是否会因此而遇到某种错误。 I know I could have done the same using an int, but I'm wondering if it can hold the address on a 64 bit system. 我知道我可以使用int做同样的事情,但是我想知道它是否可以将地址保存在64位系统上。

What are your thoughts on this? 您对此有何想法?

Use the offsetof macro found in <stddef.h> . 使用在<stddef.h>找到的offsetof宏。

Since size_t must have a large enough range to store the size of the largest possible object, it is also large enough to store the offset of any member of any struct type: the offset of a member of a struct cannot be greater than the size of the struct. 由于size_t必须具有足够大的范围来存储最大可能对象的大小,因此它还必须足够大以存储任何结构类型的任何成员的偏移量:结构成员的偏移量不能大于的大小。结构。

Use #include <stddef.h> ... offsetof(struct foo, field) . 使用#include <stddef.h> ... offsetof(struct foo, field) It's defined to be of type size_t . 定义为size_t类型。 size_t is not necessarily big enough to hold any address, but it's big enough to hold any offset in a struct, because it's big enough to hold sizeof(any struct). size_t不一定足够大以容纳任何地址,但是它足够大以容纳结构中的任何偏移量,因为它足够大以容纳sizeof(任何结构)。

要手动执行此操作,您可以考虑先进行指针减法,然后进行size_t强制转换,如下所示:

size_t offset = (size_t)((void*)&struct.field - (void*)&struct);

As long as all items are "fixed" at compile time, you'll be safe. 只要所有项目在编译时都是“固定的”,您便会安全。 However, your code will be hard to maintain, and doing things this way should generally be avoided. 但是,您的代码将难以维护,通常应避免以这种方式执行操作。 It runs a risk of tying your code to a specific architecture as eventually one of the fields will change creating problems if all of the other calculated offsets aren't appropriately updated. 如果将所有其他计算出的偏移量未适当更新,则最终会有一个字段发生变化,这会冒着将您的代码绑定到特定体系结构的风险。

Since code tends to live longer than we think it will, the odds that some maintenance effort will eventually fix one of the values is nearly certain. 由于代码的寿命往往比我们预期的更长,因此几乎可以肯定的是,某些维护工作最终将修复其中一个值的可能性。 Doing so would wreak havoc on the (much later) update to the field order. 这样做会对(稍后)对现场订单的更新造成破坏。

I've maintained code like this. 我维护了这样的代码。 My recommendation would be to do it a different way, without the need to know exact field alignment in the code. 我的建议是以另一种方式执行此操作,而无需知道代码中的确切字段对齐方式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM