Node.js实现WebAssembly方式(五)(Electron方式)
实现Node.js与WebAssembly配合实现有几种形式,这里介绍第五种:通过module方式进行,且具有脚本侧向C侧的函数注入。
安装并激活Emscripten工具
可参考http://webassembly.org.cn/getting-started/developers-guide/进行Linux环境工具安装。
Module方式范例
- 编写test.cc源文件,内容如下:
#ifndef EM_PORT_API
# if defined(__EMSCRIPTEN__)
# include <emscripten.h>
# if defined(__cplusplus)
# define EM_PORT_API(rettype) extern "C" rettype EMSCRIPTEN_KEEPALIVE
# else
# define EM_PORT_API(rettype) rettype EMSCRIPTEN_KEEPALIVE
# endif
# else
# if defined(__cplusplus)
# define EM_PORT_API(rettype) extern "C" rettype
# else
# define EM_PORT_API(rettype) rettype
# endif
# endif
#endif
EM_PORT_API(int) js_add(int a, int b);
EM_PORT_API(void) js_console_log_int(int param);
EM_PORT_API(void) print_the_answer() {
int i = js_add(21, 21);
js_console_log_int(i);
}
- 编写函数注入端jslib.js
mergeInto(LibraryManager.library, {
js_add: function (a, b) {
console.log("js_add invoked");
return a + b;
},
js_console_log_int: function (param) {
console.log("js_console_log_int invoked:" + param);
}
})
- 调用emcc命令进行文件编译,得到test.js和test.wasm
emcc test.cc --js-library jslib.js -o test.js
- 编写index.html
<html>
<head>
<meta charset="utf-8">
<title>Emscripten:Module Export</title>
</head>
<body>
<p> see console </p>
<script>
Module = {};
Module.onRuntimeInitialized = function() {
Module._print_the_answer();
}
</script>
<script src="test.js"></script>
</body>
</html>
- 把index.html放在Electron工程作为主页面运行, test.js和test.wasm也放到同目录下:
–End–