Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The struct can be declared like this:</p> <pre><code>[StructLayout(LayoutKind.Sequential)] public struct Vertex { public float x; public float y; public float z; public int ID; } </code></pre> <p>Next you need to settle on a calling convention. Your C++ code is almost certainly compiled with <code>cdecl</code>. Let's stick with that.</p> <p>The function first is easy to call from C#:</p> <pre><code>[DllImport("library.dll", CallingConvention = CallingConvention.Cdecl)] public static extern float first(Vertex[] vertices); </code></pre> <p>Note that you should not use <code>SetLastError</code> here–that's for Windows API functions. And there's no need to set the <code>CharSet</code> since there is no text here.</p> <hr> <p>Now, for <code>another</code> things get more complex. If you can allocate the memory in the C# code then that is definitely the way to go.</p> <pre><code>void PopulateVertices(Vertex *vertices, int count) { for (int i=0; i&lt;count; i++) { vertices[i].x = .... } } </code></pre> <p>On the C# side you declare it like this:</p> <pre><code>[DllImport("library.dll", CallingConvention = CallingConvention.Cdecl)] public static extern void PopulateVertices(Vertex[] vertices, int count); </code></pre> <p>and call it like this</p> <pre><code>Vertex[] vertices = new Vertex[2]; PopulateVertices(vertices, vertices.Length); </code></pre> <hr> <p>If you don't want to allocate on the C# side of the fence then do it like this:</p> <ol> <li>Return a pointer from the C++ code and allocate it with <code>CoTaskMemAlloc</code>.</li> <li>In C# declare the return value of the imported function as <code>IntPtr</code>.</li> <li>Use <code>Marshal.PtrToStructure</code> and some pointer arithmetic to marshal the return array into a C# array.</li> <li>Call <code>Marshal.FreeCoTaskMem</code> to free the memory allocated in the native module.</li> </ol> <p>But if you want my advice, try and stick to allocating the array in the managed code.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload