Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring a DLL inside a Delphi XE5 component

I'm creating a new component in Delphi, which instantiates a DLL

Unit UMyComponent

interface

type
  TMyComponent = class(TComponent)
    ... 
    procedure MyDllCall; 
  end;

procedure Register;

implementation

function MyDll: Longint; stdcall; external 'MyDllName.dll' name 'MyFunction'

procedure TMyComponent.MyDllCall;
var
  res: LongInt;
begin
  res:= MyDll;
end;

...

procedure Register;
begin 
 RegisterComponents('My Tab', [TMyComponent]); 
end;

end.

I have 2 questions:

  1. When I install the component on the IDE it searches for the physical DLL and gives an error if it's not found in path. I'd like the component to look for it when it's going to be effectively used at runtime.
  2. Is it possible to have the dll library file name to be set at runtime? i.e: 'MyDllName.dll' could change to '10029.dll' or 'ajjdwawd.dll'

Note that I put DLL declaration in the implementation in order not to expose the function call to callers.

Thanks for answering.

like image 214
Marco Carboni Avatar asked Mar 13 '26 14:03

Marco Carboni


1 Answers

Your current code uses what is known as load-time linking. The dependency must be resolved when the module is loaded, otherwise it will fail to load. You need to use the alternative method, run-time linking.

In Delphi there are two ways to do that:

  • Use the Win32 directly by calling LoadLibrary, GetProcAddress and FreeLibrary.
  • Get the Delphi RTL to do that for you using the delayed keyword.

Both approaches are covered in more detail in the documentation:

  • http://docwiki.embarcadero.com/RADStudio/en/Libraries_and_Packages
  • http://docwiki.embarcadero.com/CodeExamples/en/DelayedLoading_(Delphi)
like image 65
David Heffernan Avatar answered Mar 16 '26 09:03

David Heffernan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!