【问题标题】:Calling main program functions from a dynamically loaded library (QPluginLoader)从动态加载的库(QPluginLoader)调用主程序函数
【发布时间】:2015-08-07 02:05:05
【问题描述】:

我正在使用 Qt QPluginLoader 类在运行时动态加载插件 (DLL)。

到目前为止,我已经成功加载了带有从主程序调用的函数的插件。现在,插件将需要调用主程序中的其他函数。我已经在插件项目中包含了相关的头文件,它编译没有错误。

当我尝试从主程序调用以下插件函数时:

// main program calling a function in a dll that has been dynamically
// loaded into the program:
PluginInterface* plugin = qobject_cast<PluginInterface*>(QPluginLoader(path)).instance();
plugin->DoSomething(); // works, writes a message to the console
plugin->callMainProgramFunction(); // not working

'

// test method in the plugin project (dll) that writes to console:
void TestDLL::DoSomething();
{
   std::cout << "Hello, this messages comes from TestDLL! Have a nice day"; // works
}

'

// test method in the plugin project (dll) that tries to 
// call a method in the main program: 
void TestDLL::callMainProgramFunction()
{  
    Angle test; // angle.h is included, and offers geometric functions
    std::cout << test.sine() << "\n"; // does not work, program stops
}

程序停止。我相信这是因为插件不知道在哪里可以找到符号(来自 angle.cpp 的代码被链接并编译到主程序中),因为它是在之后动态链接到程序中的。

许多插件将使用相同的功能,因此我认为用所有实现编译每个插件是个坏主意。

有没有解决方案,使用 QPluginLoader?如何告诉动态加载的插件在主程序中的哪里可以找到符号?我知道 QLibrary 提供了一种更手动的导出/导入函数和“解析符号”的方式,但缺少 QPluginLoader 的简洁实例功能。

【问题讨论】:

    标签: c++ qt dllimport symbols


    【解决方案1】:

    您可以创建一个在插件和主程序之间共享的具有常用功能的dll,并将其链接到主程序和插件中。

    【讨论】:

    • 您能详细说明一下吗?你的意思是我应该创建一个加载到主程序和插件中的 common-functions-dll 吗?或者你的意思是所有的常用功能都应该放在 dll 中,以便两者都可以访问它们?有许多插件将使用相同的功能。感谢您的回复。
    • 你知道一个dll可以在内存中加载一次并在不同进程之间共享,因此它可以在单个进程的不同“组件”之间共享。因此,在您的情况下,您的应用程序 mainapp.exe 具有 commfunc.dll 的依赖项,您的 plugin.dll 也是如此。 mainapp.exe 启动时,会在内存中加载 commfunc.dll,所以它的所有函数都可以从 plugin.dll 中使用,因为它们的地址现在可以访问了。如果需要的函数在mainapp.exe地址空间,这是无法实现的。
    【解决方案2】:

    QPluginLoader解决了我描述的问题:通过QPluginLoader动态加载到主程序中的库,将能够调用主程序中的函数。

    我的问题的原因是我使用的插件界面中的一个细微错误。

    【讨论】:

      【解决方案3】:

      这是可能的,但不要忘记在 Linux 上将主程序与 -rdynamic 标志链接,以便主程序的符号在插件中可见。

      【讨论】:

        猜你喜欢
        • 2021-10-18
        • 2018-06-04
        • 1970-01-01
        • 2011-07-28
        • 2020-07-22
        • 1970-01-01
        • 2013-01-03
        • 2012-12-29
        • 1970-01-01
        相关资源
        最近更新 更多