title: Marshaling strings to unmanaged memory, passing them to c++ and return back to c# again
body: <p>I am creating unmanaged memory block in c# and fill it with data from structs.</p>
  
  <p>I iterate through the list of structs and do something like this:</p>
  
  <pre><code>Marshal.StructureToPtr(structTemp, currentMemoryPosition, false);
  currentMemPosition = new IntPtr(currentMemPosition.ToInt64() + structSize);      
  </code></pre>
  
  <p>The struct contains reference type: "string".
  I've looked into BOL for a StructureToPtr method and there it says:</p>
  
  <pre><code>"All other reference types (for example, strings and arrays) are marshaled to copies"
  </code></pre>
  
  <p><strong>What exactly does it mean?</strong></p>
  
  <p>Does it mean that the reference to that string will still be in the memory, in spite of the fact the instance of a struct will go out of scope?</p>
  
  <p>The above unmanaged memory block, I pass to c++ method which makes use of it. When the job is done on c++ part I iterate again through structs in memory (in c#) and:</p>
  
  <pre><code>Marshal.DestroyStructure(currentMemPosition, typeof(struct));
  </code></pre>
  
  <p>The most important question for me is:</p>
  
  <pre><code>Whether I can:
  
  1) Create structs with strings inside
  2) Marshal them to unmanaged mamory
  3) Make use of them on c++ side
  4) **Return them from c++**
  5) Read them again in c#
  6) Deallocate them in c# by using Marshal.DestroyStructure (EDITED)
  </code></pre>
  
  <p>The struct layout with string reference type is:</p>
  
  <pre><code>[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Ansi, Pack = 1), Serializable]
  internal struct TempStruct
  {
      [MarshalAs(UnmanagedType.LPStr, SizeConst = 36)]
      private string iuTest;
  
      public TempStruct(Guid IuTest)
          : this()
      {
          iuTest = IuTest.ToString("D");
      }
  }
  </code></pre>