安装ffi-napi
1、安装ffi-napi,ref-napi ,ref-array-napi,ref-struct-napi 依赖
npm i ffi-napi ref-napi ref-array-napi ref-struct-napi -S
注:ffi-napi 会自动调用windows编译工具进行编译,但是 ref-napi 不会,还需要手动执行 node-gyp 命令进行编译
cd node_modules\ref-napi\
node-gyp configure
node-gyp build
cd xx:\xxxxx
2、编写引用js
.cpp文件
#include "MyCode.h"
int Add ( int a , int b )
{
return ( a + b );
}
MyCode.h
#ifndef _MYCODE_H_
#define _MYCODE_H_
#ifdef DLLDEMO1_EXPORTS
#define EXPORTS_DEMO _declspec( dllexport )
#else
#define EXPORTS_DEMO _declspec(dllimport)
#endif
extern "C" EXPORTS_DEMO int Add (int a , int b);
#endif
生成.dll文件 MyDll.dll,新建引用dll方法的js文件
const ffi = require('ffi-napi') 引用ffi-napi
const path = require('path') 引用path
let { arch } = process 判断本地是32位还是64位
//默认加载 32位 DLL
let dllFilePath = path.resolve('resources/DLLDemo1')
if (arch === 'x64') {
dllFilePath = path.resolve('resources/DLLDemo1')
}
// 加载 DLL文件,无需写扩展名,将DLL中的函数映射成JS方法
// 导出为JS方法
//dll中函数
const MyDellDemo = new ffi.Library(dllFilePath, {
// 方法名必须与C函数名一致,dll中函数为Add
Add: [
'int', // 对应 C函数返回类型
['int', 'int'] // C函数参数列表
]
})
module.exports = {
add(x, y) {
return MyDellDemo.Add(x, y)
}
}
引用dll进程
import { add } from './MyDll' 引用编写的引用文件地址
var num = add(1,2); 调用dll中add方法,获取1+2值