The Marshal
class in the System.Runtime.InteropServices
namespace has a lot of methods to help you marshal data to and from unmanaged code.
You need to declare your native method:
[DllImport("myclib.dll")]
public static extern IntPtr Foo(Int32 size);
And also your C struct as a managed value type (you can use attributes on the fields to control exactly how they are mapped to native memory when they are marshalled):
[StructLayout(LayoutKind.Sequential)]
struct MyStruct {
public Char Character;
public Int32 Number;
}
Then you can use Marshal.PtrToStructure
to marshal each element of the array into a managed value:
var n = 12;
var pointer = Foo(n);
var array = new MyStruct[n];
var structSize = Marshal.SizeOf(typeof(MyStruct));
for (var i = 0; i < n; ++i) {
array[i] = (MyStruct) Marshal.PtrToStructure(pointer, typeof(MyStruct));
pointer += structSize;
}
Note that you are using malloc
to allocate the memory in the C code. C# us unable to free that memory and you will have to provide another method to free the allocated memory.