BlockWrite of dynamic arrays

classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate

BlockWrite of dynamic arrays

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

_______________________________________________
fpc-pascal maillist  -  [hidden email]
http://lists.freepascal.org/cgi-bin/mailman/listinfo/fpc-pascal
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate

Re: BlockWrite of dynamic arrays

Free Pascal - General mailing list

Am 30.07.2017 08:21 schrieb "Bo Berglund" <[hidden email]>:
> 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


_______________________________________________
fpc-pascal maillist  -  [hidden email]
http://lists.freepascal.org/cgi-bin/mailman/listinfo/fpc-pascal
Loading...