简体   繁体   中英

How can I pass string array from C# to Delphi dll?

I need to pass open array of strings from C# to Delphi dll. Sets the length of array in delphi and return it back to C#. Are they any ways?

For the beginning I'm trying this code in 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);
}

Delphi part:

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;

But it does not work. What is wrong?

I've changed Delphi code and now it's working. Thanks to 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;

Is there some possibility to pass an open array to Delphi?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM