动态和静态调用DLL

写一个简单的动态库,动态库中有一个求和函数,函数返回求和结果
 DLL的工程单元代码:

library wudll;  
  
uses  
  SysUtils,  
  Classes,  
  Unit1 in 'Unit1.pas';  
  
{$R *.RES}  
  exports   //用exports 声明函数出口  
    Wuadd;  
  
begin  
end.

DLL中的写了函数体的单元Unit1代码:

unit Unit1;

interface
   function Wuadd(anum1,Anum2:Integer):Integer;stdcall; //函数声明
                  //Delphi 默认采用 register 调用约定,如果dll涉及跨语言调用,最好明确指出采用 stdcall 调用约定
implementation

function Wuadd(Anum1,Anum2:Integer):Integer;stdcall;  //函数体
begin
  Result:=0;
  Result:=Anum1+Anum2;
end;
end.

---------------------------------------
以下为调用该动态库

新建Form1, 点击按钮则调用DLL计算Edit1和Edit2的和,并将结果赋值给Edit3

unit Unit1;    

interface

uses
  ShareMem,Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
  StdCtrls;
          //ShareMem 如果dll涉及长字符串的参数或变量,需要在 uses 第一的位置引用 ShareMem 单元。
type
 Twuabc=function (num1,num2:Integer):Integer;stdcall; //动态调用声明 必须写在type下
 TForm1 = class(TForm)
   Edit1: TEdit;
   Edit2: TEdit;
   Button1: TButton;
   Edit3: TEdit;
   Button2: TButton;
   procedure Button1Click(Sender: TObject);
   procedure Button2Click(Sender: TObject);
   private
   { Private declarations }
   public
   { Public declarations }
   end;

   function Wuadd(Anum1,Anum2:Integer):Integer;stdcall;external'd:\wudll.dll'; 
              //静态调用DLL声明,必须写在type外面或implementation下面,这里的函数名必须和DLL中的函数名相同,大小写敏感
var
  Form1: TForm1;
implementation
  {$R *.DFM}

  //function Wuadd(Anum1,Anum2:Integer):Integer;stdcall;external'd:\wudll.dll'; 

procedure TForm1.Button1Click(Sender: TObject);//动态调用DLL
var
  wuhandle:THandle;
  wufunc:Twuabc;
  str1:Integer;
begin wuhandle:=LoadLibrary('d:/wudll.dll'); //加载 DLL 到内存
  if wuhandle<>0 then begin
    try
      @wufunc:=GetProcAddress(wuhandle,'Wuadd'); //获得函数的入口地址
      if @wufunc<>nil then begin
        str1:=wufunc(StrToInt(Edit1.Text),StrToInt(Edit2.Text)); //调用DLL中的函数
        Edit3.Text:=IntToStr(str1);
      end;
    finally
      FreeLibrary(wuhandle);
    end;
  end;
end;
procedure TForm1.Button2Click(Sender: TObject);//静态调用DLL
var
  str1:Integer;
begin
  str1:=Wuadd(StrToInt(Edit1.Text),StrToInt(Edit2.Text)); //调用DLL中的函数
  Edit3.Text:=IntToStr(str1);
end;

end.


 





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值