我如何通过dateTime类型数组从.net到Delphi使用非托管导出(Robert Giesecke)
本文关键字:Giesecke Robert 类型 dateTime 何通过 数组 Delphi net | 更新日期: 2023-09-27 18:04:09
我想传递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;