WebAssembly (WASM)是一种用于基于堆栈的虚拟机的二进制指令格式,其设计宗旨是快速高效。它是一种底层的类似程序指令集的语言,运行在浏览器中,并提供了一种以接近本机速度执行代码的方法。所有主要的web浏览器都支持WASM,包括Chrome、Firefox、Safari和Edge。
WebAssembly系统接口(WASI)是一个允许WebAssembly代码访问底层操作系统和文件系统的接口。它为WebAssembly模块提供了一组标准化的系统调用,以便与宿主环境进行交互。这允许WebAssembly代码在后端运行。
可以简单类比为,如果WASM是JavaScript, WASI就是Node.js。
WASM的另一个重要方面是它与语言无关,这意味着用各种编程语言(如Rust、C++或C)编写的代码可以编译为WASM并在浏览器中运行。这为开发人员构建web应用程序提供了更多的选择,并允许他们利用不同语言的优势。
cargo new hello-wasm
fn main() {
println!("Hello, world!");
}
执行cargo build,这将创建一个二进制文件并将其放在target/debug下。你可以直接执行:
./target/debug/hello-wasm
rustup target add wasm32-wasi
cargo build --target wasm32-wasi
target
├── CACHEDIR.TAG
├── debug
│ ├── build
│ ├── deps
│ ├── examples
│ ├── hello-wasm
│ ├── hello-wasm.d
│ └── incremental
└── wasm32-wasi
├── CACHEDIR.TAG
└── debug
├── build
├── deps
├── examples
├── hello-wasm.d
├── hello-wasm.wasm
└── incremental
请注意,这目前是一个预览功能,仅在Docker Desktop上可用。为了能够在Docker Desktop中构建或运行WASM容器,首先需要从设置中启用“容器提取和存储功能”。
# syntax=docker/dockerfile:1
FROM scratch
COPY ./target/wasm32-wasi/debug/hello-wasm.wasm /hello.wasm
ENTRYPOINT [ "hello.wasm" ]
docker buildx build --platform wasi/wasm32 -t hello-wasm .
docker image ls
hello-wasm latest e2f29c7ab88a 2 minutes ago 520kB
docker run \
io.containerd.wasmedge.v1 \ =
--platform=wasi/wasm32 \
hello-wasm
Hello, world!