Call a Rust function from JavaScript
----- Rust -----
#[no_mangle]
pub extern fn add(a: i32, b: i32) -> i32 {
a + b
}
----- SHELL -----
$ rustc -O --target=wasm32-unknown-unknown
example.rs -o example.wasm
----- HTML -----
WebAssembly .instantiateStreaming (
fetch('example.wasm' ), {})
.then(wasm => {
var add_func =
wasm.instance.exports.add;
});
Slide 32
Slide 32 text
Call a Rust function from JavaScript
----- Rust -----
#[no_mangle]
pub extern fn add(a: i32, b: i32) -> i32 {
a + b
}
----- SHELL -----
$ rustc -O --target=wasm32-unknown-unknown
example.rs -o example.wasm
----- HTML -----
WebAssembly .instantiateStreaming (
fetch('example.wasm' ), {})
.then(wasm => {
var add_func =
wasm.instance.exports.add;
});
- WebAssembly has no main()
- It behaves like a JS module/library
Slide 33
Slide 33 text
Call a Rust function from JavaScript
----- Rust -----
#[no_mangle]
pub extern fn add(a: i32, b: i32) -> i32 {
a + b
}
----- SHELL -----
$ rustc -O --target=wasm32-unknown-unknown
example.rs -o example.wasm
----- HTML -----
WebAssembly .instantiateStreaming (
fetch('example.wasm' ), {})
.then(wasm => {
var add_func =
wasm.instance.exports.add;
var result = add_func(10, 20);
console.log(result);
});
Slide 34
Slide 34 text
Call a Rust function from JavaScript
----- Rust -----
#[no_mangle]
pub extern fn add(a: i32, b: i32) -> i32 {
a + b
}
----- SHELL -----
$ rustc -O --target=wasm32-unknown-unknown
example.rs -o example.wasm
----- HTML -----
WebAssembly .instantiateStreaming (
fetch('example.wasm' ), {})
.then(wasm => {
var add_func =
wasm.instance.exports.add;
var result = add_func(10, 20);
console.log(result);
});
Slide 35
Slide 35 text
Call a Rust function from JavaScript
● Can be used to implement compute heavy code in Rust
● Access those functions from JavaScript
● eg: Image resizing algorithm for an image editing online tool
Current challenges
● Text rendering for CJK languages (Font support, garbled text, etc)
● Running native code expecting native syscalls and interfaces (Emscripten)
● Rust graphics ecosystem is still young