node調用dll

安裝python2.7,必定要2.7node

https://www.python.org/download/releases/2.7/python

安裝後設置環境變量:在環境變量path中添加C:\Python27   (python路徑)npm

全局安裝原生模塊編譯模塊,編譯ffi模塊時須要用到的數組

3.7.0版本穩定python2.7

cnpm install node-gyp@3.7.0 -g

安裝後如何全局找不到模塊就設置環境變量,path中添加C:\Users\Administrator\AppData\Roaming\npm工具

安裝ffiui

cnpm install ffi --save

導入ffi編碼

const ffi=require("ffi");

調用code

var libpath = path.join(__dirname, '/termb.dll');
     

     //註冊dll中的接口
    //InitComm爲dll中的方法名,['int',['int']]第一個int是出參類型,最後一個int所在的數組放的是入參的類型
    var testLib = ffi.Library(libpath, {
        InitComm:['int',['int']]
    });


     //調用
    const dllRet = testLib.InitComm(1001);
    console.log('ret => '+dllRet);

注意:dll若是是32 bit,那麼node也要32位 接口

gbk編碼問題,若是調用dll返回的結果是string,須要解碼

var iconv = require("iconv-lite");

var testLib = ffi.Library(libpath, {
        funcName:['int',['string','int']]
});

var buffer= Buffer.alloc(10);
var resultRen=testLib.funcName(buffer,10);
var data=iconv.decode(buffer, 'GBK');

console.log(data);

若是在npm install的時候出現錯誤「MSBUILD : error MSB4132: 沒法識別工具版本「2.0」。可用的工具版本」又或者是「The imported project ....」之類的,通常都是在下載ffi模塊的時候出現問題。

解決方法:電腦下載安裝visual studio

相關文章
相關標籤/搜索