【问题标题】:How do I implement a callback from the windows native api in c#?如何在 C# 中实现来自 Windows 本机 api 的回调?
【发布时间】:2011-06-17 14:16:13
【问题描述】:

我有一个本机 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# native wlanapi


【解决方案1】:

是的,您应该使用委托,是的,它可以正常工作。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-04-04
    • 1970-01-01
    • 1970-01-01
    • 2012-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-25
    相关资源
    最近更新 更多