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

2024-01-22

我正在尝试导入使用 emscripten 生成的模块作为 es6 模块。 我正在尝试与基本示例 https://kripken.github.io/emscripten-site/docs/porting/connecting_cpp_and_javascript/Interacting-with-code.html#interacting-with-code来自 emscripten 文档。

这是我用来从 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 在 Module 对象上不可用:

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 option.

你可能需要等待它完成初始化——我不确定这个功能什么时候这么简单。那看起来像这样:

import Module from './example.js'
Module().then(function(mymod) {
  const int_sqrt = mymod.cwrap('int_sqrt', 'number', ['number']);
  console.log(int_sqrt(64));
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 es6 import 加载 emscripten 生成的模块? 的相关文章

随机推荐