AssemblyScript / examples

A collection of AssemblyScript examples.
https://assemblyscript.org
MIT License
283 stars 50 forks source link

Cannot access WebAssembly module exports before synchronous instantiation #6

Open ghost opened 3 years ago

ghost commented 3 years ago

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.

MaxGraey commented 3 years ago

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!");
}
ghost commented 3 years ago

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
MaxGraey commented 3 years ago

Hmm, but it works in playground

dcodeIO commented 3 years ago

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).