C言語のcontainerof関数の使い方
C言語のcontainer_of関数は、あるメンバを含む構造体へのポインタを取得する
コンテナ_オブ関数のプロトタイプは以下のとおりです。
#define container_of(ptr, type, member) ({ \
const typeof(((type *)0)->member) *__mptr = (ptr);
(type *)((char *)__mptr - offsetof(type, member)); })
パラメータptrはメンバのポインタ、typeは構造体の型、memberは構造体内のメンバの名称です。
container_of関数の使い方は次のとおりです。
- 構造体のメンバが既知のオフセットを持つようにする。
- メンバを指すポインタ ptr に container_of 関数を適用し、それに関連する引数を渡します。
- container_of 関数は、メンバーを含む構造体へのポインタを返します。
container_of 関数の使用例を次に示します。
#include <stddef.h>
struct Student {
int id;
char name[20];
};
int main() {
struct Student s;
int *ptr_id = &s.id;
struct Student *ptr_student = container_of(ptr_id, struct Student, id);
return 0;
}
本例では、メンバー id を持つ構造体 Student を定義しています。main 関数で、メンバー id のポインタ ptr_id を取得し、関数 container_of を呼び出して、メンバー id を含む構造体のポインタ ptr_student を ptr_id から取得しています。
container_of 関数を使用する際には、メンバのオフセットがわかっていることを確認する必要があります。そうでない場合、誤った結果が得られる可能性があります。メンバのオフセットはオフセットマクロを使用して取得することができます。