美文网首页
javascript WebAssembly使用

javascript WebAssembly使用

作者: proud2008 | 来源:发表于2020-03-23 11:24 被阅读0次

    https://segmentfault.com/a/1190000012110615

    WebAssembly可以看做是对JavaScript的加强,弥补JavaScript在执行效率上的缺陷。
    它是一个新的语言,它定义了一种AST,并可以用字节码的格式表示。
    它是对浏览器的加强,浏览器能够直接理解WebAssembly并将其转化为机器码。
    它是一种目标语言,任何其他语言都可以编译成WebAssembly在浏览器上运行。
    想象一下,在计算机视觉,游戏动画,视频编解码,数据加密等需要需要高计算量的领域,如果想在浏览器上实现,并跨浏览器支持,唯一能做的就是用JavaScript来运行,这是一件吃力不讨好的事情。而WebAssembly可以将现有的用C,C++编写的库直接编译成WebAssembly运行到浏览器上, 并且可以作为库被JavaScript引用。那就意味着我们可以将很多后端的工作转移到前端,减轻服务器的压力。这是WebAssembly最为吸引人的特性。并且WebAssembly是运行于沙箱中,保证了其安全性。

    WebAssembly.compile(new Uint8Array(
    `00 61 73 6d  01 00 00 00  01 0c 02 60  02 7f 7f 01
      7f 60 01 7f  01 7f 03 03  02 00 01 07  10 02 03 61
      64 64 00 00  06 73 71 75  61 72 65 00  01 0a 13 02
      08 00 20 00  20 01 6a 0f  0b 08 00 20  00 20 00 6c
      0f 0b`.trim().split(/[\s\r\n]+/g).map(str => parseInt(str, 16))
    )).then(module => {
      const instance = new WebAssembly.Instance(module)
      const { add, square } = instance.exports
    
      console.log('2 + 4 =', add(2, 4))
      console.log('3^2 =', square(3))
      console.log('(2 + 5)^2 =', square(add(2 + 5)))
    
    })
    //Promise {<pending>}
    //VM231:11 2 + 4 = 6
    //VM231:12 3^2 = 9
    //VM231:13 (2 + 5)^2 = 49
    

    写到单独的文件中

    <!DOCTYPE html>
    <html>
    <head>
        <title></title>
    </head>
    <body>
        <!-- int add(int a) {    return a;} -->
        <script type="text/javascript">
            function loadWebAssembly (path="program.wasm", imports = {}) {
              return fetch(path)
                .then(response => response.arrayBuffer())
                .then(buffer => {return WebAssembly.compile(buffer);})
                .then(module => {return new WebAssembly.Instance(module, imports)})
                .then(result =>result.exports);
            }
            loadWebAssembly()
              .then(instance => {
                let add =instance.add
                console.log('2 + 4 =', add(2, 4))
              })
        </script>
    </body>
    </html>
    
    0061 736d 0100 0000 0186 8080 8000 0160
    017f 017f 0382 8080 8000 0100 0484 8080
    8000 0170 0000 0583 8080 8000 0100 0106
    8180 8080 0000 0790 8080 8000 0206 6d65
    6d6f 7279 0200 0361 6464 0000 0a8a 8080
    8000 0184 8080 8000 0020 000b 
    

    wasm格式获取

    使用在线工具

    https://wasdk.github.io/WasmFiddle/

    image.png image.png

    例如将Java转换成JavaScript的Google Web Toolkit (GWT)

    将python转换成JavaScript的pyjamas 等等。

    相关文章

      网友评论

          本文标题:javascript WebAssembly使用

          本文链接:https://www.haomeiwen.com/subject/yrbiyhtx.html