C宏 offsetof(type, member) 该结构体成员相对于该结构体的偏移量
#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
那Delphi版的表示式怎么写呢
NativeUInt(@Record(nil^).member)
C宏 container_of() 通过结构体成员得到该结构体地址
那Delphi版的表示式怎么写呢
NativeUInt(@member)-NativeUInt(@Record(nil^).member)
例子如下:
type
TTestRecord=record
a:Integer;
b:Integer;
c:string;
d:string;
end;
procedure TForm2.btn1Click(Sender: TObject);
var
p,pb,pd:Pointer;
t:TTestRecord;
n:NativeUInt;
begin
p:=@t;
pb:=@t.b;
pd:=@t.d;
mmo1.Lines.Add('record addr:='+IntToStr(NativeUInt(p)));
mmo1.Lines.Add('record.b addr:='+IntToStr(NativeUInt(pb)));
mmo1.Lines.Add('record.d addr:='+IntToStr(NativeUInt(pd)));
n:= NativeUInt(@TTestRecord(nil^).b);
mmo1.Lines.Add('record.b len:='+IntToStr(n));
n:= NativeUInt(@TTestRecord(nil^).d);
mmo1.Lines.Add('record.d len:='+IntToStr(n));
n:=NativeUInt(pb)-NativeUInt(@TTestRecord(nil^).b);
mmo1.Lines.Add('record addr(Calculated by member b):='+IntToStr(n));
n:=NativeUInt(pd)-NativeUInt(@TTestRecord(nil^).d);
mmo1.Lines.Add('record addr(Calculated by member d):='+IntToStr(n));
end;
运行结果如下图