我有以下类层次结构:
class IStorage {
[...]
}
Q_DECLARE_INTERFACE(IStorage, "ch.gorrion.smssender.IStorage/1.0")
class ISQLiteStorage: public IStorage {
Q_INTERFACES(IStorage)
[...]
}
Q_DECLARE_INTERFACE(ISQLiteStorage, "ch.gorrion.smssender.ISQLiteStorage/1.0")
class DASQLiteStorage: public QObject, public ISQLiteStorage {
Q_OBJECT
Q_INTERFACES(ISQLiteStorage)
[...]
}
我正在使用 QT 并尝试使用 QtPlugin 创建一个插件(为我的应用程序)。我正在创建一个 DASQLiteStorage 的实例,并将这个实例提供给插件内部的一个对象:
// the next line is within my main app.
// storage is the DASQLiteStorage instance.
// gateway is an object from within the plugin.
gateway->setDefaultStorage(storage);
// this method lies within the plugin
void AbstractGateway::setDefaultStorage(IStorage* storage) {
defaultStorage_ = dynamic_cast<ISQLiteStorage*>(storage);
}
问题是,dynamic_cast 向我返回了一个空指针(不是预期的),而在我的主应用程序中执行 dynamic_cast(即在“gateway->setDefaultStorage(storage);”之前)给了我有效的指针(预期的)。
有谁知道为什么会发生这种情况?程序是否在与插件不同的内存范围内运行?这会导致这样的问题吗?任何想法如何解决这一问题?
非常感谢!
编辑:我尝试了一些建议:
// this method lies within the plugin
void AbstractGateway::setDefaultStorage(IStorage* storage) {
ISQLiteStorage* s = dynamic_cast<ISQLiteStorage*>(storage);
s = static_cast<ISQLiteStorage*>(storage);
s = qobject_cast<ISQLiteStorage*>((QObject*)storage);
defaultStorage_ = s;
}
在方法的第一行中,s 等于 NULL,在第二行中 s 包含正确的指针,在第三行中是另一个指针。为什么这些指针不相等?
为什么尽管我现在正在使用 dynamic_cast 仍然无法工作:
pluginLoader()->setLoadHints(QLibrary::ResolveAllSymbolsHint | QLibrary::ExportExternalSymbolsHint);
EDIT2:我注意到,我在代码中得到的分段错误也与此有关。我有以下构造:
// The following classes are defined within the main app.
class ILoginAccount: public IAccount [...]
class AbstractAccountStroageOfficer {
public:
AbstractAccountStroageOfficer(IAccount* account)[...]
}
// These classes are defined within my plugin and are created from within the plugin.
class BCAccount: public ILoginAccount {
public:
BCAccount()
: ILoginAccount(new DAAccountStorageOfficer(this))
{};
}
class DAAccountStorageOfficer: public AbstractAccountStorageOfficer {
public:
DAAccountStorageOfficer(ILoginAccount* account)
: AbstractAccountStorageOfficer(account) // This line raises a segfault.
{
IAccount* a = account; // This line raises a segfault as well.
a = dynamic_cast<IAccount*>(account); // This as well.
a = static_cast<IAccount*>(account); // This as well.
}
}
这些分段错误不应该发生,不是吗?但他们为什么要这样做?