gpt4 book ai didi

c++ - 在动态库之间共享来自静态库的数据

转载 作者:太空宇宙 更新时间:2023-11-04 11:42:19 25 4
gpt4 key购买 nike

我有下一个情况:

  1. A 类 的静态库; (记录器)
  2. A 类 实例创建为单例的主应用程序
  3. 与(1.) 链接并需要使用A 类 实例的不同延迟加载动态库(插件)。

我应该如何在插件 (3.) 之间共享来自主应用程序 (2.) 的单例? Qt/C++ 中是否有任何功能可以做到这一点?

目前我正在使用基于共享内存的丑陋解决方案,我认为这是不对的。

我正在考虑使用依赖注入(inject)模式进行重构,但它施加了一些限制。

示例:

静态库“log.lib”:

struct Log
{
void write( QString text );
};

主应用程序“app.exe”:

Log *logger = new Log; // I need only one logger for all application 

int main()
{
logger->write( "Main" );
...
}

插件 1 "plg1.dll"

extern Log *logger; // Logger from "app.exe"
void Foo()
{
logger->write( "Foo" );
}

插件 2“plg2.dll”

extern Log *logger; // Logger from "app.exe"
void Bar()
{
logger->write( "Bar" );
}

最佳答案

对,所以顺序是:

  • 你似乎没有使用 singleton pattern用于单例用例。
  • 您原来的问题与 Qt 关系不大。
  • 这与静态库与否无关。
  • 您可以让插件接口(interface)接受一个记录器修改器,这样您就可以使用应用程序中的实例进行设置。

我个人会正确使用单例模式,插件也可以查询实例。请看一下下面的 Qt 宏:

Q_GLOBAL_STATIC( Type, VariableName)

Creates a global and static object of type QGlobalStatic, of name VariableName and that behaves as a pointer to Type. The object created by Q_GLOBAL_STATIC initializes itself on the first use, which means that it will not increase the application or the library's load time. Additionally, the object is initialized in a thread-safe manner on all platforms.

您可以轻松地在其之上构建单例模式,实际上这甚至是线程安全的。

在这里您可以找到另一个不使用 Q_GLOBAL_STATIC 的示例,而是使用 QObject 继承,并使用我们在项目中实现的 QCoreApplication 来简化工作。

https://projects.kde.org/projects/playground/games/gluon/repository/revisions/master/entry/core/singleton.h

上面的这个版本也是线程安全的。

关于c++ - 在动态库之间共享来自静态库的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20919883/

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