Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delphi DLL in C# - var array as parameter

i need use a Delphi DLL in my C# code.

I have some success when using other methods with common parameters, but in this case the solution still hidden.

The DLL documentation presents this declaration:

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

I tried to use:

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

Not successful. Some Help?

like image 561
Andre Soares Avatar asked Feb 24 '11 13:02

Andre Soares


1 Answers

The first thing you need to do is to use stdcall on the C# side:

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

I'd also want to be sure that the Delphi side is post Delphi 2009 and so uses wide characters. If so, then there's no issue there. If you are using a non-Unicode Delphi then you'd need CharSet.Ansi.

I'd probably also return a LongBool on the Delphi side and marshal it with

[return: MarshalAs(UnmanagedType.Bool)]

back on the .NET side.

Finally, the fixed length array needs to be marshalled differently. The standard approach for fixed length character arrays is to use a StringBuilder on the .NET side which is marshalled as you desire.

Putting it altogether, and fixing your Delphi syntax, gives:

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);
}

Finally, make sure that you null-terminate your string when you return it from your DLL!

like image 160
David Heffernan Avatar answered Oct 09 '22 23:10

David Heffernan