WebAssembly 教學:初學者指南

Hello there, future WebAssembly wizards! I'm thrilled to be your guide on this exciting journey into the world of WebAssembly. As someone who's been teaching computer science for more years than I care to admit (let's just say I remember when floppy disks were actually floppy), I'm here to make this adventure as fun and accessible as possible. So, grab your favorite beverage, get comfy, and let's dive in!

WebAssembly - Home

什麼是 WebAssembly?

Imagine you're building a sandcastle. JavaScript is like using your hands - it's flexible and easy to start with, but it might not be the fastest way to build a massive fortress. WebAssembly, on the other hand, is like having a set of specialized tools - it might take a bit more setup, but boy, can it build things quickly!

WebAssembly, often abbreviated as Wasm, is a binary instruction format designed for efficient execution in web browsers. It's like a secret code that your browser understands, allowing programs to run at near-native speed.

你為什麼應該關心?

  1. 速度:WebAssembly 快如閃電。對你的網頁應用來說,就像是從自行車升級到跑車。
  2. 語言多樣性:你不再受限於 JavaScript。C、C++、Rust,隨你挑!
  3. 安全性:WebAssembly 在沙盒環境中運行,讓一切安全無虞。

WebAssembly 入門

設置開發環境

在我們開始編程之前,我們需要設置我們的工作空間。這就像在烹飪美味佳肴之前準備廚房一樣。以下是你需要的東西:

  1. 一個現代網頁浏览器(Chrome、Firefox、Safari 或 Edge)
  2. 一個文本編輯器(我推薦 Visual Studio Code,但使用你熟悉的即可)
  3. Emscripten 工具集(我們將一起安裝)

讓我們安裝 Emscripten:

# 克隆 Emscripten 儲存庫
git clone https://github.com/emscripten-core/emsdk.git

# 進入克隆的目錄
cd emsdk

# 下載並安裝最新的 SDK 工具
./emsdk install latest

# 激活最新的 SDK 工具
./emsdk activate latest

# 設置環境變量
source ./emsdk_env.sh

如果這些看起來像天書,別擔心。把它當成在創作一幅傑作前,準備你的畫架和颜料吧!

你的第一個 WebAssembly 程序

讓我們從一個簡單的 "Hello, World!" 程序開始。我們將用 C 語言寫它,然後編譯成 WebAssembly。

第一步:編寫 C 代碼

創建一個名為 hello.c 的文件,並添加以下代碼:

#include <stdio.h>

int main() {
printf("Hello, WebAssembly World!\n");
return 0;
}

這就像寫一封信,我們將把它翻譯成浏览器能夠理解的語言。

第二步:編譯成 WebAssembly

現在,讓我們把 C 代碼轉換成 WebAssembly。在終端中運行以下命令:

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

這個命令就像把信放進神奇的翻譯機中。它會生成三個文件:

  • hello.wasm:WebAssembly 二进制文件
  • hello.js:JavaScript 黏合代碼
  • hello.html:運行我們程序的 HTML 文件

第三步:運行你的 WebAssembly 程序

在網頁浏览器中打開 hello.html 文件。你應該會在頁面上看到 "Hello, WebAssembly World!" 被打印出來。恭喜!你剛剛運行了你第一個 WebAssembly 程序!

了解魔法

讓我們分解一下剛剛發生了什麼:

  1. 我們寫了一個簡單的 C 程序。
  2. 我們使用 Emscripten 將 C 代碼編譯成 WebAssembly。
  3. Emscripten 還生成了一些 JavaScript 代碼來加載和運行我們的 WebAssembly。
  4. 浏览器執行了我們的 WebAssembly 代碼,打印出我們的消息。

這就像我們用英語(C)寫了一封信,把它翻譯成通用語言(WebAssembly),然後讓一個翻譯(JavaScript)大声朗讀,讓所有人(浏览器)都能理解。

進一步:一個簡單的计算器

現在我們已經熱身了,讓我們試試一些更具互動性的東西。我們將創建一個能夠加兩個數字的最簡單计算器。

第一步:編寫 C 代碼

創建一個名為 calculator.c 的新文件:

#include <emscripten.h>

EMSCRIPTEN_KEEPALIVE
int add(int a, int b) {
return a + b;
}

在這裡,EMSCRIPTEN_KEEPALIVE 就像在函數上貼上巨大的 "重要" 標籤。它告訴 Emscripten 保留這個函數,讓 JavaScript 能夠調用它。

第二步:編譯成 WebAssembly

編譯我們的计算器:

emcc calculator.c -s WASM=1 -s EXPORTED_FUNCTIONS='["_add"]' -s EXPORTED_RUNTIME_METHODS='["ccall", "cwrap"]' -o calculator.js

這個命令有點複雜,但把它當成給我們的翻譯機提供具體指示。

第三步:創建 HTML 界面

創建一個名為 calculator.html 的文件:

<!DOCTYPE html>
<html>
<head>
<title>WebAssembly Calculator</title>
</head>
<body>
<h1>WebAssembly Calculator</h1>
<input type="number" id="num1" placeholder="Enter first number">
<input type="number" id="num2" placeholder="Enter second number">
<button onclick="calculateSum()">Add</button>
<p>Result: <span id="result"></span></p>

<script src="calculator.js"></script>
<script>
Module.onRuntimeInitialized = function() {
window.add = Module.cwrap('add', 'number', ['number', 'number']);
}

function calculateSum() {
var num1 = parseInt(document.getElementById('num1').value);
var num2 = parseInt(document.getElementById('num2').value);
var sum = add(num1, num2);
document.getElementById('result').textContent = sum;
}
</script>
</body>
</html>

這個 HTML 文件就像為我們的计算器創建一個用戶友好的界面。它有數字輸入框和一個 "Add" 按鈕。

第四步:運行你的 WebAssembly 计算

在浏览器中打開 calculator.html。你應該會看到兩個輸入框和一個 "Add" 按鈕。輸入兩個數字,點擊 "Add",然後看啊!你的 WebAssembly 计算器運行起來了!

結論

And there you have it, folks! We've taken our first steps into the exciting world of WebAssembly. We've set up our environment, created a "Hello, World!" program, and even built a simple calculator.

Remember, learning WebAssembly is like learning to ride a bike. It might seem wobbly at first, but with practice, you'll be zooming around the web development world in no time. Keep experimenting, keep learning, and most importantly, have fun!

In our next lesson, we'll dive deeper into WebAssembly's capabilities and explore how to optimize performance. Until then, happy coding!

方法 描述
emcc Emscripten 编译器命令
EMSCRIPTEN_KEEPALIVE 防止函数被优化的宏
Module.cwrap 创建一个包装器以调用编译的 C 函数
Module.ccall 直接调用编译的 C 函数

Credits: Image by storyset