NodeJS 調用C++(Node-ffi)
本文介紹如何用Nodejsd調用C++代碼
- 用node-ffi實現
如果調用的C++ dll是32位接口,則NodeJS也需要確保是32位。
用ffi,則NodeJS必須是V10及以下的版本
NodeJS查看版本和位數:
node -v //查看版本號
node -p 'process' //在返回的arch和platform可以看詳細信息
首先安裝node-gyp(nodejs默認安裝,若沒有則用一下命令)
npm install -g node-gyp
安裝ffi和ref
npm install ffi
npm install ref
默認安裝完會用node-gyp編譯
教程上說nodejs v11以上可以通過一下安裝,但是我還是會報錯。。。npm install @saleae/ffi
代碼測試:
npm 調用windows Api:
1 var ffi = require('ffi'); 2 3 var c_txt = text => { 4 return Buffer.from(`${text}\0`, "ucs2"); 5 }; 6 7 var current = ffi.Library("user32", { 8 "MessageBoxW": ["int32", ["int32", "string", "string", "int32"]] 9 }); 10 11 const ok_or_cancel = current.MessageBoxW(0, c_txt("Hello from NodeJs"), c_txt("node-ffi test"), 1); 12 13 console.log(ok_or_cancel);
新建一個C++ dll工程:
1 #if defined(WIN32) || defined(_WIN32) 2 #define EXPORT __declspec(dllexport) 3 #else 4 #define EXPORT 5 #endif 6 7 #ifdef __cplusplus 8 extern "C" { 9 #endif 10 11 EXPORT int foo(int param) { 12 int ret = param + 1; 13 // do C++ things 14 return ret; 15 } 16 17 EXPORT int bar() { 18 int ret = 0; 19 // do C++ things 20 return ret; 21 } 22 23 #ifdef __cplusplus 24 } 25 #endif
NodeJS中調用:
1 var basic = ffi.Library("./Project_dll_1", { 2 "foo": [ "int", ["int"] ], 3 "bar": [ "int", [] ] 4 }) 5 6 var v = basic.foo(1); 7 console.log(v);