溫馨提示×

container_of宏在Linux內核中如何應用

小樊
104
2024-06-29 14:08:39
欄目: 智能運維

在Linux內核中,container_of宏通常用于從結構體中獲取包含該結構體的另一個結構體的指針。這在內核中經常用于實現鏈表、樹等數據結構。

container_of宏的定義如下:

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

在使用container_of宏時,需要傳入3個參數:指向成員變量的指針ptr、包含該成員變量的結構體類型type和成員變量在結構體中的名稱member。

以下是一個示例代碼,在這個示例中,我們定義了一個結構體struct data,其中包含一個成員變量value和一個成員變量list_entry,然后通過container_of宏從list_entry指針中獲取包含該結構體的指針:

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

struct data {
    int value;
    struct list_head list_entry;
};

int main() {
    struct data my_data;
    struct list_head *list_ptr = &my_data.list_entry;
    
    struct data *data_ptr = container_of(list_ptr, struct data, list_entry);
    
    printf("Value: %d\n", data_ptr->value);
    
    return 0;
}

在這個示例中,我們通過container_of宏從list_entry指針中獲取了包含該結構體的指針data_ptr,并打印出了value的值。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女