简体   繁体   中英

How to translate c++ code to Delphi

I'm trying to translate some C++ code to Delphi.

The C++ code deals with some arrays of Single's:

const float* const inp
const float* const prWeight

I have defined the following types to deal with them:

type
   TSingleArray = array of Single;
   PSingleArray = ^TSingleArray;

when the C code adds to the the varible like so:

inp += 5

I assume that the variable is updated with the offset of the 5'th occurence and i can set an index to 5 and access value of the 5 occurence like so:

i := 5;
PSingleArray(inp)^[i] := 0.5;

and the c code:

for (int j = 5; j; --j) {
    *inp++ += *prWeight++*ari;

can be translated to

x := 0;
for j := 5 downto 0 do
   begin
      Inc(i);
      PSingleArray(inp)^[i] := PSingleArray(inp)^[i] +  
         PSingleArray(prWeight)^[x] * ari;
   end;

is this correct?

also i'm wondering. Should:

inp[k++] = nc == 1;
inp[k++] = nc == 2;
inp[k++] = nc >= 3;

be:

 Inc(k);
 PSingleArray(inp)^[k] := Ord(nc = 1);
 Inc(k);
 PSingleArray(inp)^[k] := Ord(nc = 2);
 Inc(k);
 PSingleArray(inp)^[k] := Ord(nc = 3);

or:

 Inc(k);
 PSingleArray(inp)^[k] := Ord(nc = 1);
 PSingleArray(inp)^[k] := Ord(nc = 2);
 PSingleArray(inp)^[k] := Ord(nc = 3);

I'm just not sure that this is correct. Does anybody have a clue?

You shouldn't be attempting to do a direct translation, especially with intermingled pointer / array arithmetic.

Some notes:

Drop PSingleArray . Delphi doesn't have the implicit conversion between pointers and arrays that C has. All the arithmetic on the pointers needs to become arithmetic on an array index. Copies of pointers are copies of array indices. Array indexing on an incremented pointer becomes a summation of multiple index parts.

Some of this code is unidiomatic C, you don't have to make even more unidiomatic Delphi

for (int j = 5; j; --j) { 
    *inp++ += *prWeight++*ari;
}

// previous incrementing of inp went into i
for j := 0 to 4 do 
begin
  inp[i + j] := inp[i + j] + prWeight[j] * ari;
end;
i = i + 5;

Note that ranges in C are half open, the end index is not used.

inp[k++] = ... uses a post-increment operator. The index used is the unmodified value of k, so that becomes inp[k] := ...; Inc(k); inp[k] := ...; Inc(k); . Also note the use of >= . I wouldn't recommend just casting Boolean => Single for conversions to 1.0 and 0.0 , but I lack context to suggest a better design.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM