Webassembly from Javascript

Webassembly from Javascript

本文关键字:Javascript from Webassembly      更新时间:2023-10-16

我有一个C++程序,有1000多行(使用vector和stdlib.h(。该程序由一个函数组成,该函数以5个无符号int(或1个无符号char和4个无符号整数(为输入,返回一个字符串或4个无签名int(我不知道如何返回数字数组,所以我使用字符串(。我使用WasmExplorer将该程序编译为.wasm文件。

如何从javascript中调用.wasm文件中的函数,得到结果?我试过:

let squarer;
function loadWebAssembly (fileName) {
  return fetch (fileName)
    .then (response => response.arrayBuffer ())
    .then (bits => WebAssembly.compile (bits))
    .then (module => {return new WebAssembly.Instance (module)});
};
  
loadWebAssembly ('http://test.ru/squarer.wasm')
  .then (instance => {
    squarer = instance.exports._Z7squareri;
    console.log ('Finished compiling! Ready when you are ...');
  });

Chrome中的错误(我有29Kb.wasm文件(

Uncaught (in promise) RangeError: WebAssembly.Instance is disallowed on the main thread, if the buffer size is larger than 4KB. Use WebAssembly.instantiate.

如何从JS中调用函数(附示例(?

铬中wasm/wasm-000197c6/wasm-000197c6-22的特定功能

错误消息中明确说明了问题和解决方案:应该使用WebAssembly.instantiate()函数而不是WebAssembly.Instance()构造函数。