LoginSignup
6
3

More than 5 years have passed since last update.

Rustで初めての簡単なWebAssembly入門

Last updated at Posted at 2019-01-11

本記事の内容はあまり実用的ではないもののとりあえずブラウザでWebAssemblyが動くのを確認したい人向け

前提

Rustの最新版がインストールされていること
本記事を執筆時点では1.31.1が最新だった

ビルドターゲットの確認

ターミナルで以下のコマンドを打つとビルドターゲット一覧が確認できる

# rustup target list

この中でWebAssemblyに関係しているのは以下の三つ
asmjs-unknown-emscripten
wasm32-unknown-emscripten
wasm32-unknown-unknown

今回はwasm32-unknown-unknownを使って話を進めるものとする
ビルドターゲット追加のコマンドは以下の通り

# rustup target add wasm32-unknown-unknown

今回の簡易な方法ではcargoは利用せず直接rsファイルを生成、コンパイルする
実行例として1から10までの和を返す関数

test.rs
#[no_mangle]
pub fn sum_from1_to10() -> i32 {
    let mut sum = 0;
    for i in 1..=10 {
        sum += i;
    }
    sum
}

これに対してのコンパイルは以下のコマンドで行う

rustc --target wasm32-unknown-unknown -O test.rs --crate-type=cdylib

コンパイル後test.wasmというファイルができるのでこれを適当なWebサーバーのドキュメント配下に配置し
同じ場所に以下のhtmlファイルを用意する

index.html
<!DOCTYPE html>
<html lang="ja">
    <head>
        <meta charset="utf-8" />
        <script>
fetch('test.wasm')
    .then((response) => response.arrayBuffer())
    .then((bytes) => WebAssembly.instantiate(bytes, {}))
    .then((results) => {
        const instance = results.instance;
        console.log(instance.exports.sum_from1_to10());
    });
        </script>
    </head>
    <body>
    </body>
</html>

ブラウザからアクセスした際にコンソールに以下のように55が表示されればひとまず成功
img_20190111.png

参考

Rust単体でWebAssemblyをコンパイルする(Emscripten無し)

6
3
5

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
3