There is a code written in C, I will be grateful for the help in translating it into Delphi (Pascal).

void f_print(void *uctx, const char *data, size_t length) { static int state = 0; const char *s = data; const char *prefix = (const char *)uctx; while (length != 0) { switch (state) { case 0: { if (prefix != NULL) printf(prefix); state = 1; s = data; break; } case 1: { size_t l = 0; while (*data != '\r' && *data != '\n' && length != 0) data++, length--, l++; if (l != 0) { fwrite(s, 1, l, stdout); } if (*data == '\r' || *data == '\n') state = 2; break; } case 2: { if (*data == '\r' || *data == '\n') data++, length--; else { fwrite("\r\n", 1, 2, stdout); state = 0; } break; } } } } 

Began to do this function (method) on delphi:

 procedure TfrmMain.Print(AUctx: Pointer; AData: PAnsiChar; ALength: SIZE_T); var S : PAnsiChar; prefix : PAnsiChar; state : Byte; L : Byte; begin state := 0; prefix := AUctx; S := AData; while (ALength <> 0) do begin case state of 0: begin if prefix <> nil then FrmMain.mmoOutput.Lines.Add(prefix); s := AData; state := 1; end; 1: begin l := 0; { КАК ТУТ РЕАЛИЗОВАТЬ КОД ? } end; 2: begin { КАК ТУТ РЕАЛИЗОВАТЬ КОД ? } end; end; end; end; 

I do not know how to properly implement the code on Delphi, for case (state) = 1 and 2. Can I still have problems in written code? Thanks in advance for your help!

    1 answer 1

    something like this? Well it seems necessary to rewrite, as it is, the difference is no.
    access to the value by pointer through ^ . increments and decrements through inc and dec . Pointers can also be incremented. Line wrapping and carriage return through codes #13#10 .

     while aLength <> 0 do begin case state of 1 : begin l := 0; while( (adata^ <> #13) and (adata^ <> #10) and (alength <> 0)) do begin inc(adata); dec(alength); inc(l); end; if( l <> 0) then begin write(copy(s, 1, l)); end; if( (adata^ = #13) or (adata^ = #10)) then state := 2; break; end; end; end; 

    site_t : site_t is an unsigned integer, that is, Cardinal in delphi terms.
    Some problem will be using a static variable in the method. In delphi there are no analogues to such things. That is, in your si-shnom variant, the state variable is set to 0 only at the first call, and then its value is stored between function calls. In your delphi code, you initialize it with zero each time you start it.

    Зы2: To replace a static method variable, you can either use a global variable and initialize it somewhere in the initialize section, or create a certain data type (record) in which to create a class field ( class var ). Here it will become zero itself. Sorry, this cannot be done for inline types in the procedure.

    • How else to implement case 2: Thank you! - Indie Putny
    • @IndiUTyou you have similar pieces of code in and 1-m case , do not you add 2 + 2? - teran
    • OK thanks! I was confused by the syntax C is not quite used to it ... I close the answer, thanks for the help! - Indie Putny