Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux綜合 >> Linux 核心

Linux 內核開發|offsetof 宏的原理拆解

一、offsetof 是怎麼算的

#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE*)0)->MEMBER)

可以拆成四步來看:

1> ((TYPE *)0):把位址 0 強制轉型成 TYPE 結構的指標;

2> ((TYPE *)0)->MEMBER:以 0 為基底存取 TYPE 中的 MEMBER 成員;

3> &(((TYPE *)0)->MEMBER):取出該成員的位址;

4> (size_t)(...):把結果轉成 size_t。

這個宏的巧妙之處在於:既然結構體被假設從位址 0 開始,那麼成員的位址在數值上就等於它在結構中的偏移量。

那一定要用 0 嗎?當然不是,只是用 0 最省事。若改用 4 當基底,算出的結果就必須再減掉 4 才是真正的偏移。以下程式示範這件事:

#include <stdio.h>

#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)4)->MEMBER)

struct test_struct {
    int num;
    char ch;
    float f1;
};

int main(void)
{
    printf("offsetof(struct test_struct, num) = %d\n", offsetof(struct test_struct, num) - 4);
    printf("offsetof(struct test_struct, ch)  = %d\n", offsetof(struct test_struct, ch)  - 4);
    printf("offsetof(struct test_struct, f1)  = %d\n", offsetof(struct test_struct, f1)  - 4);
    return 0;
}

執行結果:

offsetof(struct test_struct, num) = 0
offsetof(struct test_struct, ch)  = 4
offsetof(struct test_struct, f1)  = 8

為了加深印象,程式中刻意用 4 而非 0,所以結果都減去 4 才是偏移量;實務上當然一律用 0。

二、實際使用

#include <stdio.h>

#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)

struct test_struct {
    int num;
    char ch;
    float f1;
};

int main(void)
{
    printf("offsetof(struct test_struct, num) = %d\n", offsetof(struct test_struct, num));
    printf("offsetof(struct test_struct, ch)  = %d\n", offsetof(struct test_struct, ch));
    printf("offsetof(struct test_struct, f1)  = %d\n", offsetof(struct test_struct, f1));
    return 0;
}

執行結果:

offsetof(struct test_struct, num) = 0
offsetof(struct test_struct, ch)  = 4
offsetof(struct test_struct, f1)  = 8

要補充的是,這裡 num 之後接 char 再接 float 之所以沒有出現補白,是因為 4 的倍數剛好對齊;若成員順序改成 char 在前,就會看到 f1 的偏移被推到 8 而非 5,中間那三個位元組正是編譯器插入的 padding。這也是 offsetof 最實際的用途之一:用來檢查結構體的記憶體佈局是否符合預期,例如要與硬體暫存器或網路封包格式對齊時。

另外,「對指標 0 取值」在標準 C 中嚴格說來屬於 undefined behavior,只是實作上必然可行;正因如此,C99 之後標準函式庫已提供 中的官方 offsetof,實務上應直接用它,而非自行定義。

Copyright © Linux教程網 All Rights Reserved