聘我网

新概念招聘3.0

如何从结构的某个域地址得到结构的起始地址?

vote up0vote downstar
struct test 
{
  int a;
  int b;
  float c;
}

如何从struct testb的地址反推struct test的地址?

 

4 个答复

vote up0vote downcheck

windows ddk提供了个经典的宏:

#define CONTAININT_RECORD(address, type, field) \
             ((type*)((PCHAR)(address) - (PCHAR)(&((type*)0)->field)))

linux内核也有个同样功能的宏:

#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)

这里其实有个小技巧,即C的裸块,

看个例子:

int i = ({ 3 + 4 ;});
printf("i=%d\n", i);

输出:

i=7

({})中的最后一个语句的值会作为整块的值。

参考:

浅析container_of(ptr, type, member)

链接
vote up0vote down

You've got it in one. Couldn't have put it better.

链接
vote up0vote down

Got it! Thanks a lot again for helpnig me out!

链接
vote up0vote down

Grade A stuff. I'm unquestionably in your debt.

链接

您的回答





不是您要找的问题? 浏览其他含有标签 的问题或者 自己问个.