たれぱんのびぼーろく

わたしの備忘録、生物学とプログラミングが多いかも

WebAssemblyを始めよう

WebAssemblyに触れてWebの未来を感じよう

WebAssemblyとは

WebAssembly (WASM) とは、Webブラウザで動く機械語です。
WASMはプログラミング言語であり、その実体はバイナリ命令の集合体、つまり機械語です1
しかし、いわゆる機械語のイメージと異なり、Webブラウザで実行が可能です。
ゆえに、機械語の高速動作とWebブラウザのポータビリティという利点を享受でき (るように設計されてい) ます。

「高速動作するために機械語書けってこと…?」と思われるかもしれませんが、それは誤解です。
WASMはC/C++/Rustのような高級言語からのコンパイルターゲットとなることを意図されています2
すなわち、CのコードをLinux用にではなくWebブラウザ (WASM ≒ 機械語) 用にコンパイルするということです (Cがブラウザで動く!)。
もちろんWASMを手書きすることも可能なので、機械語アセンブリ言語の勉強として触るのも素晴らしいですね。

一言でまとめるなら、「WebAssembly (WASM) とは、様々な言語のコンパイルターゲットとなれるWebブラウザ用の機械語」です。

WebAssemblyを見てみる

ではWebAssembly、すなわちWebブラウザのための機械語を見てみましょう。




Webブラウザで動かしてみる

  • Get the .wasm bytes into a typed array or ArrayBuffer
  • Compile the bytes into a WebAssembly.Module
  • Instantiate the WebAssembly.Module with imports to get the callable exports
compiled_module = await WebAssembly.compile(wasm_binaries)
new WebAssembly.Instance(compiled_module, )

  1. WebAssembly (abbreviated Wasm) is a binary instruction format ref

  2. Wasm is designed as a portable target for compilation of high-level languages like C/C++/Rust, enabling deployment on the web for client and server applications. ref