zoukankan      html  css  js  c++  java
  • [WASM] Create and Run a Native WebAssembly Function

    In this introduction, we show a simple WebAssembly function that returns the square root of a number. To create this function we load up WebAssembly Explorer (https://mbebenita.github.io/WasmExplorer/), writing the native WAST code to create and export the function. We compile and download the resulting WebAssembly binary, loading this with the Fetch API and WebAssembly JavaScript API to call the function in the browser.

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

     Every WebAssembly starts with Module:
    (module
    
    )

    Define a function inside the module:

    (module
     (func $sqrt
    
     )   
    )

    Now we defined a empty function, 

    To add input and output we can do:

    (module
      (func $sqrt
         (param $num f32) # Input: param is the keyword, $num is the param name, f32 is the type
         (result f32) # Output: result is the keyword, f32 is the type 
      )
    )

    Now we can define function body:

    (module
      (func $sqrt 
        (param $num f32)
        (result f32)
        
        (f32.sqrt (get_local $num))  # call the function sqrt on f32, pass in the params $num though get_local function
      )
    )

    The calculation value will be the return value.

    If we want to use the fucntion in Javascript, we need to export the function:

    (module
      (export "sqrt" (func $sqrt)) # export the function call "sqrt" refer to $sqrt function we defined below
      (func $sqrt 
        (param $num f32)
        (result f32)
        
        (f32.sqrt (get_local $num))
      )
    )

    After "Assemble" it and "Download" the file, we can load in the project:

    <!doctype>
    <html>
        <header>
            <title>
                WASM
            </title>
            <script>
                fetch('./test.wasm')
                    .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);
                    })
                    .then(instance => {
                        window.wasmSqrt =instance.exports.sqrt;
                    })
            </script>
        </header>
    </html>

    Open the console,  we can type:

    wasmSqrt(25) //5
  • 相关阅读:
    Uniapp实现微信小程序云开发
    laravel 打印日志
    windbg 学习笔记
    Spring事务,非事务方法调用事务方法,事务不生效
    MyBatis 流式查询
    写代码有这16个好习惯,可以减少80%非业务的bug
    IDEA 神级插件推荐
    OUTLOOK添加企业邮箱
    Win10环境中MATLAB R2020b安装及破解全过程讲解
    scala function vs method
  • 原文地址:https://www.cnblogs.com/Answer1215/p/7086987.html
Copyright © 2011-2022 走看看