3

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!

Sergey Kucher
  • 4,140
  • 5
  • 29
  • 47

3 Answers3

5

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.

Martin Liversage
  • 104,481
  • 22
  • 209
  • 256
1

This should help you http://msdn.microsoft.com/en-us/library/aa288468%28v=vs.71%29.aspx

Zenwalker
  • 1,883
  • 1
  • 14
  • 27
  • Read that I haven't found there how to return array type of meclared struct – Sergey Kucher Aug 19 '11 at 14:17
  • Its no direct solution,work around could be to pass the array and let the library fill it and send it back. As explained here http://answers.unity3d.com/questions/132083/returning-a-byte-array-from-objc-to-c-script-on-io.html – Zenwalker Aug 19 '11 at 14:29
1

Refer to this thread, it has some information about how to return a dynamically allocated struct from C++ to C# as an array.

Community
  • 1
  • 1
dcp
  • 54,410
  • 22
  • 144
  • 164