container_of用法及び実現

1711 ワード

container_of      ,    struct          ,       struct    (       ,list)
struct DDD {

        int a;

        int b;

        int c;

        int d;};struct DDD  ddd;
|------------|  <-------      

|      a         |

|------------|

|      b         |

|------------|

|      c         |  <-------      

|------------|

|      d         |

|------------|
 
  
//       

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

#define container_of(ptr, type, member) ({                      \

        const typeof(((type *)0)->member) * __mptr = (ptr);     \

        (type *)((char *)__mptr - offsetof(type, member)); })



int main()

{

   printf("ddd  is %p and ddd.c is %p \r
",&ddd,&ddd.c); struct DDD * p= container_of(&ddd.c,struct DDD,c); printf("calc p is %p \r
",p); return 0; } /* output: ddd is 0x601030 and ddd.c is 0x601038 calc p is 0x601030 */