Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading from TStream into a dynamic array

I have a dynamic array of records. I’d like to read N records from a TStream into that array. I presume I need to call ReadBuffer, but what should the first argument be like? @MyArray doesn’t work.

like image 563
Seva Alekseyev Avatar asked Jun 23 '26 08:06

Seva Alekseyev


1 Answers

TStream.Read() and TStream.ReadBuffer() take an untyped var as input, which means you need to pass in an actual variable for them to access.

A variable that is a dynamic array is itself just a pointer to the first array element, the actual array is stored elsewhere in memory. So you can't pass the dynamic array variable itself to Read/Buffer(). The correct "variable" to pass is the first array element, so dereference the array pointer, using either MyArray[0] or Pointer(MyArray)^ syntax.

Either way, reading a record from the stream directly into the array may or may not work, depending on how your record type is actually declared.

If the record contains only POD types, and its data alignment matches the alignment of the stream data, this will work fine:

SetLength(MyArray, N);
if (N > 0) then
  Stream.ReadBuffer(MyArray[0], N * SizeOf(MyRecord));

Or:

SetLength(MyArray, N);
Stream.ReadBuffer(Pointer(MyArray)^, N * SizeOf(MyRecord));

Otherwise, you will have to read each record individually from the stream, de-serializing any non-POD types as needed, before then copying it into your array:

var
  Rec: MyRecord;

SetLength(MyArray, N);
for I := 0 to N-1 do
begin
  // read individual members of Rec as needed...
  Stream.ReadBuffer(Rec.SomeMember, SizeOf(Rec.SomeMember));
  ...
  MyArray[I] := Rec;
end;
like image 138
Remy Lebeau Avatar answered Jun 25 '26 20:06

Remy Lebeau



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!