1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

テキスト形式のWebAssemblyをブラウザ上で実行する

Posted at

テキスト形式のWebAssemblyをブラウザ上で実行する

ブラウザ上で.wat.wasmにして実行する方法です。
wat2wasm demoみたいなものを作りたい方向けです。

wabt.js

wabt.jsを使います。

初期化

CDNとかでwabt.jsを読み込んだら、WabtModule()を呼び出していろいろやります。

<script src = "https://unpkg.com/wabt@1.0.36/index.js"></script>
WabtModule().then((wabt) => {
  //...
})

wat -> wasm

wabt.parseWat.watコードを.wasmに変換し、.toBinary()でバイトデータを取得します。

  let wasmModule = wabt.parseWat("main.wat", code)
  let buffer = wasmModule.toBinary({
    log : true,
    canonicalize_lebs : true,
    relocatable : false,
    write_debug_names : false
  })

.toBinary()の引数はオプションです。

log

buffer.logにログ情報が記録されます。

canonicalize_lebs

LEB128が使用されるようです。

relocatable

再配置可能なwasmバイナリを作成します。

write_debug_names

デバッグ名が書き込まれます。

wasmの実行

通常のwasmと同じように実行することができます。

  WebAssembly.instantiate(buffer.buffer).then(
    (results) => {
      console.log("result : " + results.instance.exports.add(0, 10))
    }
  )

sample code

index.html
<script src = "https://unpkg.com/wabt@1.0.36/index.js"></script>
<script src = "index.js"></script>
index.js
let code = `
(module
  (func $add (param $lhs i32) (param $rhs i32) (result i32)
    local.get $lhs
    local.get $rhs
    i32.add)
  (export "add" (func $add))
)
`

WabtModule().then((wabt) => {
  let wasmModule = wabt.parseWat("main.wat", code)
  let buffer = wasmModule.toBinary({
    log : true,
    canonicalize_lebs : true,
    relocatable : false,
    write_debug_names : false
  })

  wasmModule.destroy()

  console.log(buffer.log)
  console.log("bytesize : " + buffer.buffer.byteLength)

  WebAssembly.instantiate(buffer.buffer).then(
    (results) => {
      console.log("result : " + results.instance.exports.add(0, 10))
    }
  )
})

参考

WebAssembly
wat2wasm demo
wabt.js

むすび

ちょっとしたメモでした。

bsky

1
1
0

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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?