2014-01-18 23 views
0

我一直在掙扎了幾天找出可能明顯的原因,我不能讓我的代碼編譯我的WlanRegisterNotification回調唯一的工作。回調時是靜態

我有一個類(基於wxThread),其中回調定義:

- 頭文件 -

class TestClass : public wxThread 
{ 
private: 
    static void WlanNotification(WLAN_NOTIFICATION_DATA *wlanNotifData, VOID *p); 
}; 

- 代碼文件 -

我叫WlanRegisterNotification功能,需要上述回調函數作爲參數:

dwResult = WlanRegisterNotification(hClient, WLAN_NOTIFICATION_SOURCE_ALL, true, (WLAN_NOTIFICATION_CALLBACK) WlanNotification, this, 0, &dwPrevNotif); 

Th是編譯和工作正常,但問題是功能被標記爲靜態,所以我不能訪問我的非靜態東西從回調(我需要其他原因)。

我已經嘗試每一個組合我能想到的在回調非靜態的經過:

- 頭文件 -

void WINAPI WlanNotification(PWLAN_NOTIFICATION_DATA data, PVOID context); 

- 代碼文件 -

dwResult = WlanRegisterNotification(hClient, WLAN_NOTIFICATION_SOURCE_ALL, true, (WLAN_NOTIFICATION_CALLBACK)WlanNotification, this, 0, &dwPrevNotif); 

我只是得到:

  • 錯誤C2660: 'WlanRegisterNotification':函數不接受6個 參數

  • 錯誤C2440: '類型轉換':無法從 '重載函數' 轉換爲 'WLAN_NOTIFICATION_CALLBACK'

我中號想着它關係到的typedef莫名其妙:

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

我曾試着用搜索引擎使用WlanRegisterNotification功能的例子,但沒有一個例子,我可以˚F ind是從一個類中調用它的,這在這裏似乎是個問題,所以我真的迷失了。

回答

1

非靜態類方法有一個隱藏的this參數,回調不期望讓別人知道如何填寫。這就是爲什麼你不能使用它作爲回調,除非你1)使用static刪除該參數,或者2)創建一個用作實際回調的thunk,然後讓它在內部委託給一個非靜態類方法。請記住,Windows API是爲C而設計的,而不是C++。在C中沒有類或隱含的指針。

在這種情況下,靜態回調可以訪問類的非靜態成員,因爲你明確地傳遞對象的this指針作爲WlanRegisterNotification()pCallbackContext,然後原樣傳遞給回調的context

class TestClass : public wxThread 
{ 
private: 
    static VOID WINAPI WlanNotification(PWLAN_NOTIFICATION_DATA wlanNotifData, PVOID context); 
}; 

VOID WINAPI TestClass::WlanNotification(PWLAN_NOTIFICATION_DATA wlanNotifData, PVOID context) 
{ 
    TestClass *pThis = (TestClass*) context; 
    // use pThis-> to access non-static members as needed.. 
} 

// get rid of the typecast when passing the callback. If it does 
// not compile, then it is not declared in a compatible manner... 
dwResult = WlanRegisterNotification(hClient, WLAN_NOTIFICATION_SOURCE_ALL, TRUE, &WlanNotification, this, 0, &dwPrevNotif); 
+0

感謝很多很好的解釋,現在它完美地與你寫的變化,現在我知道如何下一次問題出現解決這個問題:) – Peter