Delphi Dll 动态调用例子

Posted 我的学习笔记

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Delphi Dll 动态调用例子相关的知识,希望对你有一定的参考价值。

http://blog.sina.com.cn/s/blog_62c46c3701010q7h.html

 

一、编写dll

library TestDllByD2007;

uses
  SysUtils,
  Classes;
  function test(const astr:PChar):Boolean;stdcall;
  begin
    Result:=True;
  end;
{$R *.res}
  exports test;
begin
end.

注意:1.不能使用string类型,否则涉及到资源释放的问题,使用Pchar代替string。

        2.Dll中不能直接返回string,除非引用ShareMem单元,发布程序时需要包含BORLNDMM.DLL

二、编写测试窗体,就一个button.在button的代码中,实现dll的动态加载和释放。

unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls;

type
  TFTest=function (const astr:PChar):Boolean;
  TForm1 = class(TForm)
    btn1: TButton;
    procedure btn1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.btn1Click(Sender: TObject);
var
  sdll:string;
  tfTTT:TFTest;
  handle:THandle;
  sstr:string;//声明该变量,目的是避免发生异常。
begin
  sdll:=‘TestDllByD2007.dll‘;
  Caption:=‘‘;
  handle:=LoadLibrary(PAnsiChar(sdll));
  if Handle <> 0 then
  begin
    @tfTTT := GetProcAddress(Handle, ‘test‘);
    if @tfTTT <> nil then
    begin
      sstr:=‘testsss‘;
      if tfTTT(PChar(sstr))=True then
      begin
        Caption:=‘true‘;
      end
      else
      begin
        Caption:=‘false‘;
      end;
    end
    else
    begin
      Caption:=‘can not find the test function‘;
    end;
    FreeLibrary(Handle);
  end
  else
  begin
    Caption:=‘can not load library ‘+ sdll;
  end;
end;

end.

以上是关于Delphi Dll 动态调用例子的主要内容,如果未能解决你的问题,请参考以下文章

Delphi Dll 动态调用例子

delphi 怎么动态调用dll中的过程

关于delphi中动态调用dll时出现的问题

Delphi7 dll 动态调用的问题

DLL_Delphi动态调用

Delphi DLL文件的动态调用