Search code examples
socketsdelphiwinsockdelphi-10-seattlerecv

recv(): Constant object cannot be passed as var parameter (on second arg of this function)


I need make a Delphi version of following C code and now i got the error saying that "not is allowed": a value of PByte + a Integer value, passed on second arg of recv() function.

Have you some idea about a possible solution?

This is C version:

DWORD size;
BYTE *data = (BYTE *) malloc(size);
int   totalRead = 0;
do
{
  int read = recv(s, (char *) data + totalRead, size - totalRead, 0);
  if(read <= 0)
     goto exit;
  totalRead += read;
} while(totalRead != size);

And here was my attempt:

var
 data: PByte;
 read, bytesRead: Integer;
 Size: DWORD;

//...

data := PByte(AllocMem(Size));
bytesRead := 0;

 repeat
   read := recv(Sock, data + bytesRead, Size - Cardinal(bytesRead), 0);
   if read <= 0 then
   begin
    Writeln('0 received, exiting...');
     Exit;
   end;
   bytesRead := bytesRead + read;
 until DWORD(bytesRead) = Size;

Solution

  • var
      data: PByteArray;
    //...
    
    data := PByteArray(AllocMem(Size));
    bytesRead := 0;
    
    repeat
       read := recv(Sock, data[bytesRead], Size - Cardinal(bytesRead), 0);