Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call delphi dll function from C# passing in a byte array

I'm having trouble figuring out the best way to have a delphi function operate on a byte array from .net.

The delphi signature looks like this:

procedure Encrypt(
    var Bytes: array of byte;
    const BytesLength: Integer;
    const Password: PAnsiChar); stdcall; export;

The C# code looks like this:

[DllImport("Encrypt.dll",
    CallingConvention = CallingConvention.StdCall,
    CharSet = CharSet.Ansi)]
public static extern void Encrypt(
    ref byte[] bytes,
    int bytesLength,
    string password);

Omitting var and ref before the byte array declaration seemed to fail, but is it required since I'll be changing only the contents of the array and not the array itself?

Also, for some reason I can't seem to get the length of the array in delphi, if I remove the BytesLength parameter than Length(Bytes) will not work, if I add the BytesLength parameter, Length(Bytes) starts to work but BytesLength has a wrong value.

like image 612
Yona Avatar asked Aug 03 '11 21:08

Yona


1 Answers

Make the first parameter of the Delphi Encrypt be Bytes: PByte and you should be good to go.

An open array, as you have it, expects to be passed both the pointer to the first element and the length which explains what you describe in your question.

like image 55
David Heffernan Avatar answered Oct 18 '22 02:10

David Heffernan