【问题标题】:How can access the value of a class var using the address of the class and a offset to the variable?如何使用类的地址和变量的偏移量来访问类 var 的值?
【发布时间】:2011-12-18 21:12:39
【问题描述】:

我需要使用他的实例和变量的偏移量来访问一个类的 strict private class 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;

如您所见,函数 GetFooValue 仅在 foo 变量未像类 var 那样声明时才起作用。

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

【问题讨论】:

  • 只是一些随机猜测:你试过没有+ 4吗?如果你在调用 GetFooValue 之前创建了一个 TFoo 类型的对象(也就是说,如果你“使用类”)会发生什么?
  • 大概你没有可用的源代码?对吗?
  • @DavidHeffernan,是的,没错,我只有班级的声明。和 dcu 文件。
  • 我可以使用指针(指向实例)和字段或属性的偏移量访问目标类的所有严格私有成员,但声明的 class var 除外。
  • 如果您没有来源,那么您就不走运了。类 var 不是字段,它们是全局变量,因此您无法通过字段结构黑客攻击它们。这也是你永远不应该使用没有来源的库的另一个原因。

标签: delphi pointers delphi-xe class-helpers


【解决方案1】:

要访问严格的私有类 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.

更新示例以适应问题。

【讨论】:

【解决方案2】:

你真的不能那样做。类 var 被实现为一个全局变量,它的内存位置与类 VMT 的位置(类引用指向的位置)没有任何可预测的关系,它位于 常量数据 进程内存的区域。

如果您需要从类外部访问此变量,请声明一个 class property,将其作为其支持字段引用。

【讨论】:

  • 这里帮不上忙,因为萨尔瓦多没有来源。
猜你喜欢
  • 2020-02-24
  • 1970-01-01
  • 1970-01-01
  • 2020-09-18
  • 1970-01-01
  • 2021-07-23
  • 2020-05-20
  • 2021-01-05
相关资源
最近更新 更多