首页 > 解决方案 > 如何使用带有反应的 emscripten wasm?

问题描述

我无法让 emscripten wasm 在反应中工作。

编译c代码:

emcc src\emsample.c -s WASM=1 -o deploy\www\emsample.js -s "EXPORTED_RUNTIME_METHODS=['ccall', 'cwrap']" -s EXPORTED_FUNCTIONS="['_sayHi', '_myFunction', '_daysInWeek', '_int_sqrt', '_main']" -s MODULARIZE -s EXPORT_NAME=EmSample -s 

将 wasm 和 js 文件复制到 /src 文件夹

接下来我想利用 wasm 并添加到 App.js 中:

[...]
import EmSample from "./emsample";

EmSample({
  global: {},
  env: {
    memoryBase: 0,
    tableBase: 0,
    memory: new WebAssembly.Memory({ initial: 256 }),
    table: new WebAssembly.Table({ initial: 0, element: "anyfunc" }),
  },
}).then((instance) => {
  // What is with the weird exports._Z4facti function?
  // This is how the function name is encoded by the C++ to wasm compiler
  const sayHi = instance.exports._myFunction;

  console.log(sayHi());
});
[...]

这给出了错误:

Uncaught (in promise) TypeError: WebAssembly.instantiate(): Import #0 module="wasi_snapshot_preview1" 错误:模块不是对象或函数

如果我将导入语句更改为

//Remark: add /*eslint-disable*/ to emsample.js to avoid problems with eslint
import EmSample from "./emsample.js";

给出错误:

Uncaught (in promise) RuntimeError: abort(CompileError: WebAssembly.instantiate(): expected magic word 00 61 73 6d, found 3c 21 44 4f @+0) at Error

我玩了很多不同的 emcc 设置,但没有成功。

在简单的 HTML 页面中使用相同的 wasm 文件效果很好

<!DOCTYPE html>
<title>Emscripten + npm example</title>
Open the console to see the output from the wasm module.
<script type="module">
  import EmSample from "./emsample.js";

  EmSample().then(function (mymod) {
    console.log(mymod._sayHi());
    const mySqrt = mymod.cwrap("int_sqrt", "number", ["number"]);
    console.log(mySqrt(64));
    console.log(mySqrt(7));
    console.log(mySqrt(8));
    console.log(mymod._myFunction());
    console.log(mymod._daysInWeek());
  });
</script>

我缺少什么让它在反应应用程序中工作?

标签: reactjsemscriptenwebassembly

解决方案


推荐阅读