Return allocated value from Unmanaged code to managed
I would like to do the following: Call Unamanaged method that returns the array of type MyStruct[] that it allocated.
Example of c code:
MyStruct[] foo(i开发者_如何学JAVAnt size)
{
Mystruct* st = (MyStruct*)malloc(size * sizeof(MyStruct));
return st;
}
How should Implement c# calling method?
Thank you!
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.
This should help you http://msdn.microsoft.com/en-us/library/aa288468%28v=vs.71%29.aspx
Refer to this thread, it has some information about how to return a dynamically allocated struct from C++ to C# as an array.
精彩评论