title: MarshalAs nested structure
body: <p>I have two C++ structures that I have to send as parameters when calling a DLL method from C#.</p>
  
  <p>For example, lets define them as:</p>
  
  <pre><code>struct A
  {
      int data;
  }
  
  struct B
  {
      int MoreData;
      A * SomeData;
  }
  </code></pre>
  
  <p>A method that I need to call from C# has the following signature:</p>
  
  <pre><code>int operation (B * data);
  </code></pre>
  
  <p>(Please note that I do not have the control over these C++ structures nor methods. )</p>
  
  <p>In C# I define these structures as classes:</p>
  
  <pre><code>[StructLayout(LayoutKind.Sequential)]
  class A
  {
      public int data;
  }
  
  [StructLayout(LayoutKind.Sequential)]
  class B
  {
      public int MoreData;
  
      [MarshalAs(UnmanagedType.Struct)]
      public A SomeData;
  }
  </code></pre>
  
  <p>I have created a "debugging dll" to call from C# in order to ensure all the data is received correctly in C++ methods. So far only the data that comes before the nested structure pointer is sent correctly. </p>
  
  <p>When I try to read data from the nested structure (B->A->data) I get a read violation error (AccessViolationException).</p>
  
  <p>How can I marshal the nested structure so I will be able to read it in the C++ method?</p>