title: Delphi Assembly Function Returning a Long String
body: <p>I am trying to learn inline assembly programming in Delphi, and to this end I have found <a href="http://www.delphi3000.com/articles/article_3766.asp" rel="nofollow noreferrer">this article</a> highly helpful.</p>
  
  <p>Now I wish to write an assembly function returning a long string, specifically an <code>AnsiString</code> (for simplicity). I have written</p>
  
  <pre><code>function myfunc: AnsiString;
  asm
    // eax = @result
    mov edx, 3
    mov ecx, 1252
    call System.@LStrSetLength
    mov [eax + 0], ord('A')
    mov [eax + 1], ord('B')
    mov [eax + 2], ord('C')
  end;
  </code></pre>
  
  <p>Explanation:</p>
  
  <p>A function returning a string has an invisible <code>var result: AnsiString</code> (in this case) parameter, so, at the beginning of the function, <code>eax</code> should hold the address of the resulting string. I then set <code>edx</code> and <code>ecx</code> to 3 and 1252, respectively, and then call <code>System._LStrSetLength</code>. In effect, I do</p>
  
  <pre><code>  _LStrSetLength(@result, 3, 1252)
  </code></pre>
  
  <p>where 3 is the new length of the string (in characters = bytes) and 1252 is the standard <a href="http://msdn.microsoft.com/en-us/library/dd317756(VS.85).aspx" rel="nofollow noreferrer">windows-1252</a> codepage.</p>
  
  <p>Then, knowing that <code>eax</code> is <a href="http://docwiki.embarcadero.com/RADStudio/en/Internal_Data_Formats#Long_String_Types" rel="nofollow noreferrer">the address of the first character of the string</a>, I simply set the string to "ABC". But it does not work - it gives me nonsense data or EAccessViolation. What is the problem?</p>
  
  <h1>Update</h1>
  
  <p>Now we have two seemingly working implementations of <code>myfunc</code>, one employing <code>NewAnsiString</code> and one employing <code>LStrSetLength</code>. I cannot help but wonder if both of them are correct, in the sense  that they do not mess upp Delphi's internal handling of strings (reference counting, automatic freeing, etc.).</p>