溫馨提示×

如何用container_of宏實(shí)現(xiàn)類型轉(zhuǎn)換

小樊
81
2024-09-02 19:42:57
欄目: 編程語言

container_of 是一個(gè)宏,用于在 Linux 內(nèi)核和其他 C 語言項(xiàng)目中實(shí)現(xiàn)類型轉(zhuǎn)換

以下是 container_of 宏的定義:

#define container_of(ptr, type, member) ({ \
    const typeof(((type *)0)->member) *__mptr = (ptr); \
    (type *)((char *)__mptr - offsetof(type, member)); })

這個(gè)宏接受三個(gè)參數(shù):

  1. ptr:指向成員變量的指針。
  2. type:包含成員變量的結(jié)構(gòu)體或聯(lián)合體的類型。
  3. member:結(jié)構(gòu)體或聯(lián)合體中成員變量的名稱。

宏的工作原理如下:

  1. 首先,它計(jì)算出給定成員在其所屬結(jié)構(gòu)體或聯(lián)合體中的偏移量。這是通過 offsetof(type, member) 函數(shù)實(shí)現(xiàn)的,它返回成員在類型中的字節(jié)偏移量。
  2. 然后,它將給定的成員指針減去該偏移量,得到結(jié)構(gòu)體或聯(lián)合體的起始地址。
  3. 最后,它將計(jì)算出的地址強(qiáng)制轉(zhuǎn)換為目標(biāo)類型的指針。

以下是一個(gè)使用 container_of 宏實(shí)現(xiàn)類型轉(zhuǎn)換的示例:

#include<stdio.h>
#include <stddef.h>

typedef struct {
    int id;
    char name[20];
} Student;

int main() {
    Student student = {1, "Alice"};
    int *id_ptr = &student.id;

    // 使用 container_of 宏將 int 指針轉(zhuǎn)換為 Student 指針
    Student *student_ptr = container_of(id_ptr, Student, id);

    printf("Student ID: %d\n", student_ptr->id);
    printf("Student Name: %s\n", student_ptr->name);

    return 0;
}

在這個(gè)示例中,我們有一個(gè) Student 結(jié)構(gòu)體,包含 idname 兩個(gè)成員。我們創(chuàng)建了一個(gè) Student 實(shí)例,并獲取了 id 成員的指針。然后,我們使用 container_of 宏將 int 指針轉(zhuǎn)換為 Student 指針,以便訪問整個(gè)結(jié)構(gòu)體的成員。

0