3

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?

Paltze
  • 57
  • 1
  • 5
  • You don't export classes, simple as that. You can only export functions that will call methods on an instance passed to them. – Bergi Apr 18 '22 at 11:57
  • @Bergi I suppose I can split my class into an object containing all the properties, and all the methods as independent functions that modify and use the values in the object. But I need to run multiple instances of the library so I think I will handle raw calculations in WASM and a JS class over it for other things. Thanks for clarifying! – Paltze Apr 19 '22 at 04:52

1 Answers1

2

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?

JairusSW
  • 46
  • 4
  • 1
    I gave up on trying to export classes from AssemblyScript. I now just handle raw calculations in AssemblyScript and a wrapper class in JS. Thanks for trying to help me though. – Paltze Apr 29 '22 at 10:01
  • Honestly, I would do the same in practice. – JairusSW Jan 16 '23 at 05:07