How to import javascript function from Wasm?
# workers-help
w
I'm trying to import a javascript function from Wasm. For the
worker.ts
, I defined a function `consoleLog`:
Copy code
ts
import mod from '../build/out.wasm';

const importObject = {
  imports: {
    consoleLog: (arg: number) => {
      console.log(`Hello from JavaScript: ${arg}`);
    },
  },
};

const instance = await WebAssembly.instantiate(mod, importObject);

export default {
  async fetch() {
    const retval = instance.exports.add100(2, 5);
    return new Response(`Success: ${retval}`);
  },
};
And I'm using AssemblyScript for the Wasm side:
Copy code
ts
declare function consoleLog(arg0: i32): void;

export function add100(a: i32, b: i32): i32 {  
  // consoleLog(100);
  return a + b + 100;
}
Since I commented the
//consoleLog(100);
out, it works well after compile:
Copy code
sh
asc assembly/index.ts --outFile build/out.wasm --optimize
However, when I un-commented it as:
Copy code
ts
declare function consoleLog(arg0: i32): void;

export function add100(a: i32, b: i32): i32 {  
  consoleLog(100);
  return a + b + 100;
}
I got an error after `asc`:
Copy code
shell
service core:user:wasm102: Uncaught Error: No such module "bea1e1adde3b4c3c5cbc0842c823a3c93a930163-out.wasm".
  imported from "worker.js"
✘ [ERROR] MiniflareCoreError [ERR_RUNTIME_FAILURE]: The Workers runtime failed to start. There is likely additional logging output above.
Just wondering what's the appropriate way to import javascript function from Wasm?
s
it looks correct to me, I am not familiar with using assemblyscript, but what you probably need some way of telling it to look for the
Copy code
consoleLog
function in the object you call
Copy code
imports
. In emscripten, for example, the default import object that it looks for is called
Copy code
env
, and if you want to import a function from a different object you have to give use a macro to tell the compiler the name of the object you want to import from.