title: using Marshal.FreeHGlobal after Marshal.StringToHGlobalUni
body: <p>I'm writing a DLL in C# that is called from Delphi using <code>dllexport</code>.</p>
  
  <p>The basics is very simple and works, but I wanted to expose a function that returns fills a string with specific message (not returning a string). The way I'm doing it is that the Delphi sends the function a pointer of type wide string (<code>LPWSTR</code>) and I fill  it. This works well. However, when I do it, I need to free the memory and this is where I'm not sure I did the right thing.
  The DLL is build in one class that implement <code>IDisposable</code>. This is because I need to free the memory after the function executes.</p>
  
  <p>Here is the class and this one function.</p>
  
  <p>In order to release the memory I allocate, I declare a global static <code>intPtr</code>, which I release as dispose. Here is the code.</p>
  
  <p>Would be happy to get any feedback</p>
  
  <pre><code>namespace simpleDLL
  {
      public class Test : IDisposable
      {
          public delegate int prog(int i);
  
          static IntPtr s_copy;
          bool disposed = false;
          [DllExport("getString", CallingConvention = CallingConvention.Cdecl)]
          public static int getString(out IntPtr s, [MarshalAs(UnmanagedType.LPWStr)] string str)
          {
  
              s_copy = (IntPtr)Marshal.StringToHGlobalUni(str);
              s = s_copy;
              return str.Length;
          }
          public void Dispose()
          {
              Dispose(true);
          }
          // Protected implementation of Dispose pattern.
          protected virtual void Dispose(bool disposing)
          {
              if (disposed)
                  return;
  
              if (disposing)
              {
                  Marshal.FreeHGlobal(s_copy);
                  // Free any other managed objects here.
                  //
              }
  
              // Free any unmanaged objects here.
              //
              disposed = true;
          }
          ~Test()
          {
              Dispose(false);
          }
      }
  </code></pre>