title: System.AccessViolationException while marshaling from native to managed by implementing ICustomMarshaler
body: <p>Somehow the continuation to the <a href="https://stackoverflow.com/questions/23991078/how-to-properly-release-memory-when-doing-custom-marshaling-icustommarshaler-f">question</a> I recently posted, I've a nasty <code>System.AccessViolationException</code> while trying to marshal from native to managed (by using <code>ICustomMarshaler</code>), which I do not understand. Here a sample code that reproduce the error (**). The C++ side:</p>
  <pre><code>typedef struct Nested1{
      int32_t         n1_a; // (4*)
      char*           n1_b;
      char*           n1_c;
  } Nested1;
  typedef struct Nested3{
      uint8_t         n3_a;
      int64_t         n3_b;
      wchar_t*        n3_c;
  } Nested3;
  typedef struct Nested2{
      int32_t         n2_a;
      Nested3         nest3;
      uint32_t        n2_b;
      uint32_t        n2_c;
  } Nested2;
  typedef struct TestStruct{
      Nested1     nest1; // (2*)
      Nested2     nest2;
  } TestStruct;
  
  void ReadTest(TestStruct&amp; ts)
  {
      ts.nest2.n2_c = 10; // (3*)
  }
  </code></pre>
  <p>On the C# side a fake <code>TestStruct</code> just to show the error and the <code>ICustomMarshaler</code> implementation:</p>
  <pre><code>class TestStruct{};
  [DllImport(&quot;MyIOlib.dll&quot;, CallingConvention = CallingConvention.Cdecl)]
  extern static void ReadTest([Out, MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(CustomMarshaler))]TestStruct ts);
  
  class CustomMarshaler : ICustomMarshaler
  {
      public static ICustomMarshaler GetInstance(string Cookie) { return new CustomMarshaler(); }
  
      public object MarshalNativeToManaged(IntPtr pNativeData)
      {
          return new TestStruct();
      }
      public void CleanUpNativeData(IntPtr pNativeData) 
      { 
      } // (1*) 
      public int GetNativeDataSize() { return 40; }
      public IntPtr MarshalManagedToNative(object ManagedObj)
      {
          TestStruct ts = (TestStruct)ManagedObj;
          IntPtr intPtr = Marshal.AllocHGlobal(GetNativeDataSize());
  
          return intPtr;
      }
   }
  
  private void Form1_Load(object sender, EventArgs e)
  {
       TestStruct ts = new TestStruct();
       ReadTest(ts);
  }
  </code></pre>
  <p>Now, I have the following:</p>
  <ul>
  <li>with exactly this code I get a <code>System.AccessViolationException</code> just after line (1*);</li>
  <li>if I comment out line (2*) <em>or</em> line (3*) I get no exception and everything works fine;</li>
  <li>if I comment one among several other struct fields, e.g. line (3*) I get a &quot;Managed Debugging Assistant 'FatalExecutionEngineError' has detected  a problem in [...] This error may be a bug in the CLR or in the unsafe or non verifiable portions of user code. Common sources of this bug include user marshaling errors for COM-interop or PInvoke, which may corrupt the stack&quot;</li>
  </ul>
  <p>(**) I did an heavy editing of my original post because I think I've found an easier way to show the problem and leaving my previous text would have confused the reader. Hope is not a problem, however if previous readers want I can re-post my original text.</p>