动态加载exe文件 [英] Dynamically loading exe file
问题描述
我正在尝试从我的程序动态加载一个exe文件,并从动态加载的exe运行SomeProcedure。这是我正在加载的exe - library.exe
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;
这是我的exe,加载的library.exe,并尝试运行SomeProcedure从它。
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;
不幸的是它不工作 - AHandle有一个地址,但GetProcAddress总是返回nil。我做错了什么?
Unfortunately it's not working - AHandle has an address but GetProcAddress always returns nil. What am I doing wrong?
推荐答案
据我所知,你所尝试的是不可能的。您不能使用LoadLibrary加载.exe文件,然后调用其导出的函数。您只能将一个.exe文件加载到进程中。您需要将功能移动到库,或COM服务器或其他解决方案。
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.
正如Sertac指出的那样,文档覆盖:
As Sertac points out, the documentation does cover this:
LoadLibrary也可用于加载其他可执行模块。例如,该函数可以指定.exe文件
以获取可用于FindResource或LoadResource的句柄。但是,不要使用LoadLibrary来运行.exe文件。而是使用CreateProcess函数。
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.
您可以使用GetProcAddress与可执行文件的模块句柄。但是您必须通过调用GetModuleHandle(0)来获取模块句柄。例如,
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.
这篇关于动态加载exe文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!