Search code examples
.netdelphipinvoke

Calling a Delphi Function from .Net


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.'


Solution

  • 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.