[英]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 );
現在,我嘗試從ac#應用程序調用此方法。
[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,並且運行良好。
也許存在內存問題,但是我們將對此進行檢查。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.