是否可以在共享内存中存储多态类?

时间:2012-10-19 07:29:44

标签: c++ boost shared-memory boost-interprocess

假设我有课程BaseDerived : public Base。 我使用boost :: interprocess库构建了一个共享内存段。是否可以使用与此类似的代码:

Base* b = new Derived(); 
write(b); //one app writes
Base* b2 = read(b); //second app reads
//b equals b2 (bitwise, not the ptr location)

我在这里看到的问题是,派生的Base类所需的空间是未知的(所以要分配多少shmem?)

Q :如何通过应用程序之间的指针传递对象?

5 个答案:

答案 0 :(得分:12)

请阅读documentation

特别是:

  

虚拟禁止

     

虚拟表指针和虚拟表位于地址中   构造对象的进程的空间,所以如果我们放置一个   具有虚函数或虚基类的类,虚拟   放在共享内存中的指针对其他进程无效   他们会崩溃

     

这个问题很难解决,因为每个过程都需要一个   不同的虚拟表指针和包含它的对象   指针在许多进程中共享。即使我们映射映射   在每个进程中相同地址的区域,虚拟表都可以   在每个过程中的不同地址。启用虚拟功能   对于进程之间共享的对象,需要进行深度编译器更改   和虚拟功能将受到性能影响。这就是原因   Boost.Interprocess没有任何支持虚函数的计划   和进程之间共享的映射区域中的虚拟继承。

答案 1 :(得分:4)

共享内存最初只允许POD结构(内心,它们可能有构造函数/ copy / etc ......)。

Boost.Interprocess通过在偏移顶部模拟指向共享内存段的指针语义来提高标准。

但是,虚拟指针不是指向纯数据的指针,它是指向代码段的指针,这就是事情变得复杂的地方,因为代码段不一定映射到同一个地址处理到另一个(即使它们是从相同的二进制文件启动)。

所以......不,虚拟指针 - 多态对象不能存储在共享内存中。


然而,仅仅因为许多C ++实现选择使用虚拟指针机制并不意味着这是具有多态行为的唯一方法。例如,在LLVM和Clang中,他们在封闭的层次结构上构建,以获得没有虚拟指针(和RTTI)的多态性,从而降低内存需求。这些对象可以有效地存储在共享内存中。

那么,如何让多态与共享内存兼容:我们需要 not 来存储指向表/函数的指针,但是我们可以存储索引

这个想法的例子,但可能会被改进。

/// In header
#include <cassert>

#include <vector>

template <class, size_t> class BaseT;

class Base {
    template <class, size_t> friend class BaseT;
public:

    int get() const; //     -> Implement: 'int getImpl() const' in Derived

    void set(int i); // = 0 -> Implement: 'void setImpl(int i)' in Derived

private:
    struct VTable {
        typedef int (*Getter)(void const*);
        typedef void (*Setter)(void*, int);

        VTable(): _get(0), _set(0) {}

        Getter _get;
        Setter _set;
    };

    static std::vector<VTable>& VT(); // defined in .cpp

    explicit Base(size_t v): _v(v) {}

    size_t _v;
}; // class Base

template <class Derived, size_t Index>
class BaseT: public Base {
public:
    BaseT(): Base(Index) {
        static bool const _ = Register();
        (void)_;
    }

    // Provide default implementation of getImpl
    int getImpl() const { return 0; }

    // No default implementation setImpl

private:
    static int Get(void const* b) {
        Derived const* d = static_cast<Derived const*>(b);
        return d->getImpl();
    }

    static void Set(void* b, int i) {
        Derived* d = static_cast<Derived*>(b);
        d->setImpl(i);
    }

    static bool Register() {
        typedef Base::VTable VTable;

        std::vector<VTable>& vt = Base::VT();

        if (vt.size() <= Index) {
            vt.insert(vt.end(), Index - vt.size() + 1, VTable());
        } else {
            assert(vt[Index]._get == 0 && "Already registered VTable!");
        }

        vt[Index]._get = &Get;
        vt[Index]._set = &Set;
    }
}; // class BaseT

/// In source
std::vector<VTable>& Base::VT() {
    static std::vector<VTable> V;
    return V;
} // Base::VT

int Base::get() const {
    return VT()[_v]._get(this);
} // Base::get

void Base::set(int i) {
    return VT()[_v]._set(this, i);
} // Base::set

好的......我猜你现在感谢编译器的神奇......

关于用法,幸运的是更简单:

/// Another header
#include <Base.h>

// 4 must be unique within the hierarchy
class Derived: public BaseT<Derived, 4> {
     template <class, size_t> friend class BaseT;
public:
    Derived(): _i(0) {}

private:
    int getImpl() const { return _i; }

    void setImpl(int i) { _i = i; }

    int _i;
}; // class Derived

ideone的行动。

答案 2 :(得分:3)

我相信你正在研究对象的序列化。看看http://www.boost.org/doc/libs/1_51_0/libs/serialization/doc/index.html

您可以采取的一些方法是: 1.序列化你的C ++类 2.将数据发送到另一个应用程序 3.反序列化为C ++类。

答案 3 :(得分:-1)

//From the example above , I have removed VTable 
// I also removed static variables as per boost::interprocess 
// static variable don't work with shared memory, and also I did not see
// any advantage in actually builting a VTable for all derived classes
#include <vector>
#include <boost/bind.hpp>
#include <boost/function.hpp>

template <class> class BaseT;

class Base {
    template <class> friend class BaseT;
    boost::function< int (void) > _get;
    boost::function< void (int) > _set;
public:

    int get() {
        return _get();
    } //     -> Implement: 'int get() ' in Derived

    void set(int i) {
        _set(i);
    } // = 0 -> Implement: 'void set(int i)' in Derived
}; // class Base

template <class Derived>
class BaseT : public Base {

public:
    BaseT() : Base(), impl(static_cast<Derived *> (this)) {
        Base::_get = boost::bind(&BaseT<Derived>::get, this);
        Base::_set = boost::bind(&BaseT<Derived>::set, this, _1);
    }

    int get() {
        return impl->get();
    }

    void set(int i) {
        impl->set(i);
    }

private:
    Derived * impl;
};


//some A  implementation of Base
struct A : BaseT<A> {

    int get() {
        return 101; //testing implementation
    }

    void set(int i) {
        ; //implementation goes here
    }
};

//some B  implementation of Base
struct B : BaseT<B> {

    int get() {
        return 102; //testing implementation 
    }

    void set(int i) {
        ; //implementation goes here
    }
};

int main() {
    BaseT<A> objectA;
    BaseT<B> objectB;
    Base *a = &objectA;
    Base *b = &objectB;
    std::cout << a->get() << " returned from A class , "
            << b->get() << " returned from B class " << std::endl;
    return 0;
}

答案 4 :(得分:-1)

//While redefining I changed semantics of constnance in getter, 
//and had non-    const Derived pointer used for both getter and setter. 
//But original simantics can be preserved as following:

    int get() const {
         //return impl->get();
        //this enforces that get has to be const
        static_cast<const Derived *> (this)->get() ;
    }
相关问题