如何使用类的地址和变量的偏移量来访问类 var 的值?
我需要使用类的实例和变量的偏移量来访问类的严格私有类 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
的值
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;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
要访问严格的私有类变量,可以使用 Class Helper 来救援。
示例:
更新了示例以适应问题。
To access a strict private class var,
Class Helper
to rescue.Example :
Updated example to fit the question.
你确实不能那样做。类 var 被实现为全局变量,并且它的内存位置与类 VMT 的位置(类引用指向的内容)没有任何可预测的关系,类 VMT 位于 <进程内存的常量数据区域。
如果您需要从类外部访问此变量,请声明一个将其引用为支持字段的
类属性
。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.