Delphi中高階DLL的編寫和呼叫技巧

2021-05-17 14:09:46 字數 2939 閱讀 6928

根據delphi提供的有關 dll編寫和呼叫的幫助資訊,你可以很快完成一般的 dll編寫和呼叫的 應用程式。本文介紹的主題是如何編寫和呼叫能夠傳遞各種引數(包括物件例項)的 dll。例如, 主叫程式傳遞給 dll乙個adoconnection 物件示例作為引數, dll中的函式和過程呼叫通過該物件 例項訪問資料庫。

需要明確一些基本概念。對於 dll,需要在主程式中包含 exports子句,用於向外界提供呼叫 介面,子句中就是一系列函式或過程的名字。對於主叫方(呼叫 dll的應用程式或其它的 dll), 則需要在呼叫之前進行外部宣告,即external保留字指示的宣告。這些是編寫 dll和呼叫 dll必須 具備的要素。

另外需要了解object pascal 中有關呼叫協議的內容。在object pascal 中,對於過程和函式 有以下五種呼叫協議:

指示字 引數傳遞順序 引數清除者 引數是否使用暫存器

register 自左向右 被調例程 是

pascal 自左向右 被調例程 否

cdecl 自右向左 呼叫者 否

stdcall 自右向左 被調例程 否

safecall 自右向左 被調例程 否

這裡的指示字就是在宣告函式或過程時附加在例程標題之後的保留字,預設為register,即是 唯一使用 cpu暫存器的引數傳遞方式,也是傳遞速度最快的方式;

pascal: 呼叫協議僅用於向後相容,即向舊的版本相容;

cdecl: 多用於 c和 c++語言編寫的例程,也用於需要由呼叫者清除引數的例程;

stdcall: 和safecall主要用於呼叫windows api 函式;其中safecall還用於雙重介面。

在本例中,將使用呼叫協議cdecl ,因為被呼叫的 dll中,使用的資料庫連線是由主叫方傳遞 得到的,並且需要由主叫方處理連線的關閉和銷毀。

下面是 dll完整源程式和主叫程式完整源程式。包括以下四個檔案:

project1.dpr

unit1.pas

project2.dpr

unit2.pas

library project2;

uses

sysutils,

classes,

unit2 in 'unit2.pas' ;

exports

dotest;

begin

end.

unit unit2;

inte***ce

uses

windows, messages, sysutils, classes, graphics, controls, forms, dialogs,

db, adodb, stdctrls, menus;

type

tform1 = class(tform)

adoconnection1: tadoconnection;

memo1: tmemo;

private

public

end;

procedure dotest(h: thandle;

aconn: tadoconnection;

s: string;

n: integer);

cdecl;

implementation

end.

program project1;

uses

forms,

unit1 in 'unit1.pas' ;

unit unit1;

inte***ce

uses

windows, messages, sysutils, classes, graphics, controls, forms, dialogs,

stdctrls, db, adodb;

type

tform1 = class(tform)

button1: tbutton;

adoconnection1: tadoconnection;

procedure button1click(sender: tobject);

private

public

end;

varform1: tform1;

implementation

procedure dotest(h: thandle;

aconn: tadoconnection;

s: string;

n: integer);

cdecl;

external 'project2.dll';

end.

procedure tform1.button1click(sender: tobject);   

type  

tintfunc=function(i:integer):integer;stdcall;   

var  

th:thandle;   

tf:tintfunc;   

tp:tfarproc;   

begin  

th:=loadlibrary(』cpp.dll』);   

if th>0 then  

try  

tp:=getprocaddress(th,pchar(』testc』));   

if tp<>nil  

then begin  

tf:=tintfunc(tp);   

edit1.text:=inttostr(tf(1));   

end  

else  

showmessage(』testc函式沒有找到』);   

finally  

freelibrary(th);   

end  

else  

showmessage(』cpp.dll沒有找到』);   

end;  

Delphi中高階DLL的編寫和呼叫

根據delphi提供的有關 dll編寫和呼叫的幫助資訊,你可以很快完成一般的 dll編寫和呼叫的 應用程式。本文介紹的主題是如何編寫和呼叫能夠傳遞各種引數 包括物件例項 的 dll。例如,主叫程式傳遞給 dll乙個adoconnection 物件示例作為引數,dll中的函式和過程呼叫通過該物件 例項...

Delphi中高階DLL的編寫和呼叫 收藏

根據delphi提供的有關 dll編寫和呼叫的幫助資訊,你可以很快完成一般的 dll編寫和呼叫的 應用程式。本文介紹的主題是如何編寫和呼叫能夠傳遞各種引數 包括物件例項 的 dll。例如,主叫程式傳遞給 dll乙個adoconnection 物件示例作為引數,dll中的函式和過程呼叫通過該物件 例項...

C 呼叫delphi編寫的dll

技術實現 如何逐步實現動態庫的載入,型別的匹配,動態鏈結庫函式匯出的定義,參考下面巨集定義即可 define libexport api extern c declspec dllexport 第一步,我先從簡單的呼叫出發,定義了乙個簡單的函式,該函式僅僅實現乙個整數加法求和 libexport a...