面试题答案
一键面试引入WebAssembly模块的基本步骤
- 编写WebAssembly代码:通常使用C、C++、Rust等语言编写WebAssembly模块的源文件,编译生成
.wasm
文件。例如使用Rust编写:
#[no_mangle]
pub extern fn add(a: i32, b: i32) -> i32 {
a + b
}
通过cargo build --target wasm32-unknown-unknown
命令生成.wasm
文件。
2. 在JavaScript中加载模块:使用fetch
获取.wasm
文件内容,然后通过WebAssembly.instantiateStreaming
方法实例化模块。示例代码如下:
fetch('path/to/your/module.wasm')
.then(response => WebAssembly.instantiateStreaming(response))
.then(result => {
const exports = result.instance.exports;
// 此时可以使用exports中的函数
})
.catch(console.error);
也可以使用WebAssembly.instantiate
方法,先读取文件内容为ArrayBuffer
,再进行实例化:
fetch('path/to/your/module.wasm')
.then(response => response.arrayBuffer())
.then(buffer => WebAssembly.instantiate(buffer))
.then(result => {
const exports = result.instance.exports;
// 此时可以使用exports中的函数
})
.catch(console.error);
向WebAssembly函数传递简单数据类型(如整数)以及接收返回值
假设WebAssembly模块中有一个接收两个整数并返回它们之和的函数add
:
- 传递整数:在JavaScript中直接将整数作为参数传递给WebAssembly函数。例如:
fetch('path/to/your/module.wasm')
.then(response => WebAssembly.instantiateStreaming(response))
.then(result => {
const exports = result.instance.exports;
const sum = exports.add(3, 5);
console.log(sum);
})
.catch(console.error);
- 接收返回值:WebAssembly函数的返回值会直接返回给JavaScript调用处,就像上述代码中
exports.add(3, 5)
返回的和sum
,可以直接使用和操作。