如何使用类的地址和变量的偏移量来访问类var的值?

Sal*_*dor 4 delphi pointers class-helpers delphi-xe

我需要使用他的实例和变量的偏移来访问严格私有类var值.

到目前为止尝试了这个,检查这个示例类

type
  TFoo=class
   strict private class var Foo: Integer;
   public
   constructor Create;
  end;

constructor TFoo.Create;
begin
  inherited;
  Foo:=666;
end;

//this function works only if I declare the foo var as 
//strict private var Foo: Integer;
function GetFooValue(const AClass: TFoo): Integer;
begin
  Result := PInteger(PByte(AClass) + 4)^
end;
Run Code Online (Sandbox Code Playgroud)

如您所见,函数GetFooValue仅在foo变量未声明为类var时才起作用.

问题是我必须如何修改 GetFooValue才能获得Foo声明时的值strict private class var Foo: Integer;

LU *_* RD 7

要访问严格的私有类var,Class Helper要进行救援.

示例:

type
  TFoo = class
  strict private class var
    Foo : Integer;
  end;

  TFooHelper = class helper for TFoo
  private
    function GetFooValue : Integer;
  public
    property FooValue : Integer read GetFooValue;
  end;

function TFooHelper.GetFooValue : Integer;
begin
  Result:= Self.Foo;  // Access the org class with Self
end;

function GetFooValue( F : TFoo) : Integer;
begin
  Result:= F.GetFooValue;
end;

Var f : TFoo;//don't need to instantiate since we only access class methods

begin
  WriteLn(GetFooValue(f));
  ReadLn;
end.
Run Code Online (Sandbox Code Playgroud)

更新了适合问题的示例.