0

我在 WebAssembly 代码中有一个 u8[] 数组,如何在常规 JS 中读取它?调用它只是给我一个 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];
4

1 回答 1

1

WebAssembly 是一个只支持数字类型的低级虚拟机。更复杂的类型,例如字符串、结构和数组,在 WebAssembly 的线性内存中进行编码- 这是 WebAssembly 和 JavaScript 都可以读取和写入的连续内存块。

返回的值fileBytes不是数组本身,而是指向线性内存中数组位置的指针。为了从数组中获取数据,您需要从线性内存中读取它 - 与读取字符串的方式大致相同,如下面的问题所述:

如何从 WebAssembly 函数返回 JavaScript 字符串

如果您不想自己编写此“胶水”代码,我建议您查看wasm-bindgen

于 2020-01-18T21:15:08.247 回答