1

In main.cpp:

#include <emscripten.h>

EMSCRIPTEN_KEEPALIVE
extern "C" {
    const char *testFunc(const char *parameter) {
        return parameter;
    }
}

Compilation command:

em++ .\main.cpp -s EXPORTED_RUNTIME_METHODS='["ccall", "cwrap"]' -o wasm_module.js;

In the Vue component:

import wasmModule from "./wasm/wasm_module.js"; // I put both WASM and JS wrapper in the same folder

export default {
  created() {
    console.log(wasmModule);
  }
};

In vue.config.js, I've added:

module.exports = {
  configureWebpack: {
    module: {
      rules: [
        {
          test: /\.wasm$/,
          loaders: ["wasm-loader"]
        }
      ]
    }
  }
};

But, I'm getting:

Uncaught (in promise) RuntimeError: abort(CompileError: WebAssembly.instantiate(): expected magic word 00 61 73 6d, found 3c 21 44 4f @+0) at Error

UPDATE

I ended using a slightly different compilation command, which was given by a member of the official WebAssembly Discord server:

em++ .\main.cpp -s EXPORTED_RUNTIME_METHODS'["call", "cwrap"]' -s MODULARIZE -s ENVIRONMENT="web" -s EXPORTED_FUNCTIONS='["_testFunc"]' -o wasm_module.js

Then, I dug up in the wasm_module.js and found a variable scriptDirectory, which is responsible for locating the wasm_module.wasm file
After logging it to the console, it outputted:

http://localhost:8080/js/

So, I moved the .wasm file into public/js, and by the way, deleted the configureWebpack entry as it's now useless

Now, I could:

import wasmModule from "./wasm/wasm_module.js";
export default {
  async created() {
    const instance = await wasmModule();
    const func = instance._testFunc();
  }
};

However, there is still one problem:
No matter the arguments I pass into _testFunc, I'm getting the output 0 every single time

avi12
  • 2,000
  • 5
  • 24
  • 41

1 Answers1

0

Turns out the solution was pretty simple

main.cpp

#include <emscripten.h>
#include <string>

EMSCRIPTEN_KEEPALIVE
extern "C" {
  std::string* testFunc(std::string* parameter) {
    return parameter;
  }
}

Compilation:

em++ .\main.cpp -s EXPORTED_RUNTIME_METHODS='["ccall", "cwrap"]' -s MODULARIZE -s EXPORTED_FUNCTIONS='["_testFunc"]' -o wasm_module.js

The wasm_module.js should be somewhere under src/
The wasm_module.wasm should be under public/js/

Then, the Vue component:

import moduleWasm from "./path/to/wasm_module.js";

export default {
  async created() {
    const instance = await moduleWasm();
    const func = instance.cwrap("testFunc", "string", ["string"]); // Note that: (func_name, return_type, [parameter_types])
    console.log(func("Hello World") === "Hello World"); // true
  }
};
avi12
  • 2,000
  • 5
  • 24
  • 41