title: A heap has been corrupted. C# dllimport, delphi PChar return value
body: <p>I have dll imported. All the other parts work, but the string return value of imported method gives this:</p>
  
  <blockquote>
    <p>Unhandled exception at 0x7748EA5F (ntdll.dll) in ***.exe: 0xC0000374: A heap has been corrupted (parameters: 0x774C4270).</p>
  </blockquote>
  
  <p>It still returns the string, but I'm worried that this causes some other errors later on, that are hard to debug. From what I have tested, it feels like it can be anything, that is causing this. </p>
  
  <p>This is my importing code:</p>
  
  <pre><code>[DllImport("kernel32.dll")]
  public static extern IntPtr LoadLibrary(string dllToLoad);
  [DllImport("kernel32.dll")]
  public static extern IntPtr GetProcAddress(IntPtr hModule, string procedureName);
  
  [UnmanagedFunctionPointer(CallingConvention.StdCall, CharSet = CharSet.Ansi)]
  private delegate String GetStringDelegate(int handle, int index);
  
  private static GetStringDelegate getString { get; set; }
  
  var addressOfGetString = NativeMethods.GetProcAddress(_handle, "GetString");
  getString = (GetStringDelegate)Marshal.GetDelegateForFunctionPointer(addressOfGetString, typeof(GetStringDelegate));
  </code></pre>
  
  <p>usage</p>
  
  <pre><code>getString(Handle, 1);
  </code></pre>
  
  <p>This works, but it causes the error. While debugging, just pressing "continue" will allow it to process it and show the results. Result is correct.</p>
  
  <p>This is how it is done in delphi dll</p>
  
  <pre><code>function GetString(Hnd,Index : Integer) : PChar; stdcall;
  begin
   Result:=TControl(Hnd).Stack.GetString(Index);
  end;
  </code></pre>
  
  <p>I have same kind of code for integers, doubles, bools and everything else in the dll works, without errors. So I think it creates somekind of overflow or wrong size of memory allocation. </p>
  
  <p>Note: If I create console application, it just fails, without breaking on error, if I run console without debugger ( ctrl+f5 ), it works, still without error. Heap error is generated when I call this from forms application.</p>
  
  <p>TL;DR; This code works, but it shows the heap error, while returning ints, bools etc works perfectly.</p>