[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.

 

 
posted @   Zhentiw  阅读(272)  评论(0编辑  收藏  举报
编辑推荐:
· 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
点击右上角即可分享
微信分享提示