gpt4 book ai didi

webassembly - 如何有效地将wasm(WebAssembly)直接嵌入到html文件中?类型化数组

转载 作者:行者123 更新时间:2023-12-03 19:12:47 26 4
gpt4 key购买 nike

我需要将 wasm 应用程序直接嵌入到 html 页面本身,而不是从单独的文件中加载它(例如通过 xhr)。到目前为止,我设法通过将字节直接“打印”到 Uint8Array 中来嵌入它(见下文),但它的空间效率不高(显然)。一个 65MB 的 wasm 文件变成了一个 220MB 的 js 文件。

const go = new Go()
WebAssembly.instantiate(new Uint8Array([0,97,115,109,1,0,0,0,0,242,128,128,128,0,10,103,111,46,98,117,105,108,100,105,100,255,32,71,111,32,98,117,105,108,100,32,73,68,58,32,34,56,69,84,87,98,97,65,117,88,67,100,52,98,55,72,90,112,90,114,70,47,85,111,66,116,82,89,102,80,118,83,101,111,69,111,106,117,50,85,99,90,47,115,77,71,110,85,106,....], { type: 'application/wasm' });

最佳答案

编码 WebAssembly 模块的一种有效方法是使用 Base64 编码。您可以按如下方式编码(在节点中):

const readFileSync = require('fs').readFileSync;

const wasmCode = readFileSync(id);
const encoded = Buffer.from(wasmCode, 'binary').toString('base64')

并在浏览器或节点中解码如下:
var encoded = "...";

function asciiToBinary(str) {
if (typeof atob === 'function') {
return atob(str)
} else {
return new Buffer(str, 'base64').toString('binary');
}
}

function decode(encoded) {
var binaryString = asciiToBinary(encoded);
var bytes = new Uint8Array(binaryString.length);
for (var i = 0; i < binaryString.length; i++) {
bytes[i] = binaryString.charCodeAt(i);
}
return bytes.buffer;
}

var instance = WebAssembly.instantiate(decode(encoded), importObject)
.then(r => r.instance);

关于webassembly - 如何有效地将wasm(WebAssembly)直接嵌入到html文件中?类型化数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61583742/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com