如何将C#中的字符串数组传递给Delphi dll?

时间:2016-07-22 10:43:39

标签: c# arrays delphi

我需要将C#中的开放字符串数组传递给Delphi dll。在delphi中设置数组的长度并将其返回给C#。 他们有什么办法吗?

首先,我在C#中尝试此代码:

public struct TStrSample
{
    [MarshalAs(UnmanagedType.BStr)]
    public string Name;
}

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


[Microsoft.SqlServer.Server.SqlProcedure]
public static void hcTable(SqlBytes blob)
{
    TStrSample[] arr = new TStrSample[10];
    int len = arr.Length;
    for (int i = 0; i < len; i++)
    {
        arr[i].Name = i.ToString();
    }
    PopulateStrArray(arr, ref len);
}

德尔福部分:

type
  TStrSample = record
    Name: WideString;
  end;
  PStrSample = ^TStrSample;

procedure PopulateStrArray(arr: PStrSample; var len: Integer); stdcall;
var
  i: Integer;
  returnArray: array of TStrSample;
begin
  returnArray := @arr;
  for i := 0 to Len-1 do
    returnArray[i].Name := 'YES = ' + IntToStr(i);
end;

但它不起作用。有什么问题?

1 个答案:

答案 0 :(得分:0)

我已经更改了Delphi代码,现在它正在运行。感谢 David Heffernan

type
  TStrSample = record
    Name: WideString;
  end;
  PStrSample = ^TStrSample;

procedure PopulateStrArray(arr: PStrSample; var len: Integer); stdcall;
var
  i: Integer;
begin
  for i := 0 to len - 1 do
  begin
    arr^.Name := 'YES = ' + IntToStr(i);
    Inc(arr);
  end;
end;

是否有可能将开放数组传递给Delphi?