[英]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. 我需要使用他的实例和变量的偏移来访问类的严格私有类var值。
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. 如您所见,函数GetFooValue仅在foo变量未声明为类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;
问题是我必须如何修改
GetFooValue
以获得Foo
的值,当声明为strict private class var Foo: Integer;
To access a strict private class var, Class Helper
to rescue. 要访问严格的私有类var,要使用
Class Helper
进行救援。
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.
类var实现为全局变量 ,其内存位置与类VMT的位置(类引用指向的位置)没有任何可预测的关系,该位置位于进程内存的常量数据区域中。
If you need access to this variable from outside the class, declare a class property
that references it as its backing field. 如果需要从类外部访问此变量,请声明一个引用它作为其后备字段的
class property
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.