首先創建一個DLL文件,項目自帶的代碼為:
library ProjectPnr; { Important note about DLL memory management: ShareMem must be the first unit in your library's USES clause AND your project's (select Project-View Source) USES clause if your DLL exports any procedures or functions that pass strings as parameters or function results. This applies to all strings passed to and from your DLL--even those that are nested in records and classes. ShareMem is the interface unit to the BORLNDMM.DLL shared memory manager, which must be deployed along with your DLL. To avoid using BORLNDMM.DLL, pass string information using PChar or ShortString parameters. } uses SysUtils, Classes, //再在Uses下聲明一個函數: function Add(a, b: integer):integer; // 函數功能 實現a,b相加 begin result := a + b; end
exports add; // 必須要有這句才能輸出 begin end.
這樣一個簡單的dll就創建成功了,保存為test,建議最好把建好的dll放在和調用項目放在一起,
接下來就是調用了,調用很簡單:
新建一個application,在implementation上面引用剛剛寫的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;
解決方法:
將返回值string改成PChar,就可以調用了,應該是dll的處理string和application處理string的方法不一樣吧。
然后我將用XE打開剛剛調用dll的項目,發現直接閃退,我在用D7打開這個項目,結果有返回值,
這種現象是因為D7的PChar長度是單字節,而XE的PChar長度是雙字節,具體用SizeOf測試,D7用的是Ansi編碼,XE用的時Unicode編碼,
解決方法
把PChar改成PAnsiChar或PWideChar。
為了兼容,最好把dll要返回的string變成PAnsiChar。