We can invoke WebAssembly functions from JavaScript by loading the wasm module and making the function calls in the JavaScript environment. Imagine we've compiled a very simple C++ program (like the one featured in the code
block) that prints Hello from WebAssembly!
. The wasm module contains our print statement that we want to call from JavaScript.
1WebAssembly.instantiateStreaming(fetch('main.wasm')).then(wasmModule => {
2 wasmModule.instance.exports._Z14print_statementv();
3});
Considering we have our main.wasm
file available at the same location as our JS file, we use WebAssembly.instantiateStreaming
combined with fetch
to load and compile our wasm module directly from the server. After it's ready, we get a WebAssembly.Module
object, and we can access its exported functions. In this case, wasmModule.instance.exports._Z14print_statementv()
is our Hello from WebAssembly!
message.
Note that the C++'s print_statement()
translated into _Z14print_statementv()
. The translation is a result of name mangling in C++, a way for the compiler to generate unique names for each function.
Remember, using WebAssembly functions from JavaScript is pivotal for a good integration between low-level wasm modules and your high-level JavaScript code. Since WebAssembly isn't designed to manipulate the DOM directly, your JavaScript code acts as a bridge between wasm modules and web APIs.
xxxxxxxxxx
using namespace std;
int main() {
cout << "Hello from WebAssembly!";
return 0;
}