Call dotNET from Delphi and return a string : <p>How does a Delphi application call an exported function (non-COM) dotNET assembly and have the function return a string?</p>

<p>COM is not a possible solution for my particular application. I have control over both ends of the call.</p>

<h2>What I have tried so far - Delphi client side</h2>

<pre><code>type
  TStrProc = procedure( var x: widestring); stdcall;

function TryIt: string;
var
  Handle: THandle;
  Proc: TStrProc;
  InData: widestring;
  OutData: widestring;
begin
  Handle    := LoadLibrary( 'DelphiToDotNet.dll');
  if Handle = 0 then exit;
  @Proc := GetProcAddress( Handle, 'StrProc');
  if @Proc &lt;&gt; nil then
    begin
    InData := 'input';
    Proc( InData);
    OutData := InData;
    end;
  FreeLibrary( Handle);
  result := OutData
end;
</code></pre>

<h2>dotNET dll side</h2>

<pre><code>public class DotNetDllClass
{
  [DllExport]
  public static string StrProc(ref string s)
  {
      return "Hello from .Net " + s;
  }
}
</code></pre>

<h2>What works</h2>

<p>I can successfully pass integers into and out of dotNET procedures.
I can successfully pass strings (widestring on the Delphi side) into dotNET procedures.</p>

<h2>What doesn't work</h2>

<p>In the above two listings, the string parameter returned is junk. Accessing it causes an AV.</p>

<h2>Environment</h2>

<p>Delphi XE7, dotNET 4, Win 7, 32 bit application and dll.</p>
