如何在c#中实现来自windows本机api的回调

本文关键字:本机 windows api 回调 实现 | 更新日期: 2023-09-27 17:59:20

我有一个本地api函数,看起来像:

DWORD WINAPI WlanRegisterNotification(
  __in        HANDLE hClientHandle,
  __in        DWORD dwNotifSource,
  __in        BOOL bIgnoreDuplicate,
  __in_opt    WLAN_NOTIFICATION_CALLBACK  funcCallback,
  __in_opt    PVOID pCallbackContext,
  __reserved  PVOID pReserved,
  __out_opt   PDWORD pdwPrevNotifSource
);

我已经把它翻译成C#:

[DllImport("Wlanapi.dll", EntryPoint = "WlanRegisterNotification")]
public static extern uint WlanRegisterNotification(
     IntPtr hClientHandle, WLAN_NOTIFICATION_SOURCE dwNotifSource,
     bool bIgnoreDuplicate, WLAN_NOTIFICATION_CALLBACK funcCallback,
     IntPtr pCallbackContext, IntPtr pReserved,
     [Out] out WLAN_NOTIFICATION_SOURCE pdwPrevNotifSource);

回调函数看起来像:

typedef VOID ( WINAPI *WLAN_NOTIFICATION_CALLBACK)(
  PWLAN_NOTIFICATION_DATA data,
  PVOID context
);

我猜C#版本会看起来像:

public delegate void WLAN_NOTIFICATION_CALLBACK(
    IntPtr pWlanNotificationData, IntPtr pContext)

本质上我有两个问题:

委托是用于期望函数指针的本机方法的正确对象吗?

如果是,当收到通知时,这会自动调用c#中的委托吗?

如何在c#中实现来自windows本机api的回调

是的,您应该使用委托,是的,它会很好地工作。

但是,您必须确保GC不会收集您的委托实例。(通常通过将其放在字段中)