WASM 反应模块解析失败:未检测到魔术头 [英] WASM react module parse failed: magic header not detected
问题描述
我正在尝试在 React 项目中加载一个简单的 Web 程序集模块.wasm 模块是使用 MODULARIZE
选项编译的.
I'm trying to load a simple web assembly module in a react project. The wasm module was compiled with the MODULARIZE
option.
从 文档 我尝试将其合并到我的代码如下:
From the documentation I've tried incorporating this into my code as follows:
fetch('./my-library.wasm')
.then(response => response.arrayBuffer())
.then(bytes => WebAssembly.instantiate(bytes))
.then(results => {
console.log("do something");
});
理想情况下,我希望将结果存储在 state
中,以便我可以在整个代码中访问模块(替换控制台日志).
Where ideally I would like to store the results in the state
so I can access the module throughout the code (replacing the console log).
不幸的是,这给了我错误
Unfortunately this gives me the error
Unhandled Rejection (CompileError): wasm validation error: at offset 4: failed to match magic number
我错过了什么?在没有 MODULARIZE
的情况下编译也会出现此错误.
What am I missing? Compiling without MODULARIZE
also gives this error.
推荐答案
我试过 this 和 this 与我的模块,但他们没有't 工作所以尝试将 wasm 文件直接放在公共文件夹中并从那里获取它(另请参阅:这个).它需要针对 wasm 模块的用例(内存设置等)进行一些调整.我的具体情况现在看起来像这样
I tried this and this with my module but they didn't work so tried putting the wasm file directly in the public folder and fetching it from there (see also: this). It needed some tweaking specific to the use-case of the wasm module (memory settings, etc). My specific case looks like this now
componentDidMount() {
this.loadWasm();
}
loadWasm() {
const path = process.env.PUBLIC_URL + '/my-library.wasm';
const importObject = {
env: {
memoryBase: 0,
tableBase: 0,
memory: new WebAssembly.Memory({initial: 256, maximum: 1024}),
table: new WebAssembly.Table({initial: 256, element: 'anyfunc'}),
__assert_fail: function() {
// todo
},
emscripten_resize_heap: function() {
// todo
},
emscripten_memcpy_big: function() {
// todo
},
setTempRet0: function() {
// todo
}
}
};
WebAssembly.instantiateStreaming(fetch(path), importObject).then(obj => {
// do stuff
});
}
编辑
由于 react 的路由问题,我在从其 javascript 包装器(例如 a.out.js)中获取 wasm 时遇到了幻数错误.最后,我决定将 javascript 作为依赖项包含在 index.html 文件中并不那么麻烦.这样做的好处是不必与 webpack 和 webpack 混淆,而不必与 emcc 生成的 js 混淆.此外,不直接加载 wasm 模块,emcc 生成的 js 负责设置 importObject
.
I was getting the magic number error when fetching the wasm from its javascript wrapper (e.g. a.out.js) because of a routing problem with react. At the end of it all I decided it was less of a hassle to just include the javascript as a dependency in the index.html file. This has the advantage of not having to mess with webpack and webpack non messing with the emcc-generated js. Also, not loading the wasm module directly, the emcc-generated js takes care of setting the importObject
.
这篇关于WASM 反应模块解析失败:未检测到魔术头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!