[fpc-pascal] Difference between string and Tbytes as procedure arguments?
Bo Berglund
bo.berglund at gmail.com
Sun Nov 5 11:00:28 CET 2023
On Sun, 5 Nov 2023 10:36:47 +0100 (CET), Michael Van Canneyt via fpc-pascal
<fpc-pascal at lists.freepascal.org> wrote:
>> So my question is this:
>> Is there a difference in handling the arguments between string, AnsiString,
>> RawByteString and TBytes in a declaration like this:
>>
>> function TSSConnection.ParseCmdFileData(var SSCmdFile: TSSCommandFile; Buf:
>> AnsiString): boolean;
>>
>> and this:
>>
>> function TSSConnection.ParseCmdFileData(var SSCmdFile: TSSCommandFile; Buf:
>> TBytes): boolean;
>>
>> In the first instance it looks like the function receives a *copy* of the data
>
>No, but an ansistring is copy-on-write. As soon as you change it, a copy is
>made if your routine is not the only one using the string.
>
>> in the Buf argument and in the second case it receives a pointer to the actual
>> live data such that in the first case the argument source remains untouched
>> whereas in the second case the argument source is changed just as it had been
>> declared as var...
>
>That is correct. TBytes is a fancy wrapper around a pointer with some
>reference counting added to the mix.
>
>>
>> Is there a way to simply tell Delphi/FreePascal to treat also TBytes as copy
>> rather than a pointer to the real data?
>
>You must copy the data. The copy() function can be used for this.
Follow-up question:
Can I change the function declaration like this and preserve the content?
function TSSConnection.ParseCmdFileData(var SSCmdFile: TSSCommandFile; const
Buf: TBytes): boolean;
Or must I copy the argument Buf inside the function to a local BufL version?
That is what you adviced, right?
Note: I have now found another function that changes the content of the Buf
argument and it too causes havoc...
--
Bo Berglund
Developer in Sweden
More information about the fpc-pascal
mailing list