To get RUST compile code we will make use of WebAssembly.studio tool.
Go to WebAssembly.studio which is available at Go to https://webassembly.studio/ and it will display you screen as shown below
Click on Empty Rust Project. Once done you will get three files in src/ folder −
Open the file main.rs and change the code of your choice.
I am adding following function that will add two given numbers −
fn add_ints(lhs: i32, rhs: i32) -> i32 { lhs+rhs }
The code available in main.rs is as follows −
#[no_mangle] pub extern "C" fn add_one(x: i32) -> i32 { x + 1 }
Replace the fn add_one with yours as shown below −
#[no_mangle] pub extern "C" fn add_ints(lhs: i32, rhs: i32) -> i32 { lhs+rhs }
In main.js, change the function name from add_one to add_ints
fetch('../out/main.wasm').then( response => response.arrayBuffer() ).then(bytes => WebAssembly.instantiate(bytes)).then(results => { instance = results.instance; document.getElementById("container").textContent = instance.exports.add_one(41); }).catch(console.error);
Replace instance.exports.add_one to instance.exports.add_ints(100,100)
fetch('../out/main.wasm').then( response => response.arrayBuffer() ).then(bytes => WebAssembly.instantiate(bytes)).then(results => { instance = results.instance; document.getElementById("container").textContent = instance.exports.add_ints(100,100) }).catch(console.error);
Click on the build button available on webassembly.studio UI to build the code.
Once the build is done, click on Run button available on UI, to see the output −
We get the output as 200, as we passed instance.exports.add_ints(100,100).
Similarly, you can write a different program for rust and get it compiled in webassembly.studio.
Next Topic:-Click Here
Pingback: WebAssembly - Working with C++ - Adglob Infosystem Pvt Ltd