The lightweight WebAssembly virtual machine only supports very limited numeric data types. The host application, on the other hand, probably needs to handle complex data types. One such complex data type is the string. The string is complicated because it contains data of unknown size and of unknown structure (i.e., encoding). The host application cannot directly pass string data to and from WebAssembly. It must convert string values to and from numeric values and arrays. You can read more about it here.
wasm-pack
. It compiles Rust source code into a WebAssembly bytecode program, and then generates a JavaScript module that can interact with the WebAssembly program. The generated code takes care of input / output data encoding and management. This makes it much easier for JavaScript developer to call WebAssembly functions. Follow the steps below to install Rust and the wasm-pack
tool.cargo
project. Since this program is intended to be called from a host application, not to run as a stand-alone executable, we will create a hello
project.Cargo.toml
file to add a [lib]
section. It tells the compiler where to find the source code for the library and how to generate the bytecode output. We also need to add a dependency of wasm-bindgen
here. It is the utility wasm-pack
uses to generate the JavaScript binding for the Rust WebAssembly program.src/lib.rs
. You can actually define multiple external functions in this library file, and all of them will be available to the host JavaScript app via WebAssembly. The #[wasm_bindgen]
tag instructs the build tools to generate communication interfaces both in Rust / WebAssembly and in the JavaScript module..wasm
file is the WebAssembly bytecode program, and the .js
file is the JavaScript module.hello_lib.js
module, it is very easy to write JavaScript to call WebAssembly functions. After the import
, the WebAssembly say()
function now becomes a JavaScript function with the same name. The complete web page source file is here.hello_lib_bg.wasm
program is loaded by the hello_lib.js
module. Put this HTML file and the hello_lib.js
and hello_lib_bg.wasm
files on a web server and you can now access the web page to “say hello” to any name you enter on the page.