Ali Yousefi
Ali Yousefi

Reputation: 2765

cannot return delphi array in C# array

I want to use delphi array function in C#.

My delphi code:

TIntegerArray = array of integer;
function Testarray(): TIntegerArray stdcall; export;
 var
   res: TIntegerArray2;
 begin
   SetLength(res, 10);
   res[5] := 55;
   Result := res;
 end;
 exports Testarray;

C# code:

[DllImport("GitaTele.dll", CallingConvention = CallingConvention.StdCall)]
public static extern int[] Testarray();

Shows me error:

Cannot marshal 'return value': Invalid managed/unmanaged type combination.

Upvotes: 2

Views: 809

Answers (1)

David Heffernan
David Heffernan

Reputation: 613461

Delphi dynamic arrays are not valid interop types. You need to have the caller allocate the array, and then let the callee populate it.

procedure PopulateArray(arr: PInteger; var len: Integer); stdcall;
var
  i: Integer;
  returnArray: TArray<Integer>;
begin
  returnArray := GetArray;
  len := Min(len, Length(returnArray));
  for i := 0 to len - 1 do
  begin
    arr^ := returnArray[i];
    inc(arr);
  end;
end;

Do note the export has no meaning, is ignored, and should be removed for sake of simplicity.

From C# the calling code is:

[DllImport("...", CallingConvention = CallingConvention.StdCall)]
public static extern void PopulateArray(
    [In, Out]
    [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)]
    int[] arr,
    ref int len
);

....

int[] arr = new int[50];
int len = arr.Length;
PopulateArray(arr, ref len);
// len now contains actual length

Upvotes: 3

Related Questions