Delphi调用c++写的dll (me)

unit Unit1;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;

type
  TForm1 = class(TForm)
    btn1: TButton;
    btn2: TButton;
    procedure btn1Click(Sender: TObject);
    procedure btn2Click(Sender: TObject);

  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

  function add(a:integer;b:integer):integer;cdecl;external 'mydllForDelphi.dll' ;
  function sub(a:integer;b:integer):integer;cdecl;external 'mydllForDelphi.dll' ;

implementation

{$R *.dfm}

//mydllForDelphi.dll  c++写的dll中的代码
// extern "C" __declspec(dllexport) int add(int a, int b)
//{
//    return (a + b);
//}
//
//extern "C" __declspec(dllexport) int sub(int a, int b)
//{
//    return (a - b);
//}

procedure TForm1.btn1Click(Sender: TObject);
begin
  self.caption:= inttostr(add(4,3));
  self.caption:=self.caption+'///' +inttostr(sub(4,3));
end;

procedure TForm1.btn2Click(Sender: TObject);
//  function add(a:integer;b:integer):integer;cdecl;external 'mydllForDelphi.dll' ;
type
  TIntFunc=function(a:integer;b:integer):integer;cdecl; //cdecl 不能少
var
  Th: Thandle;
  Tf:TIntFunc;
  Tp,tp2:TFarProc ;
begin
  Th:= loadlibrary('mydllForDelphi.dll');
  if Th >0 then
  try
    Tp:=GetProcAddress(Th, PChar('add'));
    if Tp<>nil then
    begin
      Tf:=TIntFunc(Tp);
      Self.Caption:=IntToStr(Tf(9,1)); {调用TestC函数}
    end;

    Tp2:=GetProcAddress(Th, PChar('sub'));
    if Tp2<>nil then
    begin
      Tf:=TIntFunc(Tp2);
      Self.Caption:=Self.Caption+'|||'+IntToStr(Tf(9,1)); {调用TestC函数}
    end;

  finally
    freelibrary(th);
  end;

end;

end.
posted @ 2020-01-07 15:24  创新创造学习整合套路  阅读(520)  评论(0编辑  收藏  举报