CompileError: WebAssembly.compile(): expected magic word

Viewed 2569

I'm new to WebAssembly and trying to get a basic example working, but loading the .wasm file in Google Chrome returns:

CompileError: WebAssembly.compile(): expected magic word 00 61 73 6d, found 30 30 36 31 @+0

This is the C++ code:

#include <iostream>
using namespace std;

int main() 
{
    cout << "Hello, World!";
    return 0;
}

And this is the WASM file: https://drive.google.com/open?id=1nvoxoeZ6TA9OVc4JFHSwGIVxuDHFnIU1

Code that I'm executing in Chrome, based on documentation:

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()
})
1 Answers

The problem is that your .wasm file is in a hex format instead of binary.

You should probably check your compile flags, but you can also convert it back from hex with something like this or like this:

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()
})
Related