Doing
MyPchar = PChar(MyAnsiString);
is fine.
So long as MyPchar is only used while
- MyAnsiString is not changed / not assigned to
- MyAnsiString does not go out of scope (e.g. local var)
- And you do not do: MyPchar[n] := '?'; // changes the string too, and all shared instances of the string
Doing the opposite is allowed to. But
does copy the entire memory of the text to which the PChar points.
And not only does it make a copy, it has to search for the terminator #0 first.
Which also means, if your string contains a #0 in the middle, then you loose data.
That can be time consuming.
As for your record, have you considered to use
type
PAnsiStrnig = ^AnsiString;
foo = record
...
case
...
StringData: PAnsiString
Of course, since it points to the original string, the same rules apply
- the original string must be kept valid
- a copy must be made before either is changed
A copy can be made before passing the string
var ps: PAnsiString;
begin
new(ps);
ps^ := WhateverString;
And before you dispose the pointer
ps^ := ''; // make sure ps^ no longer has a ref (counted ref) to the string
dispose(ps);
Of course the difference to having a string in your record is, that PAnsiString is not automatically released.So if your record goes out of scope, then the string is not released. You need to assign '' to the dereferenced pointer. (If you have several copies of the pointer, then the last one that goes out of scope)