examples icon indicating copy to clipboard operation
examples copied to clipboard

Cannot access WebAssembly module exports before synchronous instantiation

Open ghost opened this issue 5 years ago • 4 comments
trafficstars

I get a problem when trying to access an uninitialized wasmModule. I used the example given here. I was attempting to perform a synchronous instantiation.

ghost avatar Aug 08 '20 14:08 ghost

For async initialization you should defer log and wrap it to main for example:

javascript:

(async () => {
  const wasmModule = await loader.instantiate(module_wasm, {
    myConsole: {
      log(ptr) {
        console.log(wasmModule.exports.__getString(ptr));
      }
    }
  });
  wasmModule.exports.main();
})();

assemblyscript:

@external("myConsole", "log")
declare function log(str: string): void;

export function main(): void {
  log("Hello world!");
}

MaxGraey avatar Aug 08 '20 15:08 MaxGraey

Hi! Thanks for dropping the comment. I am getting an error that has to do with accessing the wasmModule variable from within the log function in the myConsole object (Node/JavaScript API - not within AssemblyScript). The same thing happens in both (a)synchronous cases. Here is the error signature:

UnhandledPromiseRejectionWarning: ReferenceError: Cannot access 'wasmModule' before initialization

ghost avatar Aug 08 '20 15:08 ghost

Hmm, but it works in playground

MaxGraey avatar Aug 08 '20 15:08 MaxGraey

The error appears to indicate that the module is being accessed before instantiation returns, i.e. code accessing the module runs before the await finished respectively then is called. This might also happen indirectly, for example if the module calls an import from WebAssembly during startup that in turn attempts to call back into WebAssembly from JS. If the latter is the case, --explicitStart may help (calling exports._start() manually after instantiation is complete).

dcodeIO avatar Aug 08 '20 17:08 dcodeIO