container_of的使用

contanier_of是Linux内核中常用的宏,用于从包含在某个结构中的指针获得结构本身的指针,通俗地讲就是通过结构体变量中某个成员的首地址进而获得整个结构体的地址

正确的使用如下:

#include 
#include 
#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
#define container_of(ptr, type, member) ({      \
    const typeof( ((type *)0)->member ) *__mptr = (ptr); \
    (type *)( (char *)__mptr - offsetof(type,member) );})  

struct test_struct {  
    int num;  
    char ch;  
    float fl;  
};  
  
int main(void)  
{  
    struct test_struct init_test_struct = { 99, 'C', 59.12 };  
  
    char *char_ptr = &init_test_struct.ch;  
  
    struct test_struct *test_struct = container_of(char_ptr, struct test_struct, ch);  
      
    printf(" test_struct->num = %d\n test_struct->ch = %c\n test_struct->fl = %f\n",   
        test_struct->num, test_struct->ch, test_struct->fl);  
      
    return 0;  
}  



参考:http://blog.csdn.net/npy_lp/article/details/7010752

你可能感兴趣的:(Linux下驱动开发)