Delphi自行指针使用 [英] Delphi Self-Pointer usage

查看:126
本文介绍了Delphi自行指针使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在这个实例中指向我的类实例。我不能直接使用Self,我需要存储指针以供将来使用。我尝试下一个代码:

I need to get pointer to my class instance inside this instance. I can't use "Self" directly, I need store pointer for future usage. I tried next code:

type
    TTest = class(TObject)
    public
        class function getClassPointer: Pointer;
        function getSelfPointer: Pointer;
    end;

class function TTest.getClassPointer: Pointer;
begin
    Result := Pointer(Self);
end;

function TTest.getSelfPointer: Pointer;
begin
    Result := Pointer(Self);
end;

这两个结果都错了 - 这段代码:

And both result are wrong - this code:

test := TTest.Create;
Writeln('Actual object address: ', IntToHex(Integer(@test), 8));
Writeln('Class "Self" value: ', IntToHex(Integer(test.getClassPointer()), 8));
Writeln('Object "Self" value: ', IntToHex(Integer(test.getSelfPointer()), 8));

返回:

Actual object address:    00416E6C
Class "Self" value:       0040E55C
Object "Self" value:      01EE0D10

请帮我理解,这个自我的价值是什么? Self是指向此类实例的指针吗?如何使用这个指针来将来在这个对象之外使用?如何从这个值得到适当的指针?

Please, help me understand, what is this "Self" value ? Is "Self" a pointer to this class instance ? How use this pointer to future use outside of this object ? How get proper pointer from this value ?

推荐答案

你正在尝试比较三个完全不同的实体。

You're trying to compare three completely different entities.

@test返回变量测试的地址,而不是其指向的对象实例。

@test returns the address of the variable test, not the object instance that it points to.

test.getClassPointer()返回类元数据的地址,由编译器生成的常量数据结构,运行时可以找到虚拟方法表,运行时类型信息表等。类的所有实例共享相同的类元数据结构。类元数据的指针是对象实例的类型标识 - 对象知道它在运行时是什么类型。

test.getClassPointer() returns the address of the class metadata, a constant data structure generated by the compiler where the runtime can find the virtual method table, runtime type info tables, and more. All instances of a class share the same class metadata structure. The pointer to the class metadata is the object instance's type identity - it's how the object knows what type it is at runtime.

test.getSelfPointer()给你实际的地址的对象实例在内存中。两个对象实例(单独创建)将具有不同的实例地址。 test.getSelfPointer()将等于测试实例变量的内容:指针(测试)

test.getSelfPointer() gives you the actual address of the object instance in memory. Two object instances (created separately) will have different instance addresses. test.getSelfPointer() will be equal to the contents of the test instance variable: Pointer(test)

例如(伪代码,未测试):

For example (pseudocode, not tested):

type TTest = class
     end;

var test1: TTest;
    test2: TTest;

begin
  test1 = TTest.Create;  // allocates memory from the global heap, stores pointer
  test2 = test1;         // copies the pointer to the object into test2 variable
  writeln("Test1 variable points to: ", IntToHex(Integer(Pointer(test1))));
  writeln("Test2 variable points to: ", IntToHex(Integer(Pointer(test1))));
end.

这篇关于Delphi自行指针使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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