7

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?

1 Answer 1

8

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!

Sign up to request clarification or add additional context in comments.

2 Comments

Hi, the problem stills. This seems to be relative to the "char array", when i declare the import with no parametersthe program still running, but when i declare the char parameter
Hi, I wasn't thinking straight before. I'd forgotten about the array marshalling. I believe that the updated answer will do the job for you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.