delphi指针地址

问题描述 投票:0回答:5

在德尔福:

如何获取指针指向的地址(0x2384293)?

var iValue := Integer;
    iptrValue := PInteger;

implementation

procedure TForm1.Button1Click(Sender: TObject);
begin
  iptrValue := @iValue;
  iValue := 32342;
  //Should return the same value:
  Edit1.Text := GetAddressOf(iptrValue);
  Edit2.Text := GetAddressOf(iValue); 

那么现实中的 GetAddress 是什么:)

delphi pointers pointer-address
5个回答
36
投票

获取某项的地址,请使用

@
运算符或
Addr
函数。您已经展示了它的正确用法。您获得了
iValue
的地址并将其存储在
iptrValue
中。

显示地址,可以使用

Format
函数将指针值转换为字符串。使用
%p
格式字符串:

Edit1.Text := Format('%p -> %p -> %d', [@iptrValue, iptrValue, iptrValue^]);

这将显示

iptrValue
变量的地址,然后是 存储在该变量中的地址 ,然后是 存储在该地址。

iptrValue
变量声明在内存中保留一些字节并将名称与它们相关联。假设第一个字节的地址是
$00002468
:

       iptrValue
       ┌──────────┐
$2468: │          │
       └──────────┘

iValue
声明保留了另一块内存,它可能与前一个声明的内存相邻。由于
iptrValue
是四个字节宽,因此
iValue
的地址将为
$0000246C
:

       iValue
       ┌──────────┐
$246c: │          │
       └──────────┘

我绘制的框现在是空的,因为我们还没有讨论这些变量保存的值。我们只讨论了变量的地址。现在来看可执行代码:您编写

@iValue
并将结果存储在
iptrValue
中,这样您就得到了:

       iptrValue
       ┌──────────┐    ┌──────────┐
$2468: │    $246c ├───→│          │
       └──────────┘    └──────────┘
       iValue
       ┌──────────┐
$246c: │          │
       └──────────┘
Next, you assign 32342 to `iValue`, so your memory looks like this:
        iptrValue
       ┌──────────┐    ┌──────────┐
$2468: │    $246c ├───→│    32342 │
       └──────────┘    └──────────┘
       iValue
       ┌──────────┐
$246c: │    32342 │
       └──────────┘

最后,当您显示上面

Format
函数的结果时,您会看到这个值:

00002468 -> 0000246C -> 32342

5
投票

只需将其转换为整数:)

IIRC,还有一个字符串格式说明符(%x?%p?),它会自动将其格式化为 8 个字符的十六进制字符串。


5
投票

这是我自己的地址函数示例:

function GetAddressOf( var X ) : String;
Begin
  Result := IntToHex( Integer( Pointer( @X ) ), 8 );
end;

使用2个变量的相同数据的示例:

type
  TMyProcedure = procedure;

procedure Proc1;
begin
  ShowMessage( 'Hello World' );
end;

var
  P : PPointer;
  Proc2 : TMyProcedure;
begin
  P := @@Proc2; //Storing address of pointer to variable
  P^ := @Proc1; //Setting address to new data of our stored variable
  Proc2; //Will execute code of procedure 'Proc1'
end;

3
投票

GetAddressOf() 将返回变量的地址。

GetAddressOf(iptrValue) - the address of the iptrValue
GetAddressOf(iValue) - the address of iValue

你想要的是指针的值。为此,将指针转换为无符号整数类型(长字,如果我没记错的话)。然后您可以将该整数转换为字符串。


2
投票

它实际上是您需要的 ULong:

procedure TForm1.Button1Click(Sender: TObject);
var iValue : Integer;
    iAdrValue : ULong;
    iptrValue : PInteger;
begin
  iValue := 32342;
  iAdrValue := ULong(@iValue);
  iptrValue := @iValue;

  //Should return the same value:
  Edit1.Text := IntToStr(iAdrValue);
  Edit2.Text := IntToStr(ULong(iptrValue)); 
  Edit3.Text := IntToStr((iptrValue^); // Returns 32342
end;

我在Delphi 2006中没有找到GetAddressOf函数,好像是VB函数?

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.