c# - 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# 中声明和使用回调方法。
解决方案
我解决了这个我用 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);
作品!
推荐阅读
- java - 无法连接到android上的本地socketIO nodejs服务器
- python - GtkFileChooserNative 和 IFileDialog 和额外的小部件
- python - 如果只输入了我列表中的部分单词,我的代码会检查它是否为真并且部分单词是否在列表中
- java - 从数据库崩溃中检索数据
- swi-prolog - 如何在 SWI-Prolog 的设置字符串中设置换行符?
- c++ - C++ 类:构造函数的列表初始化变得无用了吗?
- node.js - 类型错误:chatManager.connect(...) 未定义
- etw - 如何使用 C# EventSource 和 ETW 实现连续日志记录?
- autohotkey - 请求支持 CapsLock 密钥代码
- kubernetes - 监控每个命名空间的资源