For this lesson, I'm using a project called WasmFiddle which allows me to write C in the box over here and compile it into WebAssembly in the browser, as well as running it to experiment with it.
There's going to be many, many languages that compile into WebAssembly. This is one of the major benefits of WebAssembly, but if we want to play around with it and understand WebAssembly, C is one of the best levels to do this at, because it's a very low level abstraction on top of the raw assembly code.
Let's create, for example, a get_square_root function. The return value of this function is going to be a floating point number. By default, float is a 32-bit type, and then we're going to call this function get_square_root. The input into this function is going to be a float number again.
Then, we're just going to return the square root of a number. In C, the square root function is loaded from the math header, so I'm just going to include that header at the top. We can now build the code.
At the bottom, our WebAssembly module comes up. We can see that it's exporting our get_square_root function, and we can see the function defined over here as well, where it's taking an input float 32, returning a float 32, and then taking the square root.
Obviously, as you write more complicated C-code, it gets much more difficult to read this indecipherable , but there's a very, very direct translation between the two.
If you want to play around with the outputs, this is a very simple, synchronous instantiation of WebAssembly that comes by default when you load up WasmFiddle. On this wasm instance or exports, we can access any of our functions in the C code.
I'm going to run the get_square_root function over here. I can call it with any number and then use the run feature.
To use this WebAssembly in our own projects, I'm going to click the "Download WASM" button. I'm then going to locate the program.wasm file in the local projects and open up the html. To load the wasm, I'm going to use a helper function called fetchAndInstantiateWasm. This will asynchronously load a WebAssembly file from a URL, execute it, and returned back the exports of that WebAssembly module.
I can call this function directly, passing the URL of our program file, which is program.wasm, and this will return a promise, returning the exact exports of the wasm file. I can then assign our get_square_root function, directly from the wasm module exports available, as the name get_square_root. If you're on this in the browser, we can see get_square_root is now available.