我的wlanregisternotification回调仅在回调为静态时工作

My WlanRegisterNotification callback is only working when the callback is static

本文关键字:回调 静态 工作 wlanregisternotification 我的      更新时间:2023-10-16

我已经挣扎了几天,以找出可能无法编译代码的明显原因。

我有一个定义回调的类(基于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);

此编译和工作正常,但是问题在于功能标记为静态,因此我无法从回调中访问我的非静态内容(我出于其他原因需要)。

我尝试了我可以想到的每种组合,以通过静态回调传递:

- 标头文件 -

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:'type cast':无法转换为"超载功能"到'wlan_notification_callback'

我认为它与Typedef有关:

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

我尝试搜索使用WlanregisterNotification函数的示例,但是我无法找到的示例是从类中调用的示例,这似乎是一个问题,所以我真的迷路了。

一个非静态类方法具有隐藏的 this参数,该参数并不期望,更不用说更不用说知道如何填充了。这就是为什么您不能将其用作回调,除非您是任何一个。)使用static删除该参数,或2)创建一个用作实际回调的thunk,然后将其内部委派给非静态类方法。请记住,Windows API是为C而不是C 设计的。c。

中没有类或隐式this指针

在这种情况下,静态回调可以访问类的非静态成员,因为您明确将对象的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);