unit Unit1;

interface

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

type
  TForm1 = class(TForm)
    Button1: TButton;
    procedure FormCreate(Sender: TObject);
    procedure Button1Click(Sender: TObject);
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

type
  TArr = array of Int64; {先把需要的动态数组数组定义成一个类型, 因为下面需要类型转换}
var
  arr1,arr2: TArr;       {两个等待测试的数组变量}
  p: Pointer;            {该指针用于中转数组中的数据}

{先给第一个数组赋测试值}
procedure TForm1.FormCreate(Sender: TObject);
var
  i: Integer;
begin
  for i := 0 to 1000 - 1 do
  begin
    SetLength(arr1, Length(arr1)+1);
    arr1[High(arr1)] := i * 2;
  end;
  {抽查显示}
  ShowMessage(IntToStr(arr1[9])); {18}
end;

{复制到第二个数组}
procedure TForm1.Button1Click(Sender: TObject);
var
  size: Cardinal;
begin
  size := Length(arr1) * SizeOf(arr1[0]); {源数组大小}
  GetMem(p, size);                        {根据源数组大小分配内存}
  CopyMemory(p, arr1, size);              {复制}
  arr2 := TArr(p);                        {转换}
  {抽查显示}
  ShowMessage(IntToStr(arr2[9]));         {18}
end;

end.


假定数组元素是个结构, 再测试一次:
unit Unit1;

interface

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

type
  TForm1 = class(TForm)
    Button1: TButton;
    procedure FormCreate(Sender: TObject);
    procedure Button1Click(Sender: TObject);
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

type
  TRec = record
    str: string;
    int: Integer;
  end;

  TArr = array of TRec;

var
  arr1,arr2: TArr;
  p: Pointer;

procedure TForm1.FormCreate(Sender: TObject);
var
  i: Integer;
begin
  for i := 0 to 1000 - 1 do
  begin
    SetLength(arr1, Length(arr1)+1);
    arr1[High(arr1)].str := IntToStr(i);
    arr1[High(arr1)].int := i * 2;
  end;
  ShowMessageFmt('%s,%d',[arr1[9].str, arr1[9].int]); {9,18}
end;

procedure TForm1.Button1Click(Sender: TObject);
var
  size: Cardinal;
begin
  size := Length(arr1) * SizeOf(arr1[0]);
  GetMem(p, size);
  CopyMemory(p, arr1, size);
  arr2 := TArr(p);
  ShowMessageFmt('%s,%d',[arr2[9].str, arr2[9].int]); {9,18}
end;

end.

posted on 2008-10-14 10:38  万一  阅读(6418)  评论(14编辑  收藏  举报