Node.js实现WebAssembly方式(五)(Electron方式)

Node.js实现WebAssembly方式(五)(Electron方式)

实现Node.js与WebAssembly配合实现有几种形式,这里介绍第五种:通过module方式进行,且具有脚本侧向C侧的函数注入。

安装并激活Emscripten工具

可参考http://webassembly.org.cn/getting-started/developers-guide/进行Linux环境工具安装。

Module方式范例

  1. 编写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);
}
  1. 编写函数注入端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);
    }
})
  1. 调用emcc命令进行文件编译,得到test.js和test.wasm
emcc test.cc --js-library jslib.js -o test.js
  1. 编写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>


  1. 把index.html放在Electron工程作为主页面运行, test.js和test.wasm也放到同目录下:
    在这里插入图片描述

–End–

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

PegasusYu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值