Home > Software design >  Returning an array from c function into c# script in unity
Returning an array from c function into c# script in unity

Time:04-28

I have a c function defined as

extern "C" Point* myFunc(int size) {
  Point *p = new Point[size];
  return p;
}

where point is just a struct defined as

extern "C" typedef struct _point {
  int x;
  int y;
} Point;

and inside my c# code I have

[DllImport("MyLibrary")]
static extern Point[] myFunc(int size);

and I use it as

Point[] newPoints = myFunc(3);
Debug.Log(newPoints.Length);

But the output is

33

The function is just an example, but the lenght of the array returned shouldn't be known before the function call. What is the correct way of returning an array to c# in order to use it, know its size and access it without incurring in any IndexOutOfRangeException?

CodePudding user response:

You can convert the array to a list:

var newList = integer_array.ToList();

CodePudding user response:

It is impossible to determine array length from a pointer. It seems instead of throwing an exception, Unity guesses and guesses wrong. The correct way to return data in an array from C is to pass an array of correct size in from C#:

extern "C" void GetPoints(Point* points, int size)
{
    for (int i = 0; i < size; i  )
        points[i].x = points[i].y = i;
}

And then on C# side:

[DllImport("MyLibrary", EntryPoint = "GetPoints")]
static extern void GetPointsNative([In][Out][MarshalAs(UnmanagedType.LPArray)] Point[] points, int size);

static Point[] GetPoints(int size)
{
    var points = new Point[size];
    GetPointsNative(points, size);
    return points;
}
  • Related