C++ 类中的成功回调 Emscripten FETCH API

Mat*_*his 2 c++ emscripten webassembly fetch-api

我正在使用 WebAssembly 并尝试从 C++ 发出 HTTPS 请求。我看过Emscripten FETCH API的解决方案并尝试使用它。

为了测试它,我创建了一个Test类,在其中发送如下请求:

void Test::sendRequest() {
    emscripten_fetch_attr_t attr;
    emscripten_fetch_attr_init(&attr);
    strcpy(attr.requestMethod, "GET");
    attr.attributes = EMSCRIPTEN_FETCH_LOAD_TO_MEMORY;
    attr.onsuccess = &Test::onSuccess;
    attr.onerror = &Test::onError;
    emscripten_fetch(&attr, "http://127.0.0.1:5000/");
}
Run Code Online (Sandbox Code Playgroud)

我的 onSuccess 回调如下所示:

void Test::onSuccess(struct emscripten_fetch_t *fetch) {
    printf("Finished downloading %llu bytes from URL %s.\n", fetch->numBytes, fetch->url);
    setText(QString::fromUtf8(fetch->data));
    emscripten_fetch_close(fetch); // Free data associated with the fetch.
}
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试编译时出现错误:

error: assigning to 'void (*)(struct emscripten_fetch_t *)' from incompatible type 'void
  (Test::*)(struct emscripten_fetch_t *)'
attr.onsuccess = &Test::onSuccess;
                 ^~~~~~~~~~~~~~~~
Run Code Online (Sandbox Code Playgroud)

看来我不能将回调函数放在类中,但我需要访问该类才能使用响应修改实例的文本属性。

我尝试使用单例模式定义测试类并从类中删除回调函数。使用这种方法,我可以修改文本属性以获得类的唯一实例,但如果可能的话,我想直接将回调函数放在类中。

mol*_*ilo 5

您不能直接使用非静态成员函数作为回调。

然而,大多数回调接口在某处都有一个“用户数据”字段,用于与发起者进行通信。

emscripten_fetch_attr_t有一个void* userData成员,您可以在其中存储您想要的任何指针。
该指针作为userData回调的参数传递,您只需将其转换回正确的类型。

因此,您可以使用自由函数作为包装回调,并将对象作为“用户数据”:

void onSuccess(struct emscripten_fetch_t *fetch) {
    auto test = static_cast<Test*>(fetch->userData);
    test->onSuccess(fetch);
}

void Test::sendRequest() {
    emscripten_fetch_attr_t attr;
    emscripten_fetch_attr_init(&attr);
    strcpy(attr.requestMethod, "GET");
    attr.attributes = EMSCRIPTEN_FETCH_LOAD_TO_MEMORY;
    attr.userData = this;
    attr.onsuccess = onSuccess;
    // ...
Run Code Online (Sandbox Code Playgroud)

并确保回调触发时该对象处于活动状态。