我想将 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/