一、环境准备:
调用Dll需要安装node-ffi-napi,由于node-ffi-napi包含 C 原生代码,所以安装需要配置 Node 原生插件编译环境
https://github.com/node-ffi-napi/node-ffi-napi
npm install --global --production windows-build-tools
npm install -g node-gyp
npm install ffi-napi
二、Delphi窗体Dll编写
2.1 Project1代码
library Project1;
uses
System.SysUtils,
System.Classes,
Unit1 in 'Unit1.pas' {Form1};
{$R *.res}
exports
ShowForm;
begin
end.
2.2 窗体单元代码Unit1
unit Unit1;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
procedure ShowForm; stdcall;// 需要从DLL中导出的函数,一定要有stdcall关键字
implementation
procedure ShowForm; stdcall;
begin
try
Form1 := TForm1.Create(nil);
try
Form1.ShowModal;
finally
Form1.Free;
end;
except
on E: Exception do
ShowMessage(E.ToString);
end;
end;
{$R *.dfm}
end.
三、将编译好Dll放入程序目录下,然后再Electron主进程main.js中引用Dll
// 调用Dll
const ffi = require('ffi-napi');
var libm = ffi.Library('Project1.dll', {
'ShowForm': ['void', []],
});
libm.ShowForm();
四、如果是渲染进程(web页面)要调用,则需要通过主进程与渲染进程通信,然后调用
4.1 主进程main.js
// 获取ipc
const {ipcMain} = require('electron')
// 调用Dll
const ffi = require('ffi-napi');
var libm = ffi.Library('Project1.dll', {
'ShowForm': ['void', []],
});
// 监听ipc通道
ipcMain.on('showForm', e => libm.ShowForm());
4.2 渲染进程调用,以Vue为例
<template>
<div style="width: 100%;height: 100%;background-color:#b979ff;">
<img src="../assets/logo.png" alt="" @click="showForm">
</div>
</template>
<script>
//if (window.require) {
const {ipcRenderer} = window.require('electron');
// }
export default {
name: "Setting",
methods: {
showForm: function () {
console.log("showForm");
ipcRenderer.send("showForm");
// if (window.require) {
// console.log("max");
// ipcRenderer.send("max");
// }
}
}
}
</script>
<style scoped>
</style>