container_of関数の使い方は何ですか?
container_ofはC言語のマクロであり、構造体のメンバーのポインタを使って、そのメンバーを含む構造体のポインタを取得するために使用されます。
以下はその使用法です。
#define container_of(ptr, type, member) \
((type *)((char *)(ptr) - offsetof(type, member)))
パラメーター説明:
- ptrは、構造体の特定のメンバーを指すポインターです。
- type: 構造体の種類。
- メンバー:構造体内のメンバーの名前。
container_ofマクロは、offsetofマクロを使用して構造体内のメンバーのオフセットを計算し、その後、メンバーポインターからオフセットを減算して構造体のポインターを取得します。
container_of マクロを使用した例を以下に示す:
#include <stddef.h>
struct Person {
char name[20];
int age;
};
int main() {
struct Person p = {"John Doe", 25};
int *p_age = &p.age;
struct Person *p_ptr = container_of(p_age, struct Person, age);
printf("Name: %s\n", p_ptr->name);
printf("Age: %d\n", p_ptr->age);
return 0;
}
結果出力:
Name: John Doe
Age: 25
上記の例では、container_of マクロを使用して、p.ageのポインタp_ageを介して構造体struct Personに含まれるメンバーのポインタp_ptrを取得し、その後、構造体内の他のメンバーにアクセスできます。