我有一个 native 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)
本质上我有两个问题:
委托(delegate)是用于需要函数指针的 native 方法的正确对象吗?
如果是这样,收到通知时会自动调用 C# 中的委托(delegate)吗?
最佳答案
是的,您应该使用委托(delegate),是的,它会正常工作。
但是,您必须确保 GC 不会收集您的委托(delegate)实例。 (通常将其放入字段中)
关于c# - 如何在 C# 中实现 Windows native api 的回调?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6387173/