如何使用 es6 导入加载 emscripten 生成的模块?

How load an emscripten generated module with es6 import?

我正在尝试将使用 emscripten 生成的模块导入为 es6 模块。 我正在尝试使用 emscripten 文档中的 basic example

这是我用来从 C 模块生成 js 模块的命令:

emcc example.cpp -o example.js -s EXPORTED_FUNCTIONS="['_int_sqrt']" -s EXTRA_EXPORTED_RUNTIME_METHODS="['ccall', 'cwrap']" -s EXPORT_ES6=1 -s MODULARIZE=1

C 模块:

#include <math.h>

extern "C" {

  int int_sqrt(int x) {
    return sqrt(x);
  }
}

然后导入生成的js模块:

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Wasm example</title>
  </head>
  <body>
    <script type="module">
      import Module from './example.js'

      int_sqrt = Module.cwrap('int_sqrt', 'number', ['number']);
      console.log(int_sqrt(64));
    </script>
  </body>
</html>

这是失败的,因为 cwrap 在模块对象上不可用:

Uncaught TypeError: Module.cwrap is not a function

在使用 MODULARIZE 时,您必须先创建模块的实例。

import Module from './example.js'
const mymod = Module();
const int_sqrt = mymod.cwrap('int_sqrt', 'number', ['number']);
console.log(int_sqrt(64));

您也可以尝试 MODULARIZE_INSTANCE 选项。

您可能需要等待它完成初始化 - 我不确定什么时候功能如此简单。看起来像这样:

import Module from './example.js'
Module().then(function(mymod) {
  const int_sqrt = mymod.cwrap('int_sqrt', 'number', ['number']);
  console.log(int_sqrt(64));
});