Sign in Join

Live chat for Free Pascal, Lazarus, Delphi and every Pascal programmer.

Mailing lists / fpc-pascal / 2017-07

BlockWrite of dynamic arrays

2 messages · 2 people ·

Reply by email Subscribe to this list Your subscription

Read-only archive. Use j and k to move between messages.

Bo Berglund

I am converting older code to move from AnsiString to TBytes as non-text data container. While doing it I am using conditionals so I don't destroy the working code until I have verified that the TBytes usage is OK.

Now I have encountered use of BlockWrite where I would like to do the following:

1) Change variable definitions from

F: File of AnsiChar;
{$IFDEF USE_ANSISTRING}
Buffer: AnsiString;
{$ENDIF}
to
F: File;
{$ELSE IFDEF USE_TBYTES}
Buffer: TBytes;
{$ENDIF}

2) Specifically set the record length to 1 using
Reset(F, 1);
and
Rewrite(F,1)

3) Change the BlockWrite command from
BlockWrite(F, Buffer[1], Length(Buffer));
to
BlockWrite(F, Buffer, Length(Buffer));

Note that I would like to *not* specify the index of the first element of the array so that the same code can work for both cases depending on conditional setting.
But I am worried that Buffer will reference a different memory location than Buffer[0].

So are these two calls equivalent when Buffer is an AnsiString or a
TBytes array:
BlockWrite(F, Buffer[0], Length(Buffer));
BlockWrite(F, Buffer, Length(Buffer));
Bo Berglund Developer in Sweden
Sven Barth
to Bo Berglund
"Bo Berglund" wrote 15 lines
3) Change the BlockWrite command from BlockWrite(F, Buffer[1], Length(Buffer)); to BlockWrite(F, Buffer, Length(Buffer)); Note that I would like to *not* specify the index of the first element of the array so that the same code can work for both cases depending on conditional setting. But I am worried that Buffer will reference a different memory location than Buffer[0]. So are these two calls equivalent when Buffer is an AnsiString or a TBytes array: BlockWrite(F, Buffer[0], Length(Buffer)); BlockWrite(F, Buffer, Length(Buffer));

Like with String you need to reference the first element with dynamic arrays, in this case Buffer[0], otherwise you'll write the management record and following unrelated data.
You can either use "Low(buffer)" as the index which *should* work with strings as well, though I don't know whether it always did... If that doesn't work simply write two overloaded inline functions that return the index of the first element depending on whether it's String or TBytes.

Regards,
Sven