首页 > 解决方案 > DLL 的 COM 接口中的回调方法

问题描述

我有一个用Delphi编写的带有COM接口的DLL:

unit uRestIntf;

interface

type
  TRestoreCallback = procedure(Msg: WideString) stdcall;

  IRestore = interface
  ['{dffe3bc0-d197-4c30-be80-5296a5a10f73}']
    procedure Restore(Id: Integer; CallbackProc: TestoreCallback); safecall;
  end;

implementation

end.

CallbackProc 应该返回带有恢复过程描述的字符串。接下来我想在 MassageBox 上显示这个字符串或保存到日志文件。

我想在 C# 代码中使用这个接口。

我声明了接口:

[ComImport, Guid("dffe3bc0-d197-4c30-be80-5296a5a10f73"),
            InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]

        public interface IGetNewRestoreObject
        {
            [MethodImplAttribute(MethodImplOptions.PreserveSig)]
            void Restore(int IdFirm, TRestoreCallbackCB cb);
        }
[DllImport("DelphiRestore.dll")]
        public static extern void GetNewRestoreObject(out IGetNewRestoreObject aGetNewRestoreObject);

并以适当的方法创建对象:

GetNewRestoreObject(out lRestoreObject);

这有效,但我不能使用这个 dll 的回调。我不知道如何在 C# 中声明和使用回调方法。

标签: c#delphicom

解决方案


我解决了这个我用 IntPtr 回调

[MethodImplAttribute(MethodImplOptions.PreserveSig)]
            void Restore(int IdFirm, IntPtr cb);
private void CallbackRestoreStatus([MarshalAs(UnmanagedType.BStr)] string aMess)
        {
            //Do something e.g.: Show Message
        }

接下来

TRestoreCallbackCB SaveStatus = CallbackRestoreStatus;
IntPtr p = Marshal.GetFunctionPointerForDelegate(SaveStatus);
lRestoreObject.Restore(1, p);
GC.KeepAlive(SaveStatus);

作品!


推荐阅读