MST

星途 面试题库

面试题:JavaScript中如何实现与WebAssembly的基本交互

请阐述在JavaScript中引入WebAssembly模块的基本步骤,并且说明如何向WebAssembly函数传递简单数据类型(如整数)以及如何接收返回值。
31.6万 热度难度
编程语言JavaScript

知识考点

AI 面试

面试题答案

一键面试

引入WebAssembly模块的基本步骤

  1. 编写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

  1. 传递整数:在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);
  1. 接收返回值:WebAssembly函数的返回值会直接返回给JavaScript调用处,就像上述代码中exports.add(3, 5)返回的和sum,可以直接使用和操作。