将unsigned char *buf=NULL转换为Pascal

Translate unsigned char *buf=NULL to Pascal?

本文关键字:NULL 转换 Pascal buf unsigned char      更新时间:2023-10-16

我在Borland Delphi工作,我在Borland c++ Builder中有几行代码。我想把这些行翻译成Delphi源代码。

unsigned char *buf=NULL;
buf=new unsigned char[SPS*2];
for (i=0; i<SPS*2; i++)
   buf[i]=2;

……

answers=buf[2];

我想用这个buf赋一个PCHar值;

a:PCHar;
a:=buf.

事实上,在:

unsigned char *buf=NULL;
buf=new unsigned char[SPS*2];

第一个赋值*buf=NULL可以翻译为buf := nil,但它是纯粹的死代码,因为buf指针的内容立即被new函数覆盖。

所以你的C代码可以翻译成这样:

var buf: PAnsiChar;
    i: integer;
begin
  Getmem(buf,SPS*2);
  for i := 0 to SPS*2-1 do
    buf[i] := #2;
...
  Freemem(buf);
end;

一个更符合delphi习惯的版本可能是:

var buf: array of AnsiChar;
    i: integer;
begin
  SetLength(buf,SPS*2);
  for i := 0 to high(buf) do
    buf[i] := #2;
  ...
  // no need to free buf[] memory (it is done by the compiler)
end;

或直接:

var buf: array of AnsiChar;
    i: integer;
begin
  SetLength(buf,SPS*2);
  fillchar(buf[0],SPS*2,2);
  ...
  // no need to free buf[] memory (it is done by the compiler)
end;

也许像这样:

var
  buf: array of AnsiChar;
  a: PAnsiChar;
...
SetLength(buf, SPS*2);
FillChar(buf[0], Length(buf), 2);
a := @buf[0];

不知道answers是什么,但是,假设它是你的c++代码中的char,那么你会这样写:

var
  answers: AnsiChar;
...
answers := buf[2];