Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Callback from Delphi dll to C# app

Inside a c# application a c#-method with parameter is to be called from a delphi dll: The C# method gets called, but the int param is not transfered correctly: some "random" value arrives.

The C#-method is passed to the delphi dll via a register method:

    [UnmanagedFunctionPointer(CallingConvention.ThisCall)]
    public delegate void ProcDelegate(int value);

    private static ProcDelegate procDelegate;

    [DllImport("CallbackTest.dll", CallingConvention = CallingConvention.StdCall)]
    public static extern void RegisterCallback(ProcDelegate callBackHandle, int value);


    public Form1()
    {
        InitializeComponent();

        procDelegate = new ProcDelegate(CalledFromDelphi);

        RegisterCallback(procDelegate, 10); // register in delphi dll


    }

    public static void CalledFromDelphi(int value)
    {
        MessageBox.Show("Value:" + value); // expect "10", but getting random value

    }

And here is the delphi code:

type TCallback = procedure(val: integer);
var callback : TCallback;
procedure RegisterCallback(aCallback : TCallback; value: integer); stdcall;
begin
  callback:=  aCallback; 
  ShowMessage('Inside Delphi:'+ IntToStr(value)); // successful ("10")

  callback(value);  // ...and test callback
end;

exports
  RegisterCallback;

What's also interesting: the callback method gets called twice (both times a "random" value arrives) although it's called only once in code. After that the app crashes with exit code (0xc0000005).

Any idea?

like image 856
bert Avatar asked Feb 06 '10 08:02

bert


1 Answers

Try

type TCallback = procedure(val: integer); stdcall;
like image 170
Toon Krijthe Avatar answered Oct 22 '22 21:10

Toon Krijthe