如何使用es6 import加载emscripten生成的模块? [英] How load an emscripten generated module with es6 import?
问题描述
我正在尝试将使用emscripten生成的模块作为es6模块导入。
我正在尝试使用基本示例(来自emscripten文档。
I am trying to import a module generated with emscripten as a es6 module. I am trying with the basic example from emscripten doc.
这是我用来从C模块生成js模块的命令:
This is the command I am using to generate the js module from the C module:
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模块:
Then importing the generated js module:
<!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不可用:
This is failing because cwrap is not available on the Module object:
未捕获的TypeError:Module.cwrap不是函数
推荐答案
在使用 MODULARIZE
时,必须首先创建模块的实例。
As you're using MODULARIZE
, you have to make an instance of the Module first.
import Module from './example.js'
const mymod = Module();
const int_sqrt = mymod.cwrap('int_sqrt', 'number', ['number']);
console.log(int_sqrt(64));
您还可以尝试使用 MODULARIZE_INSTANCE
选项。
You could also try the MODULARIZE_INSTANCE
option.
您可能需要等待它完成初始化-我不确定函数何时如此简单。看起来像这样:
You may need to wait for it to finish initialising - I'm not sure when the function is so simple. That would look like this:
import Module from './example.js'
Module().then(function(mymod) {
const int_sqrt = mymod.cwrap('int_sqrt', 'number', ['number']);
console.log(int_sqrt(64));
});
这篇关于如何使用es6 import加载emscripten生成的模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!