零指针和结构体偏移量

来源:互联网 发布:什么是程序员考试 编辑:程序博客网 时间:2024/06/02 23:40

零指针和结构体偏移量

转自:http://hi.baidu.com/debugtime/item/42ce11ca5d063d24ef4665c6


定义一个结构体

struct A
{
...

int a;
char b;
short c;

...

}

其中已知int a=100;

取得a的地址 int* address=&a

把0强制转换为A类型的指针(A*)0,则得到一个理论上的以基址0开始的A结构体,

则可以通过&((A*)0->a)的到这个假想结构体的a的地址,由于基址为0,也就是

得到了a元素在结构体中的偏移量,结合之前取得的a的地址int* address;

address-&((A*)0->a),即得到该结构体的基址。强制转换为A类型即可,如下:

(A*)(address-&((A*)0->a)),

----------------------------------------------------------------------------------------------------

DDK中有这样一个宏:

#define CONTAINING_RECORD(address,type,field) ((type*)((PCHAR)(address)-(ULONG_PTR)(&((type*)0)->field)))

就是根据这个原理来获取结构实例基地址的。

CONTAINING_RECORD 宏返回一个结构实例的基地址,该结构的类型和结构所包含的一个域(成员)地址已知。

PCHAR CONTAINING_RECORD(
IN PCHAR Address,
IN TYPE Type,
IN PCHAR Field
);
Parameters

参数
Address
Pointer to a field in an instance of a structure of type Type.
指向Type类型结构实例中某域(成员)的指针。
Type
The name of the type of the structure whose base address is to be returned. For example, type IRP.
需要得到基地址的结构实例的结构类型名。
Field
The name of the field pointed to by Address and which is contained in a structure of type Type.
Type类型结构包含的域(成员)的名称。


Return Value

返回值

Returns the address of the base of the structure containing Field.

返回包含Field域(成员)的结构体的基地址
原创粉丝点击