用C++扩展Electron(node-ffi版)

来源:互联网 发布:知信轰炸机接口 编辑:程序博客网 时间:2024/06/03 21:49

用C++扩展Electron(node-ffi版)

Electron内置的node.js,理论上可以通过扩展node.js来扩展Electron。但是通常由于系统中存在的node.js与Electron内置的node.js的版本号不同,给node.js编译的扩展是无法在Electron中使用的,需要一些特殊处理才行。

0.先安装node.js和python(2.7)。请参考:

  • https://nodejs.org/

  • https://www.python.org

1.新建一个demo项目: 创建demo目录,并进入其中,然后运行下面命令。

mkdir democd  demonpm init

运行npm init时,把『entry point』设置成main.js,之后会生成一个package.json(具体内容与输入参数有关):

{  "name": "demo",  "version": "1.0.0",  "description": "a demo for node call native functions",  "main": "main.js",  "scripts": {    "test": "echo \"Error: no test specified\" && exit 1"  },  "keywords": [    "node"  ],  "author": "Li XianJing",  "license": "ISC"}

2.安装electron和编译工具和头文件。

sudo npm install -g prebuild node-gyp electronnpm install ffi bindings --save

3.用C++编写原生代码( 为了让目录结构整洁一点,我们把代码放到native只目录下)。

下面的文件(native/demo.cc),添加一个Add方法,计算两个数之和:

double Add(double a, double b) {    return a+b;}

4.写一个Makefile(native/Makefile), 用来编译C++代码。

all:    $(CC) -g -shared  demo.c -o libdemo.dylibclean:    rm -frv libdemo*

5.用prebuild编译指定版本的electron的ref/ffi(可以把下面的命令放到Makefile中)。
(1.4.12是electron的版本号)

cd native && make; cd -cd node_modules/ref && prebuild -b 1.4.12 -r electron; cd -cd node_modules/ffi && prebuild -b 1.4.12 -r electron; cd -

6.编写Electron的入口(main.js):

const electron = require('electron')const app = electron.appconst BrowserWindow = electron.BrowserWindowconst path = require('path')const url = require('url')let mainWindowfunction createWindow () {  mainWindow = new BrowserWindow({width: 800, height: 600})  mainWindow.loadURL(url.format({    pathname: path.join(__dirname, 'index.html'),    protocol: 'file:',    slashes: true  }))  mainWindow.webContents.openDevTools()  mainWindow.on('closed', function () {    mainWindow = null  })}app.on('ready', createWindow)app.on('window-all-closed', function () {  if (process.platform !== 'darwin') {    app.quit()  }})app.on('activate', function () {  if (mainWindow === null) {    createWindow()  }})

7.编写Electron的index.html

<!DOCTYPE html><html><script>var ffi = require('ffi');var demo = ffi.Library('./native/libdemo', {  'Add': [ 'double', [ 'double', 'double'] ]});window.onload = function() {    console.log(demo.Add(12345, 54321));}</script></html>

12.测试效果:

Electron .

参考:

node-ffi

electron快速上手

prebuild工具

0 0
原创粉丝点击