2011-06-17 41 views
1

我有一個原生API函數,它看起來像:如何在c#中實現從Windows本機API的回調?

[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 
); 

我猜

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# C#版本將如下所示:

​​

基本上我有兩個問題:

委託是一個正確的對象,用於需要函數指針的本地方法嗎?

如果是這樣,當收到通知時,這會自動調用C#中的委託嗎?

+0

請參閱http://www.pinvoke.net/default.aspx/wlanapi.WlanRegisterNotification瞭解委託人應該怎麼樣。 – RBaarda

+0

實際上並沒有關於代表的任何信息:( – FlyingStreudel

+1

在頁面頂部它說:public delegate void WLAN_NOTIFICATION_CALLBACK(ref WLAN_NOTIFICATION_DATA notificationData,IntPtr context); – RBaarda

回答

2

是的,你應該使用委託,是的,它會正常工作。

但是,您必須確保GC不會收集您的委託實例。 (通常放在一個字段中)

+0

+1在錯誤發生之前糾正錯誤 – FlyingStreudel