Newsgroups : Borland : borland.public.delphi.nativeapi.win32 : 2007 Nov : Dynamically loaded DLL access violation
| Subject: | Dynamically loaded DLL access violation |
| Posted by: | "Stephen Froude" (stephen.frou..@sec.eu.c0m) |
| Date: | 13 Nov 2007 03:55:26 |
Apologies in advance if this isn’t the correct group.
I’m trying to dynamically load a third party DLL and call one of
its functions but I keep getting an access violation. At first I
thought the problem was in the DLL but if I change the code to
statically load the DLL it works fine. Can anyone help? I’ve
posted both version of the code below for reference (Delphi 6).
The function takes 2 parameters, an integer error code and a
string. The idea being you pass in the error code and it returns
the error description.
//
// Dynamic code – causes an access violation
//
procedure TForm1.Button1Click(Sender: TObject);
type
TGetErrorText = function(iErrorCode: Integer; pErrorText: PChar): Integer;
var
hDLL: THandle;
fFunc: TGetErrorText;
aText: array[0..256] of Char;
begin
hDLL := LoadLibrary('C:\max32.dll');
if hDLL <= HINSTANCE_ERROR then
raise Exception.Create('Unable to load the library.');
@fFunc := GetProcAddress(hDLL, 'GetErrorText');
if @fFunc <> nil then
begin
fFunc(19, @aText);
Label1.Caption := aText;
end;
FreeLibrary(hDLL);
end;
//
// Static code – works fine
//
function GetErrorText(iErrorCode: Integer; pErrorText: PChar): Integer; stdcall; external 'C:\max32.dll';
procedure TForm1.Button1Click(Sender: TObject);
var
aText: array[0..256] of Char;
begin
GetErrorText(19, @aText);
Label1.Caption := aText;
end;
TIA
Stephen