Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux基礎 >> Linux教程

Linux container_of 巨集的用法解析

Linux 的 container_of 原型定義如下:

container_of(ptr, type, member);

各參數含義:

  • type —— 需要操作的資料型態,通常為結構;
  • member —— type 結構中的成員名稱;
  • ptr —— member 型態的指標變數。

舉個例子:

struct typeabc{
    int   mem0;
    float mem2;
    double mem4;
    char  mem6;
};

struct typeabc abc, *pabc;
abc.mem2 = 0.0;
float *pmem2 = &abc.mem2;   // 已知成員位址

// 透過成員變數的位址,反推出它所屬結構的首位址
pabc = container_of(pmem2, struct typeabc, mem2);

核心概念是:當你手上只有某個成員的指標時,container_of 能藉由結構型態與成員名稱,把指標還原成整個結構的起始位址,這是 Linux 核心與驅動開發中非常常見的技巧。

Copyright © Linux教程網 All Rights Reserved