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

相关文章
相关标签/搜索