javascript - Web Worker 使用 Web Assembly 时出错

标签 javascript c emscripten webassembly

我想在 Web Worker 中使用 WebAssembly。

从我的主应用程序中,我像这样启动它:

let w = new Worker('test.js');
w.onmessage = (event) => { console.log(event); };
w.onerror = (event) => { console.error(event); };
w.postMessage({ message: "Hello World" });

然后,我创建了一个文件test.js,如下所示:

self.Module = {
    locateFile: function (s) {
        console.log(s);
        return s;
    }
};

self.importScripts("main.js"); 
// note: `main.js` is the JavaScript glue file created by emcc

self.onmessage = function(messageEvent) {
    console.log(messageEvent); // works!
    console.log(self.Module); // works!
    console.log(self.Module.ccall("test")); // crashes!
}

我收到错误:未捕获类型错误:无法读取未定义的属性“应用”。我不明白为什么 self.Module 未定义,这怎么可能?

我感觉 Web Worker 和 WebAssembly 的范围有些问题,无法很好地协同工作。

感谢您的意见!

最佳答案

问题是console.log()在执行时没有揭示对象的真实状态。进一步挖掘发现,实际上对象Module还没有准备好。

我引用自:https://kripken.github.io/emscripten-site/docs/getting_started/FAQ.html

How can I tell when the page is fully loaded and it is safe to call compiled functions?

Calling a compiled function before a page has fully loaded can result in an error, if the function relies on files that may not be present

[...]

Another option is to define an onRuntimeInitialized function: Module['onRuntimeInitialized'] = function() { ... };

That method will be called when the runtime is ready and it is ok for you to call compiled code.

调整我的 test.js (worker) 文件修复了该问题:

self.Module = {
    locateFile: function (s) {
        console.log(s);
        return s;
    }
    // Add this function
    onRuntimeInitialized: function() {
        test();
    }
};

self.importScripts("main.js"); 
// note: `main.js` is the JavaScript glue file created by emcc

self.data = {};

// to pass data from the main JS file
self.onmessage = function(messageEvent) {
    console.log(messageEvent); // works!
    self.data = messageEvent; // save the data
}

// gets executed when everything is ready.
self.test = function() {
    // we may safely use self.data and self.Module now!
    console.log(self.Module.ccall("test")); // works!
}

关于javascript - Web Worker 使用 Web Assembly 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50751883/

相关文章:

c++ - 在函数指针返回值中转换对指针的引用

javascript - Angular Material 选择重置

Javascript从JSON解析后获取对象的名称

javascript - 基于 Javascript 的验证是否存在安全风险?

javascript - jQuery 特色内容 slider ,每张幻灯片都有动画

C - 将 .doc 文件读取为 32 位二进制数

c - 错误 : control may reach end of non-void function in C

c - getchar 和 putchar 不像名称指定的那样工作

javascript - 使用 ULP 比较 double (最后一位的单位)

javascript - 为 C 编译器指定 header 位置(使用 emscripten 编译 R 代码)