electron调用dll插件

方法1:

const path = require('path')
const ffi = require('ffi-napi')
const ref = require('ref-napi')
// 设置依赖目录
const dependPath = path.resolve(__dirname, '../dll/')

// 指定寻找DLL依赖的目录
// 如果不设置则会在window系统去找,找不到则会报错
var kernel32 = ffi.Library("kernel32", {
  'SetDllDirectoryA': ["bool", ["string"]]
  })
kernel32.SetDllDirectoryA(dependPath);

//  引用DLL 并且初始化dll中的方法
var lib = ffi.Library('XX.dll', {
    'Init': ['int', []],
    'Release': ['int', []],
    'EnableResize': ['void', ['int']]
  });
// 调用方法
lib.Init();

注意DLL插件放在目录下,打包时需要将目录移动到指定位置

以vue-cli为例

const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  pluginOptions: {
    electronBuilder: {
      nodeIntegration: true,
      externals: ['ffi-napi', 'ref-napi'],
      builderOptions: {
   		 // 拷贝dll等静态文件到指定位置
      	"extraResources": {
      		"from": "./bottom",
        	"to": "bottom"
      		}
        }
    }
  }
})

方法2:推荐

方法1虽然可以实现 dll在指定目录中寻找依赖,但存在一个问题。

问题:如果安装目录中存在中文,则会找不到指定目录,抛出错误

解决:运行时通过配置环境变量的方式去指定依赖目录

const dependPath = path.resolve(__dirname, '../bottom/') // 指定依赖的目录
process.env.PATH = `${process.env.PATH}${path.delimiter}${dependPath}`;
Last Updated: