返回

WebAssembly 一键入门:揭秘 Hello, World 的奥秘

前端

初探 WebAssembly

WebAssembly 是一种新的编译目标,它让高级语言如 C、C++ 和 Rust 能够在网页上高效运行。通过编译源代码到 WebAssembly 模块,开发者可以构建高性能的客户端应用。本篇文章将指导读者如何使用 Rust 工具链和 LLVM 工具链来编写并部署第一个 WebAssembly 程序。

准备开发环境

安装 Rust

Rust 提供了强大的工具链来生成 WebAssembly 模块,安装 Rust 非常简单。访问 rustup.rs 并跟随指示进行安装即可。确保使用最新版的 wasm32-unknown-unknown 目标。

安装 Emscripten

Emscripten 是 LLVM 的一部分,是另一个编译 WebAssembly 的工具链。通过它可以从 C/C++ 代码生成 WebAssembly 模块。安装步骤参考 Emscripten 官方文档

编写 Hello, World

使用 Rust 构建

  1. 创建一个新的 Rust 项目:

    cargo new hello_wasm --lib
    
  2. 修改 Cargo.toml 文件,添加 [lib] 部分指定输出类型为 WebAssembly:

    [package]
    name = "hello_wasm"
    version = "0.1.0"
    
    [dependencies]
    
    [lib]
    crate-type = ["cdylib"]
    
  3. 编辑 src/lib.rs,添加一个函数:

    #[no_mangle]
    pub extern fn hello_world() -> *const u8 {
        "Hello, World!".as_ptr()
    }
    
  4. 使用以下命令编译为 WebAssembly 模块:

    wasm-pack build --target web
    

使用 Emscripten 构建

  1. 编写 C 语言代码(hello.c):

    #include <stdio.h>
    
    extern void hello_world() {
        printf("Hello, World!\n");
    }
    
  2. 使用 Emscripten 编译器编译该文件:

    emcc hello.c -s WASM=1 -o hello.html
    

集成到网页中

WebAssembly 模块需要在 HTML 页面中加载并执行。使用 JavaScript 可以加载和调用 WebAssembly 函数。

使用 Rust 生成的模块

<!DOCTYPE html>
<html>
<head><title>Simple WASM Example</title></head>
<body>
<script>
    fetch('pkg/hello_wasm_bg.wasm')
        .then(response => response.arrayBuffer())
        .then(bytes => WebAssembly.instantiateStreaming(
            fetch('pkg/hello_wasm_bg.wasm'),
            importObject))
        .then(results => {
            // 调用 Rust 函数
            alert(new TextDecoder().decode(Uint8Array.from(results.instance.exports.hello_world())));
        });
</script>
</body>
</html>

使用 Emscripten 生成的模块

<!DOCTYPE html>
<html>
<head><title>Emscripten WASM Example</title></head>
<body>
<script src="hello.js"></script>
<script>
    Module.onRuntimeInitialized = function() {
        // 调用 C 函数
        Module.ccall('hello_world', null, []);
    };
</script>
</body>
</html>

结语

通过上面的步骤,开发者可以使用 Rust 或者 Emscripten 来创建和部署 WebAssembly 应用。这些示例仅作为入门指南,深入探索还需要了解更多的编译器优化选项以及性能调优策略。进一步的信息可参考 Rust 官方文档和 LLVM 文档。

遵循上述步骤,开发者能够快速上手并开始享受 WebAssembly 带来的乐趣。