我正在尝试将使用 emscripten 生成的模块导入为 es6 模块。 我正在尝试 basic example来自 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.cwrap 不是函数
最佳答案
当您使用 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));
});
关于javascript - 如何使用 es6 导入加载 emscripten 生成的模块?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53309095/