Translate unsigned char *buf=NULL to Pascal?

1.1k views Asked by At

I'm working in Borland Delphi, and i have a few lines code in Borland C++ Builder. I would like to translate these lines into Delphi source.

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

... ....

answers=buf[2];

I would like to assign a PCHar value with this buf;

a:PCHar;
a:=buf.
2

There are 2 answers

4
David Heffernan On BEST ANSWER

Perhaps like this:

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

No idea what answers is, but, assuming it is a char in your C++ code then you would write it like this:

var
  answers: AnsiChar;
...
answers := buf[2];
0
Arnaud Bouchez On

In fact, in:

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

The first assignment *buf=NULL can be translated as buf := nil but it is pure dead code, since buf pointer content is immediately overwritten by the new function.

So your C code may be translated as such:

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

A more Delphi-idiomatic version may be:

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;

or directly:

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;