在 nodejs / elctron 中,可以通過(guò) node-ffi ,通過(guò) Foreign Function Interface 調(diào)用動(dòng)態(tài)鏈接庫(kù),俗稱調(diào)DLL,實(shí)現(xiàn)調(diào)用C/C++代碼,從而實(shí)現(xiàn)許多node不好實(shí)現(xiàn)的功能,或復(fù)用諸多已實(shí)現(xiàn)的函數(shù)功能。
node-ffi是一個(gè)用于使用純 JavaScript 加載和調(diào)用動(dòng)態(tài)庫(kù)的Node.js插件。它可以用來(lái)在不編寫任何C ++代碼的情況下創(chuàng)建與本地DLL庫(kù)的綁定。同時(shí)它負(fù)責(zé)處理跨JavaScript和C的類型轉(zhuǎn)換。
與 Node.js Addons 相比,此方法有如下優(yōu)點(diǎn):
與 Node.js Addons 相比,此方法有如下優(yōu)點(diǎn):
- 不需要源代碼。
- 不需要每次重編譯
node,Node.js Addons引用的.node會(huì)有文件鎖,會(huì)對(duì)`electron應(yīng)用熱更新造成麻煩。- 不要求開發(fā)者編寫C代碼,但是仍要求開發(fā)者具有一定C的知識(shí)。
復(fù)制代碼
缺點(diǎn)是:
- 性能有折損
- 類似其他語(yǔ)言的FFI調(diào)試,此方法近似黑盒調(diào)用,差錯(cuò)比較困難。
復(fù)制代碼
安裝
node-ffi 通過(guò) Buffer 類,在C代碼和JS代碼之間實(shí)現(xiàn)了內(nèi)存共享,類型轉(zhuǎn)換則是通過(guò) ref、 ref-array 、 ref-struct 實(shí)現(xiàn)。由于 node-ffi / ref 包含C原生代碼,所以安裝需要配置Node原生插件編譯環(huán)境。
npm install ffi
npm install ref
npm install ref-array
npm install ref-struct
解決辦法
下面是可能出現(xiàn)的問(wèn)題及解決辦法
我這里遇到的問(wèn)題是
gyp ERR! build error
gyp ERR! stack Error: `make` failed with exit code: 2
gyp ERR! stack at ChildProcess.onExit (/usr/local/lib/node_modules/npm/node_modules/node-gyp/lib/build.js:269:23)
gyp ERR! stack at ChildProcess.emit (events.js:110:17)
gyp ERR! stack at Process.ChildProcess._handle.onexit (child_process.js:1074:12)
gyp ERR! System Linux 3.19.0-26-generic
gyp ERR! command "node" "/usr/local/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild"
gyp ERR! cwd /usr/local/lib/node_modules/protractor/node_modules/selenium-webdriver/node_modules/ws/node_modules/utf-8-validate
gyp ERR! node -v v0.12.4
gyp ERR! node-gyp -v v2.0.2
gyp ERR! not ok
解決辦法
$ npm cache clean
$ rm -rf node_modules
$ rm -rf ~/.node-gyp
刪除當(dāng)前用戶目錄下的.node-gyp文件夾及.npmrc文件