在 WebAssembly 和 JavaScript 之间传输字节数组 (Uint8Array)
Transfer byte array (Uint8Array) between WebAssembly and JavaScript
我在 WebAssembly 代码中有一个 u8[] 数组,如何在常规 JS 中读取它?调用它 return 我是 i32。
// Load module WebAssembly.Instance
const instance = await getInstance("./build/embed.wasm");
// Try to get the array of bytes from the module
const embeddedFileBytes = Uint8Array.from(instance.fileBytes);
// write the file to disc
await writeFile("./output.text", embeddedFileBytes);
// check the hash is the same as the original file that was embedded
expect(sha1("./output.text")).toEqual(sha1("./input.text"))
webassembly 模块有一个导出:
export const fileBytes: u8[] = [83,65,77,80,76,69,10];
WebAssembly 是一个低级虚拟机,只支持数字类型。更复杂的类型,例如字符串、结构和数组,在 WebAssembly 的 linear memory 中编码 - 这是一个连续的内存块,WebAssembly 和 JavaScript 都可以读取和写入。
fileBytes
返回的值不是数组本身,而是指向线性内存中数组位置的指针。为了从数组中获取数据,您需要从线性内存中读取它 - 与读取字符串的方式大致相同,如以下问题所述:
如果您不想自己编写此 'glue' 代码,我建议您查看 wasm-bindgen
我在 WebAssembly 代码中有一个 u8[] 数组,如何在常规 JS 中读取它?调用它 return 我是 i32。
// Load module WebAssembly.Instance
const instance = await getInstance("./build/embed.wasm");
// Try to get the array of bytes from the module
const embeddedFileBytes = Uint8Array.from(instance.fileBytes);
// write the file to disc
await writeFile("./output.text", embeddedFileBytes);
// check the hash is the same as the original file that was embedded
expect(sha1("./output.text")).toEqual(sha1("./input.text"))
webassembly 模块有一个导出:
export const fileBytes: u8[] = [83,65,77,80,76,69,10];
WebAssembly 是一个低级虚拟机,只支持数字类型。更复杂的类型,例如字符串、结构和数组,在 WebAssembly 的 linear memory 中编码 - 这是一个连续的内存块,WebAssembly 和 JavaScript 都可以读取和写入。
fileBytes
返回的值不是数组本身,而是指向线性内存中数组位置的指针。为了从数组中获取数据,您需要从线性内存中读取它 - 与读取字符串的方式大致相同,如以下问题所述:
如果您不想自己编写此 'glue' 代码,我建议您查看 wasm-bindgen