Question

I have next situation:

  1. Static library with class A; (logger)
  2. Main application which creates class A instance as singleton
  3. Different delay loaded dynamic libraries (plugins) that links with (1.) and need to use instance of class A.

How should I share singleton from main application (2.) between plugins (3.)? Are there any features in Qt / C++ to do this?

Currently I'm using ugly solution based on shared memory and I don't think that it is right.

I'm thinking about refactoring with using of dependency injection pattern but it imposes some restrictions.

SAMPLE:

Static library "log.lib":

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

Main application "app.exe":

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

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

Plugin 1 "plg1.dll"

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

Plugin 2 "plg2.dll"

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

La solution

Right, so in order:

  • You seem not to use the singleton pattern for singleton use cases.
  • Your original question is not much related to Qt.
  • This has little to nothing to do with the distinction of static library or not.
  • You could make the plugin interface accept a logger mutator so that you could then set that with the instance from the application.

I would personally just use the singleton pattern properly, and the plugin could also query the very instance. Please take a look at the following Qt macro:

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.

You could easily build the singleton pattern on top of it, and actually this would be even thread-safe.

Here you can find another example not using Q_GLOBAL_STATIC, but QObject inheritance and facilitates the job with QCoreApplication that we implemented in our project.

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

This version above is also-thread safe.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top