首页 > 解决方案 > 来自 Javascript 的 WebAssembly

问题描述

我有一个包含 1000 多行的 C++ 程序(使用向量和 stdlib.h)。该程序由一个函数组成,该函数将五个无符号整数(或 1 个无符号字符和 4 个无符号整数)作为输入,返回一个字符串或 4 个无符号整数(我不明白如何返回一个数字数组,所以我使用了一个字符串)。我使用 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 调用函数(举例)?

Chrome中wasm/wasm-000197c6/wasm-000197c6-22中的具体功能

标签: javascriptc++webassembly

解决方案


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


推荐阅读