title: Marshalling C structures to C#
body: <p>Suppose I have a structure:</p>
  
  <pre><code>typedef struct {
  float x;
  float y;
  float z;
  int   ID;
  } Vertex;
  </code></pre>
  
  <p>and a C++ function:</p>
  
  <pre><code>float first(Vertex* ptr, int length){ //really silly function, just an example
      Vertex u,v;
      u.x = ptr[0].x; //...and so on, copy x,y,z,ID
      v.x = ptr[1].x; 
      return (u.x * v.x + u.y * v.y + u.z * v.z);
      }
  
  
  Vertex* another(float a, int desired_size){
      Vertex v = (Vertex*)malloc(desired_size*sizeof(Vertex));
      v[0].x = a;
      v[1].x = -a; //..and so on.. make some Vertices.
      return v;
  }
  </code></pre>
  
  <p>First - my IDE. I'm using Visual Studio 2010, building a C# (4.0) application; The C++ part is also built in VS2010.</p>
  
  <p>I know how to build a DLL of C/C++ code and use it in C# application, but until today I used only primitive arguments and return values like:</p>
  
  <pre><code>    [DllImport("library.dll", CharSet = CharSet.Ansi, SetLastError = true, CallingConvention = CallingConvention.StdCall)]
      public static extern int simple(int a, int b);
  </code></pre>
  
  <p>Today I need to pass an <strong>array</strong> of <strong>structs</strong> (as in the example above).. and perhaps also receive one back..</p>
  
  <p>How to I "translate" a C# class to a C struct (and vice versa) ??</p>