Delphi指针

2018-10-31

unit Unit1;

interface

uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;

type
PRec= ^TRec;
TRec= record
FInt1: Integer;
FInt2: Integer;
FInt3: Integer;
end;

TCls= class
private
FInt1: Integer;
FInt2: Integer;
FStr: string;
public
property Int1: Integer read FInt1 write FInt1;
end;

TForm1 = class(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;

var
Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
var
lRec, lrec2: TRec;
lPchar: PChar;
lPRec: PRec;
lP: Pointer; //无类型指针
lCls: TCls;
begin
//结构体之间的拷贝 及结构体与缓冲区转化
//考虑的时候将数据看作是一个整体内存块即刻
lRec.FInt1:= 11;
lrec.FInt2:= 12;
lrec.FInt3:= 13;
lPchar:= PChar(@lrec); //将lrec的地址转为PChar类型的指针
lPRec:= PRec(lPChar); //在将PChar类型的指针转为PRec
ShowMessage(Format('Int1=%d; Int2=%d; Int3=%d',[lPrec.FInt1, lPrec.FInt2, lPrec.FInt3]));
Move(lRec, Lrec2, SizeOf(lrec));//源 目的 大小
ShowMessage(Format('Int1=%d; Int2=%d; Int3=%d',[Lrec2.FInt1, Lrec2.FInt2, Lrec2.FInt3]));
//无类型指针与对象之间的转换
lCls:= TCls.Create;
lCls.Int1:= 100;
lp:= lCls;
ShowMessage(Format('Int1=%d',[TCls(lp).FInt1]));

//无类型指针与结构体
lp:= lPchar;
ShowMessage(Format('Int1=%d',[PRec(lp)^.FInt1]));
end;

end.

阅读5