Skip to content

example of calling js from wasm ? #158

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
jeromeetienne opened this issue Jul 4, 2018 · 5 comments
Closed

example of calling js from wasm ? #158

jeromeetienne opened this issue Jul 4, 2018 · 5 comments
Labels

Comments

@jeromeetienne
Copy link

hello, im trying to learn how to call js function from assemblyscript.

is there a working example i could look at ?

thanks

@MaxGraey
Copy link
Member

MaxGraey commented Jul 4, 2018

Hi, Jerome.
You can define functions inside typescript like:

main.ts

declare namespace console {
   function logi(val: i32);
}

// also you can do this
@external("env", "logf")
declare function logf(val: f64);

console.logi(123);
logf(1e10);

// if you not specify this via namespace of @external decorator external will be imported 
// with name of module i.e "main" in this case.

On javascript side you should write something like this:

index.js

WebAssembly.instantiateStreaming(fetch("build/main.wasm"), {
  env: {
    // import as @external("env", "logf")
    logf(value) {
      console.log("logf: " + value);
    },
    abort(msg, file, line, column) {
      console.error("abort called at main.ts:" + line + ":" + column);
    }
  },
  console: {
    // import as console.logi
    logi(value) {
      console.log("logi: " + value);
    }
  }
}).then(result => {
  // const exports = result.instance.exports
});

@MaxGraey
Copy link
Member

MaxGraey commented Jul 4, 2018

Arguments which can be passed between JS <-> WASM is pretty limit it's just i32 and f64. For passing strings, arrays and etc you can use this package

@MaxGraey
Copy link
Member

MaxGraey commented Jul 5, 2018

By the way after approved this PR AssemblyScript in WebAssembly Studio works again

@dcodeIO
Copy link
Member

dcodeIO commented Oct 27, 2018

Closing this issue for now as it hasn't received any replies recently. Feel free to reopen it if necessary!

@trusktr
Copy link
Member

trusktr commented May 27, 2019

For the life of me, I can't figure this out (well, short of diving into the AssemblyScript source code). I posted more details in #384

EDIT: As described in #384, I resorted to using @external syntax, and placed that in a separate file so as not to taint the other files with non-portable syntax.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

4 participants