gpt4 book ai didi

Delphi自指针的使用

转载 作者:行者123 更新时间:2023-12-03 15:05:51 24 4
gpt4 key购买 nike

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

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;

两个结果都是错误的 - 这段代码:

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 ”值(value)是什么? “Self”是指向此类实例的指针吗?如何使用这个指针来将来在这个对象之外使用?如何从该值获取正确的指针?

最佳答案

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

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

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

test.getSelfPointer() 为您提供内存中对象实例的实际地址。两个对象实例(单独创建)将具有不同的实例地址。 test.getSelfPointer() 将等于测试实例变量的内容:Pointer(test)

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

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自指针的使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3824136/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com