【问题标题】:How load an emscripten generated module with es6 import?如何使用 es6 导入加载 emscripten 生成的模块?
【发布时间】:2018-11-14 21:37:22
【问题描述】:

我正在尝试将使用 emscripten 生成的模块导入为 es6 模块。 我正在尝试使用来自 emscripten doc 的 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

【问题讨论】:

    标签: javascript es6-modules emscripten webassembly


    【解决方案1】:

    当您使用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));
    });
    

    【讨论】:

    • 我收到此错误:编译失败。 ./src/components/js_plumbing.js。 SyntaxError: Unexpected token, expected ( (3:25) . > 3 | var _scriptDir = import.meta.url;
    • 请您看一下我尝试使用您的建议的用例好吗? forum.vuejs.org/t/…
    • @user2315094 提出一个新问题。
    • 我在这里问了一个新问题:stackoverflow.com/questions/59530889/…。我提前感谢您为解决方案做出贡献
    猜你喜欢
    • 1970-01-01
    • 2023-04-01
    • 2019-10-22
    • 2020-03-11
    • 1970-01-01
    • 2021-01-21
    • 1970-01-01
    相关资源
    最近更新 更多