如何使用C#调用接收Delphi开放数组参数的函数? [英] How do I use C# to call a function that receives a Delphi open-array parameter?
问题描述
如何将Delphi代码转换为C#?它需要一个数组的字节
,但我不知道C#等效的是什么。我的尝试不起作用,并抛出异常,如AccessViolationException。
How do I convert the Delphi code into C#? It takes an array of Byte
, but I'm not sure what the C# equivalent is. My attempt doesn't work and throws exceptions like AccessViolationException.
Delphi:
function SetLevel(a: array of byte): boolean; stdcall; external 'DMX510.dll';
C#:
[DllImport("DMX510.DLL")]
public static extern Boolean SetLevel(Byte[] bytearray);
Byte[] byteArray = new Byte[5];
byteArray[1] = 75;
SetLevel(byteArray);
推荐答案
Delphi开放数组不是有效的interop类型。您不能通过P / invoke轻松匹配C# byte []
。在一个理想的世界中,不同的界面将被本地DLL暴露出来,但正如您在注释中所说明的那样,您无法控制该界面。
A Delphi open array is not a valid interop type. You can't easily match that up with a C# byte[]
through a P/invoke. In an ideal world a different interface would be exposed by the native DLL but as you have stated in comments, you do not have control over that interface.
但是,您可以欺骗C#代码传递Delphi DLL将正确解释的东西,但它有点脏。关键是一个Delphi开放的数组,它被声明为具有一个额外的隐含参数,包含数组中最后一个元素的索引。
However, you can trick the C# code into passing something that the Delphi DLL will interpret correctly, but it's a little dirty. The key is that a Delphi open array declared like that has an extra implicit parameter containing the index of the last element in the array.
[DllImport(@"DMX510.DLL")]
public static extern bool SetLevel(byte[] byteArray, int high);
byte[] byteArray = new byte[] { 0, 75, 0, 0, 0};
SetLevel(byteArray, byteArray.Length-1);
Delphi DLL函数声明如下:
To be clear, in spite of the parameter lists looking so different, the C# code above will successfully call the Delphi DLL function declared so:
function SetLevel(a: array of byte): boolean; stdcall;
我不知道传递长度为5的数组是否合适,或者是否真的意味着将第二个项目设置为非零值。
I have no idea whether or not passing an array of length 5 is appropriate, or whether you really meant to just set the second item to a non-zero value.
这篇关于如何使用C#调用接收Delphi开放数组参数的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!