I have a Qt-based project that loads plugins via QPluginLoader.
These plugins inherit class Plugin from this project.
Plugin.h
#ifndef PLUGIN_H
#define PLUGIN_H
class Plugin:public QObject
{
public:
inline static MyObj* obj;
};
Q_DECLARE_INTERFACE(Plugin,Plugin_iid)
#endif
I need to be able to access static pointer 'obj' from all plugins, which is initialized before any plugins are loaded.
The problem is that if I try to access the pointer from a plugin, it is not initialized, so it doesn't really behave like a static member. It behaves normally from within the main project.
What needs to be done to make this work?
Edit:
If I remove the 'inline' keyword and create a Plugin.cpp file:
Plugin.cpp
#include "Plugin.h"
MyObj* Plugin::obj;
.. then the plugin won't even load anymore, complaining the obj is an undefined symbol.
Edit II:
Accessing the variable from a plugin happens like so:
TestPlugin.h
#ifndef TESTPLUGIN_H
#define TESTPLUGIN_H
#include "/path/to/Plugin.h"
class TestPlugin:public Plugin
{
Q_OBJECT
Q_PLUGIN_METADATA(IID "TestPlugin" FILE "metadata.json")
Q_INTERFACES(Plugin)
public:
TestPlugin();
};
TestPlugin.cpp
#include "TestPlugin.h"
TestPlugin::TestPlugin()
{
qDebug() << obj; // obj is uninitialized here
}
Edit III:
To put any and all discussion to rest whether obj is initialized;
here's how it's done:
#include "Plugin.h"
#include "MyObj.h"
MainProject::MainProject()
{
...
Plugin::obj=new MyObj();
qDebug() << Plugin::obj; // there, initialized successfully
...
loadPlugins();
...
}