Sharing classes from JavaScript with Rust
Sharing JavaScript classes with Rust is also made easy with #[wasm_bindgen]
. Let's look at how to achieve it.
JavaScript classes are objects with some methods. Rust is a strictly typed language. This means the Rust compiler needs to have concrete bindings. Without them, the compiler complains, because it needs to know about the lifetime of an object. We need a way to ensure the compiler has this API available at runtime.
The extern C function block helps out here. The extern C makes a function name available in Rust.
In this example, let's see how to share a class from JavaScript with Rust:
- Let's create a new project:
$ cargo new --lib class_from_js_world Created library `class_from_js_world` package
- Define the
wasm-bindgen
dependency for the project. Open thecargo.toml
file and add the following content:[package] name = "class_from_js_world" version = "0.1.0" authors = ["Sendil...