0

I am trying to build a DLL in Delphi and consume that in C#. I have the below simple code Delphi code

library Project1;
uses
  System.SysUtils,
  System.Classes;

{$R *.res}

function DelphiFunction(A: Integer; B: Integer; out outputInt : integer): integer; stdcall; export;
 begin

     if A < B then
        outputInt := B
     else
        outputInt := A;

   DelphiFunction := outputInt;
 end;

exports DelphiFunction;
begin
end.

C# Code

[DllImport("Project1.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
public static extern bool
DelphiFunction(int a, int b);

private void button3_Click(object sender, EventArgs e)
{
   var a = 2;
   var b = 3;
   var result = DelphiFunction(a, b);
}

However, I am getting an error at line var result = DelphiFunction(a, b);

System.AccessViolationException: 'Attempted to read or write protected memory. This is often an indication that other memory is corrupt.'

1 Answer 1

3

Your C# declaration bears little resemblence to the Delphi function that you are trying to call. To recap, the target is this:

function DelphiFunction(A: Integer; B: Integer; out outputInt: integer): integer; stdcall;

Your C# has the wrong calling convention, the wrong return value type, and is missing an argument. You need this:

[DllImport("Project1.dll", CallingConvention = CallingConvention.StdCall)]
public static extern int DelphiFunction(int a, int b, out int outputInt);

Note that you don't need to specify the CharSet, and the export directive in Delphi is spurious and ignored. Remove it.

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

Comments

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.