How can access the value of a class var using the address of the class and a offset to the variable?

混江龙づ霸主 提交于 2019-12-05 14:43:50
LU RD

To access a strict private class var, Class Helper to rescue.

Example :

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.

Updated example to fit the question.

You really can't do it that way. A class var is implemented as a global variable, and its memory location doesn't have any predictable relationship to the location of the class VMT (what the class reference points to), which is located in the constant data region of your process's memory.

If you need access to this variable from outside the class, declare a class property that references it as its backing field.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!