首页 > 解决方案 > C++ 类中的成功回调 Emscripten 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/");
}

我的 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.
}

但是,当我尝试编译时,我有一个错误说:

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

好像不能把回调函数放在类中,但是我需要访问类才能用响应修改实例的文本属性。

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

标签: c++fetch-apiwebassemblyemscripten

解决方案


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

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

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;
    // ...

并确保在回调触发时对象是活动的。


推荐阅读