如何将 int 数组从 C# 编组到 delphi

How to marshall array of int from c# to delphi

我从使用 Delphi2006 制作的 dll 导出了以下内容。

procedure ScSetMRStatus(StatusType: TStatusType; active_mr_ids: TLongIntArray; id_dst: Integer; id_src_list: TLongIntArray; IsComplete: Boolean); stdcall; export;

其中 TLongIntArray 定义为:

TLongIntArray = array of LongInt;

并且 TStatusType 只是一个枚举:

  TStatusType = ( stPhysical, stMaster );

现在我尝试从 C# 应用程序调用此方法。

[DllImport(DelphiDLLName, EntryPoint = "ScSetMRStatus", CallingConvention = CallingConvention.StdCall)]
private static extern void ScSetMRStatus(
    Int32 statusType,
    IntPtr activeMrIds,
    Int32 IdDst,
    IntPtr idSrcList,
    [MarshalAs(UnmanagedType.U1)] bool isComplete);

在 c# 中以这种方式使用它:

ScSetMRStatus((Int32) statusType, ConvertManagedArrayToDelphiDynIntArray(activeMrIds), idDst, ConvertManagedArrayToDelphiDynIntArray(idSrcList), isComplete);

ConvertManagedArrayToDelpiDynIntArray 看起来像:

public static IntPtr ConvertManagedArrayToDelphiDynIntArray(int[] array)
{
    if (array == null) return IntPtr.Zero;

    int elementSize = sizeof(int);
    int arrayLength = array.Length;
    int allocatedMemSize = 8 + elementSize * arrayLength;
    IntPtr delphiArrayPtr = Marshal.AllocHGlobal(allocatedMemSize);
    Marshal.WriteInt32(delphiArrayPtr, 0, 1);
    Marshal.WriteInt32(delphiArrayPtr, 4, arrayLength);
    for (int k = 0; k < arrayLength; k++) {
        Marshal.WriteInt32(delphiArrayPtr, 8 + k*elementSize, array[k]);
    }
    return delphiArrayPtr+8;
}

但这行不通!

如何将 C# 数组发送到 delphi?

终于成功了!

我们对调用进行了一些更改以释放分配的内存。

var activeMrIdsNative = ConvertManagedArrayToDelphiDynIntArray(activeMrIds);
var idSrcListNative = ConvertManagedArrayToDelphiDynIntArray(idSrcList);
ScSetMRStatus((Int32) statusType, activeMrIdsNative, idDst, idSrcListNative, isComplete);
Marshal.FreeHGlobal(activeMrIdsNative-8);
Marshal.FreeHGlobal(idSrcListNative-8);

我们只是认为它不会起作用,因为我们还没有看到 Delphi 方面用它做什么。所有数据都进入 delphi dll,并且运行良好。

可能存在内存问题,但我们会检查一下。