Exporting classes from WebAssembly to JavaScript with Assemblyscript?
Asked Answered
V

1

6

I'm experimenting with compiling TypeScript to WebAssembly using Assemblyscript and I'm trying to export a class from WebAssembly so that it may be used in the JavaScript. To clarify, I want to be able to construct new instances of the class in a .js file even if the class is defined in a .wasm.

I have done some research and experimenting and it seems like Assemblyscript will export the class methods as functions instead of exporting the class as a whole.

This is how I want it to look on the WebAssembly side:

export class Point {
  public x: i32;
  public y: i32;

  constructor(x: i32, y: i32) {
    this.x = x; 
    this.y = y;
  }
}

And this is what I want to accomplish on the JavaScript side:

// Omitted code for instatiating the Wasm Module

var exports = object.instance.exports; // The exports of the Wasm instance
var Point = exports.Point; // The Point class

let point = new Point(0, 0) // Construct a new Point

So I'm wondering if anyone knows of a way to achieve this (or at least similar) functionality?

Vanillin answered 11/6, 2019 at 12:11 Comment(1)
I managed to find a solution and figured I should post it here. The main author (at least I think so) of AssemblyScript has written a loader which is part of the project that I didn't find at first. It can be found here: github.com/AssemblyScript/assemblyscript/tree/master/lib/loader With a short guide of how to use it for exporting classes from Wasm to JavaScript here: github.com/AssemblyScript/docs/blob/master/basics/loader.mdVanillin
U
0

WebAssembly has a very basic type system, which has just four numeric types. In order to compile even the most basic types like strings to WebAssembly requires the creation of quite a bit of 'glue code' (in the case of strings, the data is exchanged via linear memory).

To achieve what you describe is possible, but would require the creation of more 'glue code' that AssemblyScript is currently able to produce.

Unconventional answered 11/6, 2019 at 12:37 Comment(1)
Thanks, I figured I would need to manually produce some glue code for this. I have exported classes like this using Rust and tried to look at the glue code produced by Rust's wasm-pack. I felt quite lost so I was hoping someone could point me in the right direction.Vanillin

© 2022 - 2024 — McMap. All rights reserved.