var
S: string;
begin
SetLength(S, MAX_SIZE);// when casting to a PChar, be sure the string is not empty
SetLength(S, GetModuleFilename(0, PChar(S), Length(S)));
// statements
end;
To eliminate the overhead of copying the buffer, you can cast the string to a PChar (if you are certain that the routine does not need the PChar to remain in memory). http://docwiki.embarcadero.com/RADStudio/en/Passing_a_Local_Variable_as_a_PChar
We have a string and it will remain in memory until its reference count decremented to 0, so it will not be removed in the course of scope.
So, why do we need PChar
to remain in memory? Is there some API function that require the exact same PChar
reference that is passed to another API function previously?
Especially i am considering the sample code. So, the question must be "why would a routine need a PChar(type-cast from a string) passed to it remain in memory after it returns?". Async i/o routines, or an async method that access the passed pchar after the caller returns, or modify of a global string by another thread are good reasons.