从C#调用delphi dll函数传入一个字节数组

时间:2022-09-20 16:57:22

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

我无法找到使用.net的字节数组运行delphi函数的最佳方法。

The delphi signature looks like this:

delphi签名如下所示:

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

The C# code looks like this:

C#代码如下所示:

[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?

在字节数组声明之前省略var和ref似乎失败了,但它是否需要,因为我只更改数组的内容而不是数组本身?

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.

另外,由于某些原因,我似乎无法在delphi中获取数组的长度,如果我删除BytesLength参数而不是Length(Bytes)将无法工作,如果我添加BytesLength参数,则Length(Bytes)开始工作但是BytesLength的值不正确。

1 个解决方案

#1


2  

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

将Delphi Encrypt的第一个参数设为Bytes:PByte,你应该好好去。

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.

一个开放的数组,就像你拥有它一样,期望传递指向第一个元素的指针和解释你在问题中描述的内容的长度。

#1


2  

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

将Delphi Encrypt的第一个参数设为Bytes:PByte,你应该好好去。

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.

一个开放的数组,就像你拥有它一样,期望传递指向第一个元素的指针和解释你在问题中描述的内容的长度。