Linux内核中常用的两个宏定义
#ifndef offsetof
#define offsetof(TYPE,MEMBER) ((size_t) & ((TYPE*)0)->MEMBER)
#endif
#ifndef container_of
#define contatiner_of(ptr,type,member)({ \
const typeof(((type*)0)->member)* __mptr = (ptr); \
(type*)((char*) __mptr - offsetof(type, member)); })
#endif
offsetof用于计算TYPE结构体重MEMBER成员的偏移位置。
-编译器清楚的知道结构体成员变量的便宜位置
-通过结构体变量首地址与偏移量定位成员变量
#include <QCoreApplication>
#ifndef offsetoff
#define offsetoff(TYPE,MEMBER) ((size_t) & ((TYPE*)0)->MEMBER)
#endif
struct ST
{
int i;
int j;
char c;
};
void func(struct ST* pst)
{
int *pi = &(pst->i);
int* pj = &(pst->j);
char* pc = &(pst->c);
printf("pst = %p\n" , pst);
printf("pi = %p\n",pi);
printf("pj = %p\n",pj);
printf("pc =