Calling procedure from dll in Delphi XE2

654 Views Asked by At

So, I'm trying to call a procedure from a DLL in Delphi XE2. but the procedure just won't assign.

I have tried several examples found on the internet. The DLL is being loaded as expected. The exports are correctly written.

Everything seems fine but still no success.

What is up with that?

The code I have is the following

type
  TStarter = procedure; stdcall;

...

fTheHookStart: TStarter;

...

procedure TForm1.LoadHookDLL;
begin
  LogLn('Keyboard Hook: Loading...');
  // Load the library
  DLLHandle := LoadLibrary('thehookdll.DLL');

  // If succesful ...
  if Handle <> 0 then
  begin
    LogLn('Keyboard Hook: DLL load OK!');
    LogLn('Keyboard Hook: assigning procedure ...');

    fTheHookStart := TStarter(GetProcAddress(DLLHandle, 'StartTheHook'));
    if @fTheHookStart <> nil then
    begin
      LogLn('Keyboard Hook: procedure assignment OK!');
      LogLn('Keyboard Hook: Starting...');
      fTheHookStart;
    end
    else
    begin
      LogLn('Keyboard Hook: procedure assignment FAIL!');
      FreeLibrary(DLLHandle);
      if Handle <> 0 then LogLn('Keyboard Hook: DLL free OK!') else LogLn('Keyboard Hook: DLL free FAIL!');
    end;
  end
  else
  begin
    LogLn('Keyboard Hook: DLL load FAIL!');
  end;
end;
2

There are 2 best solutions below

0
On BEST ANSWER

One error is that you assign DllHandle when you load the dll, but then you check if Handle <> nil. Handle is actually your forms handle, which ofcourse is not nil. That will not matter if the loading succeeded, but if it failed, you will get wrong logging. Since you also have some logging functions, what does the log show?

5
On

As I understand it, the DLL loads, but GetProcAddress returns nil. There is only one such failure mode. The DLL does not export a function with that name.

Watch out for name decoration and letter case. C and C++ DLLs may export decorated names. And exported names are sensitive to letter case.

Use dumpbin or Dependency Walker to check the exported function name.

For reference, when GetProcAddress fails, as the documentation explains, a call to GetLastError will yield an error code.


And it looks like the other answer is onto something. You believe that you have loaded the DLL correctly, but your code doesn't perform that check correctly.

If you'd called GetLastError then the system could have alerted you to this. If you'd inspected the variables under the debugger, the problem would have been obvious.