`
freesoftman
  • 浏览: 313964 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

再次理解offsetof的实现原理

阅读更多

offsetof的原型为:

size_t offsetof(type, member);

 

DESCRIPTION
       The  macro  offsetof()  returns the offset of the field member from the
       start of the structure type.

       This macro is useful because the sizes of the  fields  that  compose  a
       structure  can  vary  across  implementations, and compilers may insert
       different numbers of padding bytes between  fields.   Consequently,  an
       element's  offset  is  not necessarily given by the sum of the sizes of
       the previous elements.

       A compiler error will result if member is not aligned to a byte  bound‐
       ary (i.e., it is a bit field).

RETURN VALUE
       offsetof()  returns  the  offset  of  the given member within the given
       type, in units of bytes.

CONFORMING TO
       C89, C99, POSIX.1-2001.

 

以上内容摘自开发文档。

 

大意就是获取结构体成员member在结构体type中的偏移量。

 

其实offsetof就是一个宏定义,我们也可以自己实现的。接下来就来分析这个宏的具体实现。

struct type{

    int a;

    int b;

    int member;

    int c : 1;

}

 

#define offsetof(type, member)   (size_t)&(((type *)0)->member)

 

type是一个结构体,定义如上所示,它有一个member成员,返回的是结构体type的成员member相对type的偏移地址。

 

这里的一个妙处就:(type *)0骗编译器说有一个指向结构体type的指针,地址值是0。

然后在取该指针的member地址 &((type *)0)->member,因为基址是0,所以这时member的地址就是member在type中的偏移量了。

 

最后转换成size_t型,即unsigned int。

分享到:
评论

相关推荐

    memoffset:Rust的offsetof

    备忘录集 类似于Rust结构的offset_of功能。 引入以下宏: offset_of! 用于获取结构成员的偏移量。 offset_of_tuple! 用于获取元组成员的偏移量。 (需要Rust 1.20+) ... 用于获取一个或多个字段跨度的范围。...

    深度剖析C语言结构体

    Linux内核的实现博大精深,从offsetof的实现到后面的container_of,为什么通过结构体的的成员就能获得整个结构体的指针呢?这就得益于offsetof宏的实现。关于这个宏,前面的博文也有讲解,但不够深入,今天的这个...

    对mongoose源码的阅读,写的分享ppt,欢迎一起探讨

    对mongoose源码的分析,另外 分享了一些比较经典的用法,比如函数指针,strcspn实现,offsetof用法等等

    《C深度解析》第7、8章 结构体/共用体/枚举,杂项(自动类型转换、大小端序等)

    结构体结构体定义、访问、传参,结构体对齐(offsetof宏、contaner_of宏),结构体内嵌函数指针,程序分层,模块化等。2. 共用体共用体与结构体的异同、共用体的作用、共用体举例3. 枚举第8章:自动类型转换、大小...

    Go程序设计语言

    简介 本书由《C程序设计语言》的作者Kernighan和...27613.1 unsafe.Sizeof、Alig[0no0]f 和Offsetof 27613.2 unsafe.Pointer 27813.3 示例:深度相等 28013.4 使用cgo调用C代码 28213.5 关于安全的注意事项 286

    内存对齐(Memory alignment)

    结构体内存布局2.1 offsetof 定位某成员在结构体中的「 偏移量」2.2 为保证内存对齐,填充了什么值3. 内存对齐3.1 结构体成员默认内存对齐3.2 不同架构内存对齐方式3.3 小试牛刀3.3.1 前置填充3.3.2 中间填充3.3.3 ...

    C语言中结构体偏移及结构体成员变量访问方式的问题讨论

    c语言结构体偏移 示例1 我们先来定义一下需求: 已知结构体类型定义如下: ...如果你对c语言的库函数比较熟悉的话,那么你第一个想到的肯定是offsetof函数(其实只是个宏而已,先姑且这样叫着吧),我们man 3 offset

    linux内核 0.11版本源码 带中文注释

    * 是啊,是啊,下面这段程序很差劲,但我不知道如何正确地实现,而且好象它还能运行。如果有 * 关于实时时钟更多的资料,那我很感兴趣。这些都是试探出来的,以及看了一些bios 程序,呵! */ #define CMOS_...

Global site tag (gtag.js) - Google Analytics