2

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.
Andrey Atapin
  • 7,745
  • 3
  • 28
  • 34
user558126
  • 1,303
  • 3
  • 21
  • 42
  • 2
    1) `unsigned char` = `Byte`, not `Char` (blame Ritchie for that), 2) `new` can be translated to `GetMem()` or with intermediate type which declares size 3) for loop is straightforward – Premature Optimization Nov 01 '11 at 13:42

2 Answers2

6

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;
Rob Kennedy
  • 161,384
  • 21
  • 275
  • 467
Arnaud Bouchez
  • 42,305
  • 3
  • 71
  • 159
1

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];
David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490