一、调用代码
Delphi版本Delphi 10 Seattle
Delphi代码
unit Unit1;interfacefunction testint(i: Integer): Integer; stdcall;function testpchar(value: PAnsiChar): PAnsiChar; stdcall;implementationfunction testint(i: Integer): Integer; stdcall;beginresult := i + 1000;end;function testpchar(value: PAnsiChar): PAnsiChar; stdcall;varsvalue: string;beginsvalue := Utf8ToAnsi(value);svalue := '你好:' + svalue;result := PAnsiChar(AnsiToUtf8(svalue));end;end.
library test;{ Important note about DLL memory management: ShareMem must be thefirst unit in your library's USES clause AND your project's (selectProject-View Source) USES clause if your DLL exports any procedures orfunctions that pass strings as parameters or function results. Thisapplies to all strings passed to and from your DLL--even those thatare nested in records and classes. ShareMem is the interface unit tothe BORLNDMM.DLL shared memory manager, which must be deployed alongwith your DLL. To avoid using BORLNDMM.DLL, pass string informationusing PChar or ShortString parameters. }usesSystem.SysUtils,System.Classes,Unit1 in 'Unit1.pas';{$R *.res}exportstestint,testpchar;beginend.
所有的string类型都需要定义成PAnsiChar
此处nodejs使用的编码是utf8,需要转码
返回值,需先通过AnsiString转换,再转换PAnsiChar
Node.js代码
var ffi = require('ffi');try {var demo = ffi.Library('test.dll', {'testint': [ 'int', ['int'] ],'testpchar' : [ 'string', ['string'] ],});console.log(demo);const info = demo.testint(1);console.log(JSON.parse(info));const info2 = demo.testpchar('啊啊啊');console.log(info2);console.log('End Test');} catch(err) {console.log(err);}
二、ffi安装
由于node-ffi/ref包含 C 原生代码,所以安装需要配置 Node 原生插件编译环境。
npm install --global --production windows-build-tools
npm install -g node-gyp
安装对应的库
npm install ffi
三、调用出错解决
1、Error: Dynamic Linking Error: Win32 error 193
这个是Windows动态库方面的错误,查询Windows错误码大全,193这个编号的意思是不是有效的win32程序。检查发现这里出错原因是Node.js是64位而dll是32位的,将dll编译成64位后正常输出。