如何动态加载和调用BPL包中的函数 [英] How to dynamically load and call a function in a BPL package

查看:181
本文介绍了如何动态加载和调用BPL包中的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这似乎很简单,但是下面的代码不起作用。

It seems pretty straightforward but the code below doesn't work.

BPL:

procedure DoSomething();
begin
  LogEvent('Did');
end;

exports
  DoSomething;

主要EXE:

procedure CallModuleFunc;
var
  H: THandle;
  P: procedure();
begin
  H := LoadPackage('mymod.bpl');
  try
    if (H <> 0) then
    begin
      @P := GetProcAddress(H, 'DoSomething');
      if Assigned(P) then
        P();
    end;
  finally
    UnloadPackage(H);
  end;
end;

现在没有错误,bpl使用 LoadPackage()成功加载code>,但 GetProcAddress()返回nil。为什么?可能是因为名字改头换面。我试过添加 stdcall (导出函数和 P 的声明),但是并没有解决问题。我在网上看到了数百个示例,这些示例应该可以通过这种方式工作。我什至尝试了 GetProcAddress(H,‘DoSomething $ qqsv’),但是它也不起作用。我在这里错过了什么?

Now there's no error, the bpl loads successfully with LoadPackage() but GetProcAddress() returns nil. Why? probably because name mangling. I've tried adding stdcall (both exported function and P's declaration) but that didn't solve the problem. I've seen hundreds of examples on the web that it's supposed to be working this way. I even tried GetProcAddress(H, 'DoSomething$qqsv') but it didn't work either. What am I missing here?

推荐答案

经过数小时的搜索,反复试验和错误,我意识到这一定是我要做的事情或做了不同的事情。问题是我的第一个版本mymod.bpl放入了Delphi的默认BPL输出目录(根本没有导出,也没有DoSomething())。然后,我将BPL输出目录更改为项目的根源目录,以便可以在一处看到源和bpl模块。该exe文件没有像以前在Delphi 7中那样放到源代码所在的位置,而是在Debug或Release文件夹下。误导我的是,当LoadPackage()在exe的当前目录(即Debug / Release)中找不到模块时,它将查看Delphi的默认包文件夹(该文件夹具有bpl的第一个和错误的版本)并加载它,所以没有错误,但也没有DoSomething(),因为它不再由模块的编译更新。

After hours of searches and trial and errors, I realized it had to be about something I do or did differently. The problem was that my very first version of mymod.bpl was put into Delphi's default BPL output directory (which had no export, no DoSomething() at all). Then, I had changed the BPL output directory to my project's root source directory, so that I could see the sources and the bpl modules in one place. The exe was not put into where the sources reside as it used to be in Delphi 7, it was under Debug or Release folders. What misdirecting me was that when LoadPackage() cannot find the module in exe's current dir (which was Debug/Release) it looks at Delphi's default package folder (which had the very first and wrong version of the bpl) and loads it, so no error there but also no DoSomething() because it was no longer updated by my module's compile.

我希望这种解释能帮助其他可能遇到类似问题的人弄清楚。感谢所有抽出时间阅读并撰写评论的人。

I hope this explanation helps someone else who might have a similar issue to figure things out. Thanks to everyone who spared time to read this and written comments.

这篇关于如何动态加载和调用BPL包中的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆