c++ - 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 类,并从类中删除回调函数。使用这种方法,我可以修改获取类的唯一实例的文本属性,但如果可能的话,我想直接将回调函数放在类中。
解决方案
您不能直接将非静态成员函数用作回调。
但是,大多数回调接口在某处都有一个“用户数据”字段,用于与发起者进行通信。
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;
// ...
并确保在回调触发时对象是活动的。
推荐阅读
- grep - BBEdit:当反向引用紧跟一个数字时如何编写替换模式
- reactjs - 如何在 React+Graphql 中设置 resetToken?
- laravel - 部署者 Laravel 迁移失败
- c++ - 在 C++ 中声明方法时出现测试问题
- android - 在实现地图视图的两个片段之间共享数据的最佳方式?
- ubuntu - Github Action- 如何重启会话?
- python - 为什么打印格式会抛出 NoneType 错误?
- javascript - JavaScript:无法将 for 循环的索引与另一个数字进行比较
- ansible - Ansible - 调用救援后跳过块中的其他任务
- python - 如何解决Kivy中的“.kv多次加载”错误?