Mic*_*Mic 6 javascript emscripten webassembly es6-modules
我正在尝试将使用 emscripten 生成的模块导入为 es6 模块。我正在尝试使用emscripten doc 中的基本示例。
这是我用来从 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);
}
}
Run Code Online (Sandbox Code Playgroud)
然后导入生成的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>
Run Code Online (Sandbox Code Playgroud)
这是失败的,因为 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));
Run Code Online (Sandbox Code Playgroud)
您也可以尝试该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));
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3815 次 |
| 最近记录: |