[WASM] Set up wasm-bindgen for easy Rust/JavaScript Interoperability

Interoperability between JavaScript and Rust is limited to numerics and accessing memory directly. Since this can be exhausting and overwhelming to do manually the Rust/Wasm team has created the wasm-bindgen project to facilitate high-level interactions between Rust and JavaScript.

 

WebAssembly programs operate on a limited set of value types. Due to this, the functions bridging between JavaScript and Rust only allow for primitive numeric types, like integer or float. 

So if you pass a string between Javascript and WASM, it convert to a number.

 

This is not what we wanted to achieve here. Fortunately, we can work around this by directly reading or writing to WebAssembly's memory using JavaScript. Each WASM module has a linear memory, which is initialized during instantiation.

 

While sometimes accessing memory directly can be useful, in most cases, it's quite cumbersome. That's why the generic bindgen-style framework, wasm-bindgen, was created. The framework makes it possible to write idiomatic Rust function signatures that map to idiomatic JavaScript functions automatically.

 

To get started, we add wasm-bindgen as a dependency to our Cargo configuration.

复制代码
# Cargo.toml

[package]
name = "utils"
version = "0.1.0"
authors = ["zhentian-wan <answer881215@gmail.com>"]
edition = "2018"

[dependencies]
wasm-bindgen="0.2"

[lib]
crate-type = ["cdylib"]
复制代码

 

lib.rs:

复制代码
#![feature(use_extern_macros)]

extern crate wasm_bindgen;

use wasm_bindgen::prelude::*;

#[wasm_bindgen(module = "../domUtils")]
extern {
  fn appendStringToBody(s: &str);
}

#[wasm_bindgen]
pub extern fn run() {
  appendStringToBody("Hello World");
}
复制代码

 

We compile our Rust library using wasm-pack build

wasm-pack build

This way, we can pass types, like strings, into our Rust code without manually having to take care of the conversion.

 

domUtils.js:

export const appendStringtoBody = (value) => {
  const text = document.createTextNode(value);
  document.body.appendChild(text);
}

When using wasm-bindgen, we then can declare that the module should be imported.

 

Run:

wasm-pack build

npx webpack-dev-server

 

posted @   Zhentiw  阅读(468)  评论(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-23 [RxJS] Multicasting shortcuts: publish() and variants
2016-10-23 [RxJS] RefCount: automatically starting and stopping an execution
2015-10-23 [Angular 2] Inject Service
2015-10-23 [Angular 2] Use Service use Typescript
点击右上角即可分享
微信分享提示