Bootstrap

list_entry(ptr, type, member) 与 container_of

 

#define list_entry(ptr, type, member) /
     container_of(ptr, type, member)

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

 #define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)

这个linux的双向列表中的一个宏定义,目的是根据type类型的结构体成员的指针ptr,获取ptr所在的结构体实例对象的首地址,看实例分析吧。

 

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct test_
{
    int a;
    int b;
}test;

int main()
{
    test t;
    test *p = &t; 
    printf("address t:%p\n", p); 

    test *pt = (test *)0;
    unsigned long offset_member =  (unsigned long) &((test *)0)->b;
    printf("offset_a:%ld\n", offset_member);

    int *ptr = &t.b;
  
;