Delphi- DLL操作

  动态链接库(Dynamic Link Library)是一个可以执行的并可以被多个Windows应用程序共享的程序模块(Module)。模块中包含代码、数据和资源。
  动态链接库的优点:不用重复编译和链接,一旦装入内存,DLL中的函数就可以被系统中的任何在运行的应用程序使用,而不必产生函数的多个COPY。
  DLL和EXE很类似,区别在于,DLL文件中虽然包含了可执行代码却不能单独执行,只能由Windows应用程序直接或间接调用。


  静态链接是将应用程序调用的库函数COPY一份到应用程序中去。
  动态链接,当应用程序使用了某个DLL中的函数时,动态链接不COPY代码,还是在运行期间在DLL的位置寻找所需的函数代码。

第一种方法:

生动DLL,不能直接行运,在prjoect里按complie,或者按ctrl + F9编译运行,将生成的DLL,复制到新项目中用。

uses
  SysUtils,
  Classes;

{$R *.res}

function Max(x,y,z:Integer):Integer;stdcall;
var
  t:Integer;
begin
  if (x<y) then
    t := y;
  else
    t := x;

  if (t<z) then
    t := z;

  Result := t;
end;

begin

end.

测试调用运行:

var
  Form1: TForm1;
  function Max(x,y,z:Integer):Integer;stdcall;external 'ProjectMax.dll';

implementation

{$R *.dfm}

procedure TForm1.btn1Click(Sender: TObject);
var
  t: Integer;
begin
  t := Max(3,4,1);
  ShowMessage(IntToStr(t));
end;

动态调用DLL

type
  Max = function(x,y,z:integer):integer; stdCall;

procedure TForm1.btn1Click(Sender: TObject);
var
  temp: Integer;
  handle: THandle;
  FPointer: TFarProc;
  MyFunc: Max;
begin

  handle := LoadLibrary('ProjectMaxDll.dll');
  if handle <> 0 then
  begin
      FPointer := GetProcAddress(handle,'Max');
      if  FPointer<>nil then
      begin
        MyFunc:= Max(FPointer);
        temp:= MyFunc(1,2,3);
        ShowMessage(IntToStr(temp));
      end
      else
      begin

      end
  end
  else
    ShowMessage('未找到动态链接库!');

end;
原文地址:https://www.cnblogs.com/cxeye/p/3529413.html