Search code examples
c#delphidlldelphi-7

Unmanaged Exports and delegates


I am using Robert Giesecke Unmanaged Exports to create a .NET wrapper DLL to use a .NET DLL in Delphi 7. Everything works fine so far, but now I have a function which needs to have a callback/delegate.

How can this be done?

Can I just give the function pointer to my .NET DLL and call it from there and when yes how is it done?


Solution

  • It's pretty simple. You define a delegate type just as you would with a standard p/invoke.

    Here's the simplest example that I can think of:

    C#

    using RGiesecke.DllExport;
    
    namespace ClassLibrary1
    {
        public delegate int FooDelegate();
    
        public class Class1
        {
            [DllExport()]
            public static int Test(FooDelegate foo)
            {
                return foo();
            }
        }
    }
    

    Delphi

    program Project1;
    
    {$APPTYPE CONSOLE}
    
    type
      TFooDelegate = function: Integer; stdcall;
    
    function Test(foo: TFooDelegate): Integer; stdcall; external 'ClassLibrary1.dll';
    
    function Func: Integer; stdcall;
    begin
      Result := 666;
    end;
    
    begin
      Writeln(Test(Func));
    end.
    

    Output

    666
    

    The default calling convention on the C# side is CallingConvention.Stdcall so I've gone along with that. That's the obvious thing to do.