通过指针调用成员函数



我正在使用vscode、ESPAsyncWebServer和Wifi库在ESP32上进行开发。我正在努力制作我自己的wifi管理器,所以我想在类中放入一些函数,但我在指向成员函数时遇到了一些麻烦。

我有这个定义没有类:

void onNotFound(AsyncWebServerRequest *request){
//Handle Unknown Request
request->send(404);
}
String processor(const String& var)
{
if(var == "HELLO_FROM_TEMPLATE")
return F("Hello world!");
return String;
}

我想从一个班上叫他们女巫是:

My_Wifi.h

class My_Wifi {
private:
Config *config;
DNSServer dnsServer;
AsyncWebServer server;
uint16_t serverPort = 80;
void onNotFound(AsyncWebServerRequest *request);   <------
String processor(const String& var);   <-----
void webServerSetup();
public:
My_Wifi();
void setup(uint16_t port);
void sendJsonDoneResponse(AsyncWebServerRequest *request);
};

My_Wifi.cpp

void My_Wifi::onNotFound(AsyncWebServerRequest *request) {...}
String My_Wifi::processor(const String& var) {...}
void My_Wifi::webServerSetup() {

this->dnsServer.start(53, "*", WiFi.softAPIP());
this->server.onNotFound(this->onNotFound);  <------
this->server
.serveStatic("/wifi_settings.html", SPIFFS, "/wifi_settings.html")
.setTemplateProcessor(this->processor)    <------
.setFilter(ON_STA_FILTER);
...
}

显然,这只是调用函数而不是引用它

如何通过指针调用成员函数?

谢谢你抽出时间。

我试过:

typedef void (My_Wifi::*onNotFoundFn)(AsyncWebServerRequest *request);
void My_Wifi::webServerSetup() {

this->dnsServer.start(53, "*", WiFi.softAPIP());
onNotFoundFn ptr = &My_Wifi::onNotFound;
this->server.onNotFound(*ptr); //this->server.onNotFound(ptr);
...
}

为了调用成员函数,您需要提供成员函数应该被调用的对象,并且它应该匹配

typedef std::function<String(const String&)> AwsTemplateProcessor;

使用lambda捕获this:的示例

.setTemplateProcessor([this](const String& str) { return processor(str); } )

onNotFound的类似lambda应与匹配

typedef std::function<void(AsyncWebServerRequest *request)> ArRequestHandlerFunction;

会是这样的:

server.onNotFound([this](AsyncWebServerRequest* r) { onNotFound(r); });

由于您实际上没有在onNotFound回调中使用this,因此可以使当前回调函数static:

class My_Wifi {
private:
static void onNotFound(AsyncWebServerRequest *request);

并在没有λ的情况下提供:

server.onNotFound(&My_Wifi::onNotFound);

或者,根本不创建成员函数。只需提供lambda:

server.onNotFound([](AsyncWebServerRequest* request){ request->send(404); });

最新更新