In this section, we'll explore the essentials of executing WASM functions directly from our JavaScript code, a crucial aspect when integrating WebAssembly with modern web applications. This will be similar to a basketball coach directly engaging with their star player and implementing game strategies in real-time.
Just as we've compiled our C++ code into WebAssembly modules, we can leverage these modules in our application by loading them into JavaScript. The WebAssembly JavaScript API provides a method called 'WebAssembly.instantiateStreaming()'. This function fetches and compiles a WASM binary and returns a promise that resolves into a 'WebAssembly.instance' object. This object represents an instance of our WASM module and allows us to call the exported WASM functions.
However, we must ensure that we understand the types and number of arguments and the return type of the WASM function that we are about to invoke. The thing to note about WebAssembly and its interface with JavaScript is that currently WASM only understands numerical types which include integers and floating-point values.
Consider a WebAssembly module that exports a function 'add' which takes two integers as arguments and returns an integer. This function can be invoked directly once the WASM module is instantiated, as shown in the code snippet below.
In our upcoming lessons, we'll dive into more complex scenarios like exchanging string and array data between JavaScript and WebAssembly, and handling WebAssembly memory manually. Stay tuned!
xxxxxxxxxx
using namespace std;
extern "C" int add(int a, int b) {
return a + b;
}
int main() {
cout << "WebAssembly module ready" << endl;
}