title: Why would a routine need a PChar(type-cast from a string) passed to it remain in memory after it returns?
body: <pre><code>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;
  </code></pre>
  
  <blockquote>
    <p>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).
    <a href="http://docwiki.embarcadero.com/RADStudio/en/Passing_a_Local_Variable_as_a_PChar" rel="nofollow">http://docwiki.embarcadero.com/RADStudio/en/Passing_a_Local_Variable_as_a_PChar</a></p>
  </blockquote>
  
  <p>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 <code>PChar</code> to remain in memory? Is there some API function that require the exact same <code>PChar</code> reference that is passed to another API function previously?</p>
  
  <p>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.</p>