dynamic_cast返回NULL但不应该返回NULL

时间:2009-12-27 00:21:15

标签: c++ qt plugins dynamic-cast

我有以下类层次结构:

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实例,我将此实例提供给插件中的FROM FROM对象:

// 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-&gt; 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,在第二行中包含正确的指针,在第三行中包含另一个指针。为什么这些指针不相等? 尽管我现在正在使用,为什么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.
    }
}

这些细分错误不应该发生,如果它们?但为什么呢?

1 个答案:

答案 0 :(得分:4)

基本上,RTTI在模块边界上是不可靠的。不同的编译器在这里有不同的行为;你必须研究你的编译器/版本在这种情况下的作用。当然,如果你有一个不同的主应用程序和插件的编译器/版本,它显然没有机会工作。

使用static_cast作为解决方法。

相关问题