Jascha Schubert
Jascha Schubert

Reputation: 159

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?

Upvotes: 4

Views: 1503

Answers (3)

buttercup
buttercup

Reputation: 1116

You could:

1) Make the NET DLL function return an Integer, which is consumed by the Delphi 7 DLL. The varied return results will then trigger various procedures to be called inside the Delphi 7 DLL.

2) Make it fully native (Convert from NET to Delphi 7).

3) Make it fully NET (Make it fully NET instead).

4) If both of them are DLLs, you could export a native DLL function from Delphi to NET via an unmanaged DLL call.

Upvotes: -1

Jascha Schubert
Jascha Schubert

Reputation: 159

Found the answer, this Call C function inside C# via function pointer helped me a lot

Basically you can just send the pointer and call it

On the C# side:

  1. Define the Signature of the delegate

    public delegate void LinkCallback(int AValue);
    
  2. Create a IntPtr Varialbe to store the pointer

    public IntPtr Callback;           
    
  3. In the DLL function which gets the pointer assign it to the variable

    Callback = new IntPtr(cb);
    
  4. To call the callback you must marshal it

    LinkCallback callback = (LinkCallback)Marshal.GetDelegateForFunctionPointer(ConList[Idx].Callback,typeof(LinkCallback));
    
    callback(10);
    

Upvotes: -2

David Heffernan
David Heffernan

Reputation: 612794

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.

Upvotes: 5

Related Questions