Posted on 2025/03/02, 4:09 PM By admin22
JavaScriptおよびTypeScriptが全盛の今、その周辺の技術も賑やかです。
WebAssemblyというのは、処理の高速化等で使用されますが、これにコンパイルできるOnyxという言語を試してみました。
インストール)
sh <(curl https://get.onyxlang.io -sSfL)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
<!DOCTYPE html> <html lang="ja"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Onyx WebAssembly</title> </head> <body> <h1>Onyx WebAssembly</h1> <div> <button id="runButton">11 + 22</button> <p id="result"></p> </div> <script> async function loadWasm() { const response = await fetch('add.wasm'); console.log(response) const bytes = await response.arrayBuffer(); console.log(bytes) const imports = { "host": { "print_str": (offset, length) => { console.log(`WASM tried to print a string at offset ${offset} with length ${length}`); } } }; const importObject = {} const wasmModule = await WebAssembly.instantiate(bytes, imports); console.log('wasm', wasmModule) return wasmModule.instance.exports.add; } document.getElementById('runButton').addEventListener('click', async () => { const add = await loadWasm(); console.log(add) const result = add(11, 22); document.getElementById('result').innerText = `11 + 22 = ${result}`; }); </script> </body> </html> |
1 2 3 4 |
#export "add" (a: i32, b: i32) -> i32 { return a + b } main :: () {} |
onyx build -o add.wasm -r js add.onyx
python3 -m http.server 8080
wasmを外部モジュールとして呼び出すサンプルです。
下記、node でもやってみました。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
import fs from 'fs/promises'; async function loadWasm() { const bytes = await fs.readFile('./add.wasm'); const imports = { "host": { "print_str": (offset, length) => { console.log(`WASM tried to print a string at offset ${offset} with length ${length}`); } } }; const { instance } = await WebAssembly.instantiate(bytes, imports); return instance.exports.add; } loadWasm().then(add => { console.log("11 + 22 =", add(11, 22)); }).catch(console.error); |
% node index.js
11 + 22 = 33
どちらでも使える共通モジュールを持つことができます。
アルゴリズムなどで利用すると便利ですね。
Categories: 未分類 タグ: Javascript, Onyx