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:[email protected];
pd:[email protected];
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;
運行結果如下圖