I'm trying to dynamically load an exe file from my program and run SomeProcedure from that dynamicaly loaded exe. Here's what I'm doing in loaded exe - library.exe
interface
procedure SomeProcedure; stdcall;
implementation
procedure SomeProcedure;
begin
ShowMessage('Ala has a cat');
end;
And here's my exe that load's library.exe and try to run SomeProcedure from it.
type
THandle = Integer;
TProc = procedure();
var
AHandle: THandle;
Proc: TProc;
procedure TForm1.Button1Click(Sender: TObject);
begin
AHandle := LoadLibrary('library.exe');
if AHandle <> 0 then begin
@Proc := GetProcAddress(AHandle, 'SomeProcedure');
if @Proc <> nil then
try
Proc;
finally
FreeLibrary(AHandle);
end;
end;
end;
end;
Unfortunately it's not working - AHandle has an address but GetProcAddress always returns nil. What am I doing wrong?
To the very best of my knowledge, what you are attempting is not possible. You cannot use LoadLibrary to load a .exe file, and then call its exported functions. You can only have one .exe file loaded into a process. You'll need to move the functionality into a library, or a COM server, or some other solution.
As Sertac points out, the documentation does cover this:
LoadLibrary can also be used to load other executable modules. For example, the function can specify an .exe file to get a handle that can be used in FindResource or LoadResource. However, do not use LoadLibrary to run an .exe file. Instead, use the CreateProcess function.
You can use GetProcAddress with the module handle of an executable. But you have to obtain the module handle by calling GetModuleHandle(0), for example.