如何在 C# 中实现 Windows 本机 api 的回调?
我有一个本机 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# 中的委托吗?
I have a native api function which looks like:
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
);
I have translated it to C# as:
[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);
The callback function looks like:
typedef VOID ( WINAPI *WLAN_NOTIFICATION_CALLBACK)(
PWLAN_NOTIFICATION_DATA data,
PVOID context
);
I am guessing the C# version will look something like:
public delegate void WLAN_NOTIFICATION_CALLBACK(
IntPtr pWlanNotificationData, IntPtr pContext)
Essentially I have two questions:
Is a delegate the correct object to use for a native method that expects a function pointer?
And if so, will this automatically call the delegate in c# when the notification is received?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,您应该使用委托,是的,它会正常工作。
但是,您必须确保 GC 不会收集您的委托实例。 (通常将其放入字段中)
Yes, you should use a delegate, and yes, it will work fine.
However, you must make sure that the GC does not collect your delegate instance. (typically by putting it in a field)