Open3

【読書】『入門WebAssembly』

AoToAoTo

第2章 WATの基礎

本性を最後まで読めば、Node.js を使ってコマンドラインから実行できるシンプルな WebAssembly アプリケーションを記述できるようになるはずです。

ということで、WAT(WebAssembly Text) からやっていきます!

  • 基本的な記述方法
command.wat
(module
 ;; comment
 (;
 multi-line
 comment
 ;)
)
  • hello world!
    WAT は文字列を組み込みでサポートしないため、メモリデータを文字データ配列として直接操作し、 JavaScript コードで文字列に変換する手順を踏む。
helloworld.wat
(module
 (import "env" "print_string" (func $print_string(param i32)))
 (import "env" "buffer" (memory 1))
 (global $start_string (import "env" "start_string") i32)
 (global $string_len i32 (i32.const 12))
 (data (global.get $start_string) "hello world")
 (func (export "hellowrold"))
  (call $print_string (global.get $string_len))
)
helloworld.js
const fs = require('fs');
const bytes = fs.readFileSync(__dirname + '/helloworld.wasm');

let hello_world = null;
let start_string_index = 100;
let memory = new WebAssembly.Memory({ initial: 1})

let importObject = {
 env: {
  buffer; memory,
  start_string: start_string_index,
  print_string: function(str_len){
   const bytes = new Unit8Array(memory.buffer,
            start_string_index,
            str_len);
   const log_string = new Textdecoder('utf8').decode(bytes);
   console.log(log_string);
   }
 }
};

(async () =>{
 let obj = await WebAssembly.instantiate(new Unit8Array(bytes),
    importObject);
 ({helloworld: helle_world} = obj.instance.exports);
 hellow_world();
 }
)();