Click the button to run the WebAssembly code.
Download call-js.rs
Download call-js.wat (WebAssembly text format)
extern {
fn alert(ptr: *const u8, number: u32);
}
#[no_mangle]
pub extern "C" fn run() {
unsafe {
let x = b"Hello World!\0";
alert(x as *const u8, 42);
}
}
The JavaScript code loads the WebAssembly module and has access to the exported function.
window.Module = {};
const imports = {
env: {
alert: function(ptr, number) {
let str = copyCStr(Module, ptr);
alert(str + " -> " + number);
}
}
};
fetchAndInstantiate("./call-js.wasm", imports)
.then(mod => {
Module.memory = mod.exports.memory;
Module.run = mod.exports.run;
Module.dealloc_str = function() {}
Module.run();
});