wasm-bindgen

wasm-bindgen is used for facilitting high-level interactions between wasm modules and JavaScript. You can use it to import Javascript functions/Web APIs for use in Rust or export WASM functions defined in Rust for use in Javascript. This interoperability is useful in ensuring that a rustwasm program have access to all the available APIs of the browser and existing Javascript applications can flexibly plug in a wasm module to speed up performance.

Import Javascript Functions for use in rustwasm

The following lib.rs import the 'window.alert' function from the web to rustwasm.

use wasm_bindgen::prelude::*;

#[wasm_bindgen]
extern "C" {
    fn alert(s: &str);
}

#[wasm_bindgen(start)]
pub fn main() -> Result<(), JsValue> {
	alert("Hello World"); 
    Ok(())
}

After compiling the above, simply use the following HTML to run the wasm-bindgen 'Hello World' example.


<html>
    <head>
        <meta content="text/html;charset=utf-8" http-equiv="Content-Type"/>
    </head>
    <body>
            
        <script type="module">
            import init from './pkg/hello_web.js';  
            async function run() {
            await init();
            }    
            run();
        </script>
    </body>  
</html>

Export rustwasm function for use in Javascript

use wasm_bindgen::prelude::*;

    #[wasm_bindgen]
    extern "C" {
        fn alert(s: &str);
    }
    
    #[wasm_bindgen]
    pub fn add(a: u32, b: u32) -> u32 
    {
        a + b
    }

    #[wasm_bindgen(start)]
    pub fn main() -> Result<(), JsValue> {
        alert("Hello World"); 
        Ok(())
    }
    

Use exported Rust things from JavaScript with ECMAScript modules!


        <html>
            <head>
                <meta content="text/html;charset=utf-8" http-equiv="Content-Type"/>
            </head>
            <body>
                    
                <script type="module">
                    import init from './pkg/hello_web.js';  
                    async function run() {
                    await init();
                    const result = add(1, 2);
                    console.log(`1 + 2 = ${result}`);
                    if (result !== 3)
                      throw new Error("wasm addition doesn't work!");    
                    }    
                    run();
                </script>
            </body>  
        </html>

        

Structs