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(int size)
{
Mystruct* st = (MyStruct*)malloc(size * sizeof(MyStruct));
return st;
}
How should Implement c# calling method?
Thank you!
The
Marshalclass in theSystem.Runtime.InteropServicesnamespace has a lot of methods to help you marshal data to and from unmanaged code.You need to declare your native method:
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):
Then you can use
Marshal.PtrToStructureto marshal each element of the array into a managed value:Note that you are using
mallocto 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.