gpt4 book ai didi

windows - 动态加载exe文件

转载 作者:可可西里 更新时间:2023-11-01 14:45:05 26 4
gpt4 key购买 nike

我正在尝试从我的程序动态加载一个 exe 文件,并从该动态加载的 exe 运行 SomeProcedure。这是我在加载的 exe 中所做的 - library.exe

interface    

procedure SomeProcedure; stdcall;

implementation

procedure SomeProcedure;
begin
ShowMessage('Ala has a cat');
end;

这是我的 exe,它加载了 library.exe 并尝试从中运行 SomeProcedure。

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。我做错了什么?

最佳答案

据我所知,您的尝试是不可能的。您不能使用 LoadLibrary 加载 .exe 文件,然后调用其导出的函数。您只能将一个 .exe 文件加载到进程中。您需要将功能移动到库、COM 服务器或其他一些解决方案中。

正如 Sertac 指出的那样,documentation确实涵盖了这一点:

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) 来获取模块句柄,例如。

关于windows - 动态加载exe文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18218593/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com