Exporting classes from WebAssembly to JavaScript with Assemblyscript?

Viewed 1081

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?

2 Answers

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.

Related