How to export classes from AssemblyScript?

1k views Asked by At

I am trying to port my simple collision detection library from JavaScript to WebAssembly for speed. After looking up languages that compile to WASM, AssemblyScript seemed to be perfect as I only needed to add types to my JS file. The whole library is a Class and after adding types I tried to compile it but it does not compile properly. For example, compiling this using command npx asc path/to/main.ts -o wasm.wasm --exportRuntime -t wasm.wat --bindings esm:

export class Test {
    constructor() {
        console.log('Successful!');
    }
};

Resulted in this error:

WARNING AS235: Only variables, functions and enums become WebAssembly module exports.

 export class Test {
              ~~~~
 in main.ts(1,14)

After seeing the error I tried to fix it by doing:

class Test {
    constructor() {
        console.log('Successful!');
    }
};

export function getTest(): Test {
    return Test;
};

But that resulted in another error:

ERROR AS234: Expression does not compile to a value at runtime.

     return Test;
            ~~~~
 in main.ts(8,12)

FAILURE 1 compile error(s)

So I tried to do this:

class Test {
    constructor() {
        console.log('Successful!');
    }
};

export function getTest(): Test {
    return new Test();
};

That compiled successfully and after calling getTest from JavaScript I got an output Successful! in the console but it did not return the initiated class, instead I got this: [Number (Internref): 18624].

So I serched on the internet for solution and found this. But the accepted solution there is to use AssemblyScript Loader, which is deprecated. I also know about as-bind but it states that it wraps around AssemblyScript Loader so, indirectly, it is also deprecated. So how can I export classes from AssemblyScript?

2

There are 2 answers

3
JairusSW On BEST ANSWER

So, there currently is no way to export classes. However, you can call methods on a class from JavaScript or call a get or set method to modify data. I believe it is planned to have functions named like Vec3#constructor Vec3#magnitude ect..

Exporting classes from WebAssembly to JavaScript with Assemblyscript?

0
Stefan Gohlke On

A short update regarding this question:

I also tried this using AssemblyScript 0.27.22 and ran into the same issue. According to the manual (https://www.assemblyscript.org/compiler.html#host-bindings) complex objects are returned as reference (pointer) while for simple objects it is possible to return a copy of them.

class Person {
  firstname: string;
  lastname: string;
}

export function createPerson(): Person {
  return {firstname: 'AFirstName', lastname: 'ALastName'};
}

I used this example in my Typescript file and logged the result in my JS/HTML file, it should look like this: "Generate person: {firstname: 'AFirstName', lastname: 'ALastName'}"

While this is still not perfect it is a step to a better type/object support.