Question

I recently changed my Delphi 7 IDE to Delphi XE5 (Big change). I'm working on a small client / server application and i'm having problems when trying to read an string.

My code:

Function TIOHandler.readString(Var data: String): Integer;
Var
  byteReceived: Integer;
  buff: Array Of Char;
Begin
  byteReceived := 0;
  Result := 0;
  SetLength(buff, 255);

  byteReceived := self.readBuffer(buff[0], SizeOf(buff));

  If (byteReceived > 0) Then
  Begin
    SetLength(data, SizeOf(buff));
    lstrcpyn(@data[1], @buff[0], SizeOf(buff));
    Result := byteReceived;
  End
  Else If byteReceived = SOCKET_ERROR Then
    Result := SOCKET_ERROR;
End;

Function TIOHandler.readBuffer(Var buffer; bufferSize: Integer): Integer;
Begin
  Result := recv(self.ioSocket.aSock, buffer, bufferSize, 0);
End;

I get rare symbols, looks like is character encoding problem. Can anyone tell me which is what I have wrong.

Best regards.

Was it helpful?

Solution

  1. Don use array of char for buffer, use "array of byte" instead of "array of char", it automatically makes your code independent from size of char. Alternatively you can use RawBinaryString type for binary data.

  2. SizeOf(buff) is size of pointer (4 or 8 bytes depending of target), you should use something like "Length(buff)*SizeOf(buff[0])"

  3. Don't forget that size of char is 2 in new Delphi compilers by default, it is highly recommended to read something about char/string types in Delphi.

UPDATE: You can convert String<->RawBinaryString for example like this:

function BinToString(const s: RawByteString): String;
begin
  assert(length(s) mod SizeOf(result[1])=0);
  setlength(result, length(s) div SizeOf(result[1]));
  move(s[1], result[1], length(result)*SizeOf(result[1]));
end;

function StringToBin(const s: String): RawByteString;
begin
  setlength(result, length(s)*SizeOf(s[1]));
  move(s[1], result[1], length(result));
end;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top