Unmanaged exports and delegates

I use Robert Giesecke Unmanaged Exports to create a .NET DLL for using the .NET DLL in Delphi 7. Everything works fine so far, but now I have a function that should have a callback / delegate.

How can I do that?

Can I just point to my .NET library and call it there and when yes, how to do it?

+4
source share
3 answers

It is pretty simple. You define the delegate type in the same way as the standard p / invoke.

Here is the simplest example that I can think of:

WITH#

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

# CallingConvention.Stdcall, . .

+5

:

1) NET DLL , DLL Delphi 7. , DLL Delphi 7.

2) ( NET Delphi 7).

3) NET ( NET).

4) DLL, DLL- Delphi NET DLL.

-1

, Call C #

,

#:

  • public delegate void LinkCallback(int AValue);
    
  • IntPtr Varialbe,

    public IntPtr Callback;           
    
  • DLL-, ,

    Callback = new IntPtr(cb);
    
  • To call a callback, you must marshal it

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

Source: https://habr.com/ru/post/1546160/


All Articles