WASM is a typed format. We have declared our doubler
function as taking an int
parameter. What happens if we give it something else?
Let's try with a float
parameter. Put 21.5
as input value and see what happens...
As you can see, the float
input is truncated. Not bad, but not specially good...
WASM currently has four available types:
- i32: 32-bit integer
- i64: 64-bit integer
- f32: 32-bit float
- f64: 64-bit float
Types from languages compiled to WASM are mapped to these types in a suitable way for each language.
In JavaScript there aren't types, so some care has to be done to explicitely do the good conversions when dealing with data to/from WASM.
Let's modify our C source code to receive a double
parameter and return a double
result:
double doubler(double a) {
return 2*a;
}
Generate the WASM and replace the old .wasm
file with the new one.
And now our WASM also works with non-integer numbers:
Taking as base what we have done until here, let's extend our demo to do some other basic functions:
square
: returns the square of the inputhalf
: returns the half of the inputaddition
: takes two parameters and returns the sumsubstraction
: takes two parameters and returns the differenceproduct
: takes two parameters and returns the productdivision
: takes two parametes and returns the division
The UI should look like:
You will need to code the C functions for every operation (you can put them all together in the same source file), update the WASM, and get the exported WASM functions exposed in the JS. Then some click listeners in the HTML and you will be done..
In the next step we will see how we can deal with data not belonging to those basic types. We will see how we can use the shared memory between WASM and JS to communicate data between them.