传递char数组作为引用指针

时间:2015-02-05 15:02:02

标签: arrays delphi pointers

我试图将array[0..512] of char作为引用指针传递给另一个函数。但是我不明白Delphi如何处理指针。

在我的按钮点击代码中,我有这个;

procedure TForm1.Button3Click(Sender: TObject);
var
  sect_size: integer;
  sector : array[0..512] of char;
  hand : THandle;
  ret: integer;
begin

  hand := open_disk('system.img', sect_size);

  ret := read_disk(hand, @sector, 0, 1, sect_size);
end;

然后,对于read_disk函数,我有这个代码;

function read_disk(hnd: THandle; var ptr:pointer; sector: int64; nsects, sectorsize: integer): DWORD;
var
  offset: int64;
  lw: DWORD;
  hgh: cardinal;
  len, rd: DWORD;
  ret: boolean;
  sc : array[0..512] of char;
begin
  offset := sector * sectorsize;

  lw := offset and $0FFFFFFFF;
  hgh := (offset SHR 32) and $0FFFFFFFF;

  lw := SetFilePointer(hnd, lw, @hgh, FILE_BEGIN);

  len := nsects * sectorsize;

  ret := ReadFile(hnd, ptr, len, rd, NIL);

  Result := rd;

end;

我正在尝试将sector变量从按钮单击传递到read_disk函数,但是Delphi会抛出一个摆动并说; [dcc32 Error] Unit1.pas(245): E2033 Types of actual and formal var parameters must be identical

此错误位于@sector

行的ret := read_disk(hand, @sector, 0, 1, sect_size);部分

由于

编辑: 工作代码现在看起来像;

function read_disk(hnd: THandle; ptr:pointer; sector: int64; nsects, sectorsize: integer): Cardinal;
var
  offset: int64;
  lw: DWORD;
  hgh: cardinal;
  len, rd: Cardinal;
  ret: boolean;
begin
  offset := sector * sectorsize;

  lw := offset and $0FFFFFFFF;
  hgh := (offset SHR 32) and $0FFFFFFFF;

  lw := SetFilePointer(hnd, lw, @hgh, FILE_BEGIN);

  len := nsects * sectorsize;

  ret := ReadFile(hnd, ptr^, len, Result, NIL);

end;

ret := read_disk(hand, @sector, 0, 1, sect_size);

1 个答案:

答案 0 :(得分:1)

发生错误是因为您启用了严格的指针检查。

更干净,更Pascal'ish的方式来做你想要的是像

type
  TMyBuffer = array[0..512] of char;

function read_disk(hnd: THandle; var Buffer: TMyByffer; 
  sector: int64; nsects, sectorsize: integer): DWORD;
var
...

然后

procedure TForm1.Button3Click(Sender: TObject);
var
  sect_size: integer;
  sector : TMyBuffer;
  hand : THandle;
  ret: integer;
begin

  hand := open_disk('system.img', sect_size);

  ret := read_disk(hand, sector, 0, 1, sect_size);
end;

此外,如果您希望继续使用不透明pointer类型,则var会变得多余,因为您会将指针传递给指针。

哦,然后你可能意味着array[0..511] of char,而不是0..512(尼特)。