如何使用类的地址和变量的偏移量访问类var的值? [英] How can access the value of a class var using the address of the class and a offset to the variable?

查看:117
本文介绍了如何使用类的地址和变量的偏移量访问类var的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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;

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

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

问题是,当像strict private class var Foo: Integer;这样声明时,如何必须修改GetFooValue以获得Foo的值

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;

推荐答案

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

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

示例:

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.

这篇关于如何使用类的地址和变量的偏移量访问类var的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆