Delphi调用C++ DLL多输出参数传递
开发环境
- VS2015
- Dephi 6
C++编写DLL
使用VS2015创建生成DLL的空的工程TestDLL,添加一个test.cpp文件,编写代码如下:
extern "C" int __declspec(dllexport) __stdcall Add(int x, int y)
{
return x + y;
}
extern "C" int __declspec(dllexport) __stdcall Generate(unsigned char* result, unsigned char* width, unsigned char* height, int * size)
{
result[0] = 5;
result[1] = 6;
result[2] = 7;
*width = 10;
*height = 20;
*size = 3;
return 0;
}
添加一个模块定义文件Source.def,编写内容如下:
LIBRARY TestDLL
EXPORTS
Add
Generate
选择Release和x86模式,点击生成TestDLL,即可生成TestDLL.dll文件。
Delphi编写代码
创建一个工程,代码如下:
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TForm1 = class(TForm)
btnAdd: TButton;
edtResult: TEdit;
lbl1: TLabel;
edtWidth: TEdit;
lblHeight: TLabel;
edtHeight: TEdit;
lbl2: TLabel;
edtSize: TEdit;
lbl3: TLabel;
edtValue: TEdit;
lbl4: TLabel;
procedure btnAddClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
function Add(a:Integer; b:Integer):Integer;stdcall;external 'TestDLL.dll';
function Generate(result:PByte; width: PByte; height: PByte; size: PInteger):Integer;stdcall;external 'TestDLL.dll';
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.btnAddClick(Sender: TObject);
var
res: Integer;
retData: array[0..10] of Byte;
width: Byte;
height: Byte;
size: Integer;
resultStr: string;
i:Integer;
begin
res := Generate(@retData, @width, @height, @size);
edtWidth.Text := IntToStr(width);
edtHeight.Text := IntToStr(height);
edtSize.Text := IntToStr(size);
i := 0;
for i := 0 to size-1 do
resultStr := resultStr + ' ' + IntToStr(retData[i]);
edtValue.Text := resultStr;
edtResult.Text := IntToStr(res);
end;
end.
执行程序,得到如下结果:
可以看到,C++的DLL可以向Delphi中传出数组和整数等。