c# - 如何使用非托管导出 (Robert Giesecke) 将 dateTime 类型数组从 .NET 传递到 Delphi?

标签 c# arrays delphi datetime

我想将 dateTime 类型数组从 .NET dll 传递到 Delphi。 这是 C# 代码:

[DllExport]
public static void ReadDateTimeData(out IntPtr unmanagedArray, out int length)
{
    //Get the DateTimeArray
    DateTime[] dateTimeArray = MyClass.Instance.GetDateTimeArray();
    length = dateTimeArray.Length;

    unmanagedArray = Marshal.AllocHGlobal(length*Marshal.SizeOf(typeof (int)));
    Marshal.Copy(dateTimeArray, 0, unmanagedArray, length);
}

但 Marshal.Copy() 方法不支持 DateTime 类型数组指向非托管内存指针。我应该怎么办?另外,如何实现delphi代码?

最佳答案

如果您的日期时间值在自动化兼容范围内,您可以使用 DateTime.ToOADate()获取自动化兼容的值,然后简单地使用 Marshal.Copy 的重载和 double[] 代替:

public static void ReadDateTimeData(out IntPtr unmanagedArray, out int length)
{
    // Get the DateTimeArray
    DateTime[] dateTimeArray = GetDateTimeArray();
    length = dateTimeArray.Length;
    // Convert to double[]
    double[] oaDateArray = new double[length];
    for (int i = 0; i < length; i++)
        oaDateArray[i] = dateTimeArray[i].ToOADate();

    unmanagedArray = Marshal.AllocHGlobal(length * Marshal.SizeOf(typeof(double)));
    Marshal.Copy(oaDateArray, 0, unmanagedArray, length);
}

在 Delphi 端,您将收到一个指向 TDateTime 数组的指针:

procedure ReadDateTimeData(out DateTimeArray: PDateTime; out Length: Integer); stdcall; external 'TestLib.dll';
procedure FreeDateTimeData(DateTimeArray: PDateTime); stdcall; external 'TestLib.dll';

procedure Main;
var
  DateTimeArray, P: PDateTime;
  I, Len: Integer;
begin
  ReadDateTimeData(DateTimeArray, Len);
  try
    P := DateTimeArray;
    for I := 0 to Len - 1 do
    begin
      Writeln(DateTimeToStr(P^));
      Inc(P);
    end;
  finally
    FreeDateTimeData(DateTimeArray);
  end;
end;

或者,关闭范围检查:

type
  PDateTimeArray = ^TDateTimeArray;
  TDateTimeArray = array[0..0] of TDateTime;

procedure ReadDateTimeData(out DateTimeArray: PDateTimeArray; out Length: Integer); stdcall; external 'TestLib.dll';
procedure FreeDateTimeData(DateTimeArray: PDateTimeArray); stdcall; external 'TestLib.dll';

procedure Main;
var
  DateTimeArray: PDateTimeArray;
  I, Len: Integer;
begin
  ReadDateTimeData(DateTimeArray, Len);
  try
    for I := 0 to Len - 1 do
      Writeln(DateTimeToStr(DateTimeArray^[I]));
  finally
    FreeDateTimeData(DateTimeArray);
  end;
end;

关于c# - 如何使用非托管导出 (Robert Giesecke) 将 dateTime 类型数组从 .NET 传递到 Delphi?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39176862/

相关文章:

arrays - 从 Ruby 中没有 nil 值的变量创建数组

delphi - 加快Delphi状态栏的更新速度

forms - 在同一应用程序中,以另一种独立的形式更改控件的状态

c# - 查找程序集中某个类的所有用途

c# - 是否应该通过组合或其他方式引入新行为?

python - 包含第一个元素的反向数组切片

C++ ||添加两个矩阵数组 - 更简单的输出方式?

delphi - 如何阻止 Delphi 6 COM 服务器应用程序在启动时重新注册 COM

c# - Java 设计器脚本项目在 VB6 到 C# 转换中的作用是什么?

c# - 列表过滤变体