首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >如何使用非托管导出将dateTime类型数组从.NET传递到Delphi (Robert Giesecke)?

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

Stack Overflow用户
提问于 2016-08-27 10:24:14
回答 1查看 688关注 0票数 1

我想把Delphi中的dateTime类型数组传递给.NET。这是c#代码:

代码语言:javascript
代码运行次数:0
运行
复制
[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代码?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-08-27 16:05:22

如果您的DateTime值在与自动化兼容的范围内,则可以使用DateTime.ToOADate()获取与自动化兼容的值,然后只需使用带有double[]Marshal.Copy重载:

代码语言:javascript
代码运行次数:0
运行
复制
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数组的指针:

代码语言:javascript
代码运行次数:0
运行
复制
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;

或者,关闭范围检查:

代码语言:javascript
代码运行次数:0
运行
复制
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;
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39176862

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档