Question

tried a lot of examples and haven't succeeded I have a DLL writen in Delphi which export a function which have return a Array, and then import into C# application. A have success to work with one variable:

Delphi

function GetArrayData(var testArray : integer): WordBool; stdcall; export;
begin
  testArray := 1;
  Result := True;
end;

C#

[DllImport("some.dll", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Ansi)]
    static extern bool GetArrayData([Out] out IntPtr IntegerArrayReceiver);

private void GetButton_Click(object sender, EventArgs e)
{
    unsafe
    {
        IntPtr  IntegerArrayReceiver = IntPtr.Zero;
        GetArrayData(out IntegerArrayReceiver);
        textBoxData.Text = IntegerArrayReceiver.ToString();
    }

Please can some one to transform this code to work with a Array. Mean export a array from Delphi and import to C# array. I have source for both Delphi and C# code.

Was it helpful?

Solution

On the Delphi side you write it like this:

function GetArrayData(arr: PInteger; len: Integer): LongBool; stdcall;
var
  i: Integer;
  P: PInteger;
begin
  P := arr;
  for i := 0 to len-1 do
  begin
    P^ := i;
    inc(P);
  end;
  Result := True;
end;

Here we receive a pointer to the first element, and the length of the array.

And on the C# side you would write:

[DllImport("some.dll")]
static extern bool GetArrayData(int[] arr, int len);
....
int[] arr = new int[42];
if (GetArrayData(arr, arr.Length))
    ....

The calling C# code allocates the array and passes a pointer to the first element to the Delphi code.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top