rustam
rustam

Reputation: 21

IdUdpClient how to accept data in a dynamic array

This code accepts data in a static array.

TMyRec = record
   MyArray: array[0..1, 0..10] of double;
end;

MyClient: TIdUDPClient;
MyRec: TMyRec;
Buffer: TIdBytes;

SetLength(Buffer, SizeOf(MyRec));
if MyClient.ReceiveBuffer(Buffer, 1) > 0 then
begin
     BytesToRaw(Buffer, MyRec, SizeOf(MyRec));
end;

And how do it in a dynamic array.

TMyRec = record
   MyArray: array of array of double;
end;

Upvotes: 0

Views: 125

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 598134

First off, you are allocating Buffer to SizeOf(MyRec) bytes (176 for the static array version), but then you are only reading 1 byte from the UDP socket. You need to replace 1 with SizeOf(MyRec) or Length(Buffer) instead, to match the allocation.

That being said, an array of array of ... is not stored in one contiguous block of memory. It is actually an array of pointers to other arrays that are scattered all over memory. So, to do what you are asking, you would have to do something like this:

type
  TMyRec = record
    MyArray: array of array of double;
  end;

const
  BytesPerArr = SizeOf(Double) * 11;

var
  MyClient: TIdUDPClient;
  MyRec: TMyRec;
  Buffer: TIdBytes;

...

SetLength(MyRec.MyArray, 2, 11);
SetLength(Buffer, 2 * BytesPerArr);

if MyClient.ReceiveBuffer(Buffer, Length(Buffer)) > 0 then
begin
  Move(Buffer[0], MyRec.MyArray[0][0], BytesPerArr);
  Move(Buffer[BytesPerArr], MyRec.MyArray[1][0], BytesPerArr);
end;

Upvotes: 1

Related Questions