前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >wasm不通过请求直接使用的方法

wasm不通过请求直接使用的方法

原创
作者头像
治电小白菜
发布2024-07-19 10:29:17
800
发布2024-07-19 10:29:17
举报
文章被收录于专栏:技术综合

由于做sdk,不浪费流量让用户从服务器下载wasm,而是直接打入sdk内部,所以考虑直接将wasm转为buffer数组直接传入

一、方法

现将wasm二进制转为base64,方便代码引入;使用时再将其转为buffer数组。

二、步骤

1. wasm转换base64

直接使用nodejs进行转换,wasm使用的是mdn的示例

代码语言:js
复制
const readFileSync = require('fs').readFileSync;
const writeFileSync = require('fs').writeFileSync;
const wasmCode = readFileSync('simple.wasm');
// 将wasm二进制转为base64
const encoded = Buffer.from(wasmCode, 'binary').toString('base64');
// 写入js文件
writeFileSync('simple.wasm.js', `
  const WasmStr = "${encoded}";
  // base64转为二进制
  function base64ToBinary(str) {
    if (typeof atob === 'function') {
      // this works in the browser
      return atob(str)
    } else {
      // this works in node
      return new Buffer(str, 'base64').toString('binary');
    }
  }
  // base64转为buffer数组
  export function decodeWasm() {
    var binaryString =  base64ToBinary(WasmStr);
    var bytes = new Uint8Array(binaryString.length);
    for (var i = 0; i < binaryString.length; i++) {
        bytes[i] = binaryString.charCodeAt(i);
    }
    return bytes.buffer;
  }
`);

2. 页面引用

1) 页面使用module方式引入刚刚生成的simple.wasm.js,将decodeWasm()的值传入WebAssembly.instantiate

代码语言:html
复制
<!doctype html>
<html>
  <head><meta charset="utf-8"><title>WASM test</title></head>
  <body>
    <script type="module">
      import { decodeWasm } from './simple.wasm.js'
      const importObject = {
        my_namespace: {
          imported_func: arg => {
            console.log(arg);
          }
        }
      };
      ;(async () => {
        const result = await WebAssembly.instantiate(decodeWasm(), importObject)
        result.instance.exports.exported_func();
      })()
    </script>
  </body>
</html>

2. 控制台查看,可以看到正常输出

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 一、方法
  • 二、步骤
    • 1. wasm转换base64
      • 2. 页面引用
        • 1) 页面使用module方式引入刚刚生成的simple.wasm.js,将decodeWasm()的值传入WebAssembly.instantiate
        • 2. 控制台查看,可以看到正常输出
    领券
    问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档