0

我正在尝试确认我已经在实践中工作的东西背后的理论。完整的设置有点扭曲,因为功能在不同的 dll 之间分割,但我将尝试描述这种情况:

class __declspec( dllexport ) BaseClass
/** This class' definition is available to everything,
 *  via .h file, .dll and .lib. */
{
    protected:
        std::string name;

    public:
        std::string GetName();
        /** This is implemented in BaseClass, and just returns this->name. */
}

class DerivedClass: public BaseClass
/** This class is created within the executable, but is not 'visible' to other
 *  dlls - either through .h files, .lib, or anything else. */
{
    public:
        DerivedClass();
        /** This sets this->name based on its own propertied. */
}

这种向上转换有效,但它需要完全访问 DerivedClass 的定义:

void* pointer;
DerivedClass* derived_pointer = reinterpret_class<DerivedClass*>(pointer);
BaseClass* base_pointer = dynamic_cast<BaseClass*>(derived_pointer);
base_pointer->GetName();

但是,以下内容不起作用:

void* pointer;
BaseClass* base_pointer = reinterpret_class<BaseClass*>(pointer);
base_pointer->GetName();

为了解决这个问题,我实现了一个接口:

class __declspec( dllexport ) IBaseClass
/** Fully virtual 'interface' class, in same file as BaseClass. */
{
    public:
        virtual std::string GetName() = 0;
}

class __declspec( dllexport ) BaseClass: public IBaseClass
/** This class' definition is available to
 *  everything, via .h file, .dll and .lib. */
{
    protected:
        std::string name;

    public:
        std::string GetName();
        /** This is implemented in BaseClass, and just returns this->name. */
}

class DerivedClass: public BaseClass
/** This class is created within the executable, but is not 'visible'
 *  to other dlls - either through .h files, .lib, or anything else. */
{
    public:
        DerivedClass();
        /** This sets this->name based on its own propertied. */
}

现在下面的代码确实有效:

void* pointer;
IBaseClass* ibase_pointer = reinterpret_class<IBaseClass*>(pointer);
ibase_pointer->GetName();

我有一些模糊的记忆,有人告诉我强制转换为完全虚拟的类是一种特殊情况 - 但我不记得为什么,或者在网上找到任何关于它的信息。

请帮助我 - 为什么我的代码有效?!

4

1 回答 1

1

这完全依赖于类布局,它是实现定义的,不能依赖。特别是对于 MSVC,类布局的一个很好的介绍是http://www.openrce.org/articles/full_view/23并且值得知道您可以要求带有/d1reportSingleClassLayout标志的类布局。

在您的情况下,由于第一个BaseClass没有虚拟成员,它将被放置在内部DerivedClass未指定的位置。我猜这DerivedClass有一些虚拟成员,否则我希望BaseClass在开始DerivedClass和开始reinterpret_cast工作。如果它有虚拟成员,您将拥有:

+--------------------+
|DerivedClass vtable |
|BaseClass::name     |
|DerivedClass members|

通过添加接口 IBaseClass 没有任何改变;DerivedClass 仍然布局为:

+--------------------+
|DerivedClass vtable |
|BaseClass::name     |
|DerivedClass members|

但是DerivedClassvtable 以 vtable 开头IBaseClass

+---------------------+
|IBaseClass::GetName  |
|DerivedClass virtuals|

所以通过DerivedClassvtable 调用是有效的。

于 2012-07-12T15:52:50.767 回答