[Rust] Load a WebAssembly Function Written in Rust and Invoke it from JavaScript
In this lesson we are going to setup a project from scratch by introducing the JavaScript snippet to load a WebAssembly module. We demonstrate two different ways and showcase the benefit of the streaming solution. Once the module is loaded we can invoke a function previously exported from our Rust code.
Create a new project as a library:
cargo new --lib utils
Go to the project folder, modify Cargo.toml:
[package] name = "utils" version = "0.1.0" authors = ["zhentian-wan <answer881215@gmail.com>"] edition = "2018" [dependencies] [lib] crate-type = ["cdylib"]
Create an function in src/lib.rs:
#[no_mangle] pub extern fn add_one(x: u32) -> u32 { x + 1 }
The extern
keyword is needed to create an interface, so that this function can be invoked from other languages. The function accepts a value x
, which is an unsigned integer, which is incremented by one and returned. In addition, we need to add a no-mangle
annotation to tell the Rust compiler not to mangle the name of this function.
Run:
cargo build --target wasm32-unknown-unknown --release
wasm-gc target/wasm32-unknown-unknown/release/utils.wasm -o utils.gc.wasm
Create an index.html file and load utils.gc.wasm file we just generated:
<!DOCTYPE html> <html> <head> <script> WebAssembly.instantiateStreaming(fetch("utils.gc.wasm")) .then(wasmModule => { const result = wasmModeult.instance.exports.add_one(3); const text = document.createTextNode(result); document.body.appendChild(text); }); </script> <head> <body></body> <html>
Run:
http
Open the broswer we should see the output 4.
Be aware, instantiate streaming requires that our WASM file must be served with a content type, application/wasm. Fortunately, our HTTP server already does so.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2016-10-19 [RxJS] Connection operator: multicast and connect
2016-10-19 [RxJS] AsyncSubject: representing a computation that yields a final value