delphi指针地址

Acr*_*ron 13 delphi pointers pointer-address

在德尔福:

如何获得指针指向的地址(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); 
Run Code Online (Sandbox Code Playgroud)

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

Rob*_*edy 33

获取某些内容的地址,请使用@运算符或Addr函数.您已经证明了正确使用它.你得到了地址iValue并将其存储起来iptrValue.

显示地址,可以使用该Format函数将指针值转换为字符串.使用%p格式字符串:

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

这将显示iptrValue变量的地址,然后显示存储在该变量中的地址,然后显示存储在该地址的.

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

       iptrValue
       +----------+
$2468: |          |
       +----------+
Run Code Online (Sandbox Code Playgroud)

iValue声明保留另一块内存,它可能将毗邻先前声明的记忆.由于iptrValue是四个字节宽,地址iValue将是$0000246C:

       iValue
       +----------+
$246c: |          |
       +----------+
Run Code Online (Sandbox Code Playgroud)

我现在绘制的方框是空的,因为我们还没有讨论这些变量的值.我们只讨论了变量的地址.现在到可执行代码:你编写@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 |
       +----------+
Run Code Online (Sandbox Code Playgroud)

最后,当您Format从上面显示函数的结果时,您会看到以下值:

00002468 -> 0000246C -> 32342
Run Code Online (Sandbox Code Playgroud)

  • 很棒的解释! (3认同)

moo*_*baa 5

只需将其转换为整数:)

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


小智 5

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

function GetAddressOf( var X ) : String;
Begin
  Result := IntToHex( Integer( Pointer( @X ) ), 8 );
end;
Run Code Online (Sandbox Code Playgroud)

使用 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;
Run Code Online (Sandbox Code Playgroud)