zl程序教程

您现在的位置是:首页 >  前端

当前栏目

[WASM] Compile C Code into WebAssembly

code INTO compile WebAssembly Wasm
2023-09-14 08:59:18 时间

We use the C language instead of pure WAST to create a square root function using WASM Fiddle (https://wasdk.github.io/WasmFiddle//). We show how to run the WebAssembly in WASM Fiddle, then download and run it in the browser using a helper function to load the WebAssembly.

WASM Fiddle: https://wasdk.github.io/WasmFiddle/?t96rp

Demo Repo: https://github.com/guybedford/wasm-intro

 

// C

#include <math.h>

float getSqrt (float num) {
  return sqrt(num);
}

 

Compile to WASM:

(module
  (type $FUNCSIG$ff (func (param f32) (result f32)))
  (table 0 anyfunc)
  (memory $0 1)
  (export "memory" (memory $0))
  (export "getSqrt" (func $getSqrt))
  (func $getSqrt (param $0 f32) (result f32)
    (f32.sqrt
      (get_local $0)
    )
  )
)

 

index.html:

<!doctype>
<html>
<header>
    <title>
        WASM
    </title>
    <script>

        function fetchAndInstantiateWasm(url, imports) {
            return fetch(url)
                .then((res) => {
                    if (res.ok) {
                        return res.arrayBuffer();
                    }
                    throw new Error('Unable to fetch WASM')
                })
                .then((bytes) => {
                    return WebAssembly.compile(bytes);
                })
                .then(module => {
                    return WebAssembly.instantiate(module, imports || {});
                })
                .then(instance => instance.exports);
        }

        fetchAndInstantiateWasm('./program.wasm')
            .then(m => {
                window.getSqrt = m.getSqrt;
            });
    </script>
</header>
</html>