delphi 建立DLL檔案 及其呼叫和注意事項

2022-08-20 03:30:12 字數 1070 閱讀 5140

首先建立乙個dll檔案,專案自帶的**為:

library projectpnr;

uses

sysutils,

classes,

//再在uses下宣告乙個函式:

function add(a, b: integer):integer; // 函式功能 實現a,b相加

begin

result := a + b;

endexports add; // 必須要有這句才能輸出

begin

end.

這樣乙個簡單的dll就建立成功了,儲存為test,建議最好把建好的dll放在和呼叫專案放在一起,

接下來就是呼叫了,呼叫很簡單:

function apnr(a,b: integer):integer; external 'test.dll';

這裡注意,大小寫要和dll裡的函式一樣。

放乙個按鈕,在onclick事件中呼叫dll裡函式就行。

procedure tform2.button1click(sender: tobject);

begin

showmessage(add(1, 2)); //3

end;

但是當返回值是string時,呼叫會報指標記憶體錯誤,比如說:(至少在delphi7裡)

//dll裡函式

function add(a, b: integer): string;

begin

result := inttostr(a + b);

end;

解決方法:

然後我將用xe開啟剛剛呼叫dll的專案,發現直接閃退,我在用d7開啟這個專案,結果有返回值,

這種現象是因為d7的pchar長度是單位元組,而xe的pchar長度是雙位元組,具體用sizeof測試,d7用的是ansi編碼,xe用的時unicode編碼,

解決方法

把pchar改成pansichar或pwidechar。

為了相容,最好把dll要返回的string變成pansichar。

Delphi除錯dll檔案

完整的除錯 dll方法如下 1 新建乙個 dll 工程,名字就叫 mydll 吧,編譯後生成 mydll.dll,我們要除錯的就是它了。3 mydlltest.exe 所在目錄中不能有 mydll.dll 重要!4 mydlltest 採用靜態呼叫的方法呼叫 mydll.dll 的匯出函式 重要!完...

建立DLL函式及其使用DLL

如果想要匯出乙個全域性函式,就用關鍵字來宣告 declspec dllexport 注意 這是vc自己特有的關鍵字,在linux下不可用。declspec dllexport int add int a,int b return a b 配置生成my.dll和my.lib檔案 在main.cpp中 ...

DELPHI中建立呼叫DLL

一,新建 new other dll wizard 二,library new uses sysutils,classes,dialogs procedure dll begin showmessage delphi end exports dll begin end.三,儲存,四,project ...