0

I have the following export from a dll made with Delphi2006.

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

where TLongIntArray is defined as:

TLongIntArray = array of LongInt;

and TStatusType is just an enum:

  TStatusType = ( stPhysical, stMaster );

Now I tried to call this method from a c# application.

[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);

Using it this way from c#:

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

ConvertManagedArrayToDelpiDynIntArray looks like:

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;
}

But this doesn't work!

How do I send c# arrays to delphi?

0

1 Answer 1

1

It's finally working!

We did a few changes around the call to free the allocated memory.

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

We just thought it would not work, as we have not looked at what the Delphi side does with it. All data gets it's way into the delphi dll and it's working good.

Maybe there is a memory issue, but we will examine this.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.