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

问题描述 投票:1回答:1

我正在使用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类,并从该类中删除回调函数。通过这种方法,我可以修改text属性以获得类的唯一实例,但如果可能的话,我想直接将回调函数放在类中。

c++ fetch-api webassembly emscripten
1个回答
0
投票

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

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

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

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

© www.soinside.com 2019 - 2024. All rights reserved.