编译错误:WebAssembly.compile():预期的魔术词

Val*_*lip 6 javascript google-chrome webassembly

我是 WebAssembly 的新手,并试图让一个基本示例正常工作,但.wasm在 Google Chrome 中加载文件会返回:

编译错误:WebAssembly.compile():预期的魔术字 00 61 73 6d,发现 30 30 36 31 @+0

这是 C++ 代码:

#include <iostream>
using namespace std;

int main() 
{
    cout << "Hello, World!";
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

这是 WASM 文件:https://drive.google.com/open?id =1nvoxoeZ6TA9OVc4JFHSwGIVxuDHFnIU1

我在 Chrome 中执行的代码基于文档

function instantiate(bytes, imports) {
  return WebAssembly.compile(bytes).then(function(m) {
      return new WebAssembly.Instance(m, imports)
  });
}

fetch('simple.wasm').then(function(response) {
    return response.arrayBuffer()
})
.then(function(bytes) {
    var importObject = {
        imports: {
            i: function(arg) {
                console.log(arg)
            }
        }
    };
    return instantiate(bytes, importObject)
})
.then(function(instance) {
    return instance.exports.e()
})
Run Code Online (Sandbox Code Playgroud)

Pet*_*kij 5

问题是您的.wasm文件是十六进制格式而不是二进制格式。

您可能应该检查您的编译标志,但您也可以使用类似以下内容将其从十六进制转换回来

function fromHex(hexString) {
  return new Uint8Array(hexString.match(/[0-9a-f]{2}/g).map(byte => parseInt(byte, 16)));
}

function instantiate(bytes, imports) {
  return WebAssembly.compile(bytes).then(function(m) {
      return new WebAssembly.Instance(m, imports)
  });
}

fetch('simple.wasm').then(function(response) {
    return response.text()
})
.then(function(text) {
    const bytes = fromHex(text);
    var importObject = {
        imports: {
            i: function(arg) {
                console.log(arg)
            }
        }
    };
    return instantiate(bytes, importObject)
})
.then(function(instance) {
    return instance.exports.e()
})
Run Code Online (Sandbox Code Playgroud)