{ Important note about DLL memory management: ShareMem must be the
first unit in your library's USES clause AND your project's (select
Project-View Source) USES clause if your DLL exports any procedures or
functions that pass strings as parameters or function results. This
applies to all strings passed to and from your DLL--even those that
are nested in records and classes. ShareMem is the interface unit to
the BORLNDMM.DLL shared memory manager, which must be deployed along
with your DLL. To avoid using BORLNDMM.DLL, pass string information
using PChar or ShortString parameters. }
uses
SysUtils,
Classes,
//再在Uses下声明一个函数:
function Add(a, b: integer):integer; // 函数功能 实现a,b相加
begin
result := a + b;
endexports add; // 必须要有这句才能输出
begin
end.
这样一个简单的dll就创建成功了,保存为test,建议最好把建好的dll放在和调用项目放在一起,
接下来就是调用了,调用很简单:
新建一个application,在implementation上面引用刚刚写的dll函数:
function apnr(a,b: integer):integer; external 'test.dll';
这里注意,大小写要和dll里的函数一样。
放一个按钮,在OnClick事件中调用dll里函数就行。
procedure TForm2.Button1Click(Sender: TObject);
begin
ShowMessage(add(1, 2)); //3
end;
但是当返回值是string时,调用会报指针内存错误,比如说:(至少在delphi7里)
//dll里函数
function add(a, b: integer): string;
begin
result := IntToStr(a + b);
end;
解决方法: