Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I Need to access a strict private class var value of a class using his instance and a offset to the variable.

so far tried this , check this sample class

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;

As you see the function GetFooValue works only when the foo variable is not declarated like a class var.

The question is how I must modify the GetFooValue in order to get the value of Foo when is declarated like strict private class var Foo: Integer;

like image 912
Salvador Avatar asked Jan 19 '23 00:01

Salvador


2 Answers

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.

like image 154
LU RD Avatar answered Feb 20 '23 10:02

LU RD


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.

like image 34
Mason Wheeler Avatar answered Feb 20 '23 11:02

Mason Wheeler