2008. június 4., szerda

Dynamic loading and binding of DLLs


Problem/Question/Abstract:

Dynamic loading and binding of DLLs

Answer:

Sometimes you may need to load a DLL at runtime, for example

if you have a couple of different DLLs to choose between
to have a concept for optional functionality.

This small source code shows how to load the DLL with LoadLibrary and use the returned handle to access (bind) the functions that are contained:

{ function declaration }

type
  � TfncCnx = function(s: string): THandle;

var
  � cnx: TfncCnx;
begin
  { load the DLL and get the function's address }
  � h := LoadLibrary('myDll');
  if h = 0 then
  begin
    ShowMessage('DLL not available');
  end
  else
  begin
    �@cnx := GetProcAddress(h, 'myProc');
    if @cnx = nil then
    begin
      { function not found.. misspelled? }
      ShowMessage('blub');
    end
    else
    begin
      { call the function as usually }
      x := cnx('alpha');
    end;
    { unload the DLL }
    � FreeLibrary(h);
  end;
end;

Nincsenek megjegyzések:

Megjegyzés küldése