简体   繁体   中英

How to call this Delphi function from a DLL in C#?

I am given a Delphi DLL that contains functions that I need to call in C#. One of the functions takes two char arrays, where one is an encrypted password and the other is the key.

TCString = array[0..254] of Char;
...
function Decrypt(const S, Key: TCString): TCString; stdcall;

I tried to figure out how to call this function on my own but I keep getting "Cannot marshal 'return value': Invalid managed/unmanaged type combination." I am using byte since the Char type in Delphi is AnsiChar which is 8 bits.

[DllImport("path", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Ansi)]
        public static extern byte[] Decrypt(byte[] S, byte[] Key);

What is the correct way to call this in C#?

I think I would be inclined to wrap the fixed length array in a C# struct.

public struct CString
{
    [UnmanagedType.ByValArray(SizeConst=255)]
    byte[] value;
}

This allows the size to be specified in one place only.

The next hurdle is the return value. The Delphi ABI treats a return value that cannot fit into a register as an additional hidden var parameter. I'll translate that as a C# out parameter.

Finally the two input parameters are declared as const . That means that they are passed by reference.

So the function would be:

[DllImport(dllname, CallingConvention = CallingConvention.StdCall)]
public static extern void Decrypt(
    [In] ref CString S, 
    [In] ref CString Key, 
    out CString Result

);

I've intentionally avoided any use of text in this because this would appear to be a function that operates on binary data. Many Delphi programmers treat AnsiChar arrays interchangeably with byte arrays in such situations which is often confusing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM