DLL调用正常,但在freelibrary出错。
caike 2005-10-19 01:41:15 在程序中我动态调用DLL中的函数,DLL文件中包含一个form,引出的函数将建立一个form,执行都很正常,但在freelibrary时出错,提示如下:
Project e:\delphi\test.exe raised too many consecutive exceptions:'access violation at 0x00000000:read of address 0x00000000',Process stopped.
后来经过各种方法试验,发现不用freelibrary这条语句,程序就执行正常。我觉得奇怪,就试着运行delphi5开发人员指南中的DLL一章的例子,也出现同样的错误。Delphi5开人员指南的例子如下:
================
DLL代码
================
library CalendarLib;
uses
ShareMem,
SysUtils,
Classes,
DLLFrm in 'DLLFrm.pas' {DLLForm};
exports
ShowCalendar;
begin
end.
========
DLLFrm.pas代码
========
unit DLLFrm;
interface
uses
SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls,
Forms, Dialogs, Grids, Calendar;
type
TDLLForm = class(TForm)
calDllCalendar: TCalendar;
procedure calDllCalendarDblClick(Sender: TObject);
end;
{ Declare the export function }
function ShowCalendar(AHandle: THandle; ACaption: String): TDateTime; StdCall;
implementation
{$R *.DFM}
function ShowCalendar(AHandle: THandle; ACaption: String): TDateTime;
var
DLLForm: TDllForm;
begin
// Copy application handle to DLL's TApplication object
Application.Handle := AHandle;
DLLForm := TDLLForm.Create(Application);
try
DLLForm.Caption := ACaption;
DLLForm.ShowModal;
Result := DLLForm.calDLLCalendar.CalendarDate; // Pass the date back in Result
finally
DLLForm.Free;
end;
end;
procedure TDLLForm.calDllCalendarDblClick(Sender: TObject);
begin
Close;
end;
end.
=================================
调用程序代码
=================================
unit MainFfm;
interface
uses
SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls,
Forms, Dialogs, StdCtrls;
type
TShowCalendar = function (AHandle: THandle; ACaption: String): TDateTime; StdCall;
EDLLLoadError = class(Exception);
TMainForm = class(TForm)
lblDate: TLabel;
btnGetCalendar: TButton;
procedure btnGetCalendarClick(Sender: TObject);
end;
var
MainForm: TMainForm;
implementation
{$R *.DFM}
procedure TMainForm.btnGetCalendarClick(Sender: TObject);
var
LibHandle : THandle;
ShowCalendar: TShowCalendar;
begin
LibHandle := LoadLibrary('CALENDARLIB.DLL');
try
if LibHandle = 0 then
raise EDLLLoadError.Create('Unable to Load DLL');
@ShowCalendar := GetProcAddress(LibHandle, 'ShowCalendar');
if not (@ShowCalendar = nil) then
lblDate.Caption := DateToStr(ShowCalendar(Application.Handle, Caption))
else
RaiseLastWin32Error;
finally
FreeLibrary(LibHandle); //这一句出错
end;
end;
开始我以为是参数类型为String的问题,但后来试着将String改为Pchar,还是出现同样的问题。
实在是不知该问题出在哪里,还请大侠们指点,谢谢!