Delphi DLL在C#中 - var array作为参数

时间:2011-02-24 13:45:16

标签: c# arrays delphi dll

我需要在我的C#代码中使用Delphi DLL。

在使用具有公共参数的其他方法时我取得了一些成功,但在这种情况下,解决方案仍然隐藏。

DLL文档提供了此声明:

Function Get_Matrix (var Matrix : array [ 1..200 ] of char) : boolean ; stdcall;

我试图使用:

[DllImport("DLL.dll")]
public static extern bool Get_Matrix(ref char[] Matrix);

不成功。一些帮助?

1 个答案:

答案 0 :(得分:8)

您需要做的第一件事是在C#端使用stdcall

[DllImport("DLL.dll", CallingConvention=CallingConvention.StdCall,
    CharSet=CharSet.Auto)]

我还想确保Delphi方面发布Delphi 2009,因此使用宽字符。如果是这样,那就没有问题了。如果您使用的是非Unicode Delphi,那么您需要CharSet.Ansi

我可能还会在Delphi端返回LongBool并用

编组
[return: MarshalAs(UnmanagedType.Bool)]

回到.NET端。

最后,需要对固定长度数组进行不同的编组。固定长度字符数组的标准方法是在.NET端使用StringBuilder,根据需要进行编组。

完全放弃并修复Delphi语法,给出:

<强>的Delphi

type
  TFixedLengthArray = array [1..200] of char;

function Get_Matrix(var Matrix: TFixedLengthArray): LongBool; stdcall;

<强> C#

[DllImport("DLL.dll", CallingConvention=CallingConvention.StdCall,
    CharSet=CharSet.Auto)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool Get_Matrix(StringBuilder Matrix);

static void Main(string[] args)
{
    StringBuilder Matrix = new StringBuilder(200);
    Get_Matrix(Matrix);
}

最后,确保在从DLL返回时将null终止字符串!