Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to store polymorphic class in shared memory?

Suppose I have class Base and Derived : public Base. I have constructed a shared memory segment using boost::interprocess library. Is it possible to have code similar to this:

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

The problems I see here is for instance that the required space for a derived class of Base is unknown (so how much shmem to allocate?)

Q: how to pass objects via pointers between applications?

like image 708
Queequeg Avatar asked Oct 19 '12 07:10

Queequeg


1 Answers

Just read its documentation

In particular:

Virtuality forbidden

The virtual table pointer and the virtual table are in the address space of the process that constructs the object, so if we place a class with a virtual function or virtual base class, the virtual pointer placed in shared memory will be invalid for other processes and they will crash.

This problem is very difficult to solve, since each process needs a different virtual table pointer and the object that contains that pointer is shared across many processes. Even if we map the mapped region in the same address in every process, the virtual table can be in a different address in every process. To enable virtual functions for objects shared between processes, deep compiler changes are needed and virtual functions would suffer a performance hit. That's why Boost.Interprocess does not have any plan to support virtual function and virtual inheritance in mapped regions shared between processes.

like image 136
CashCow Avatar answered Oct 19 '22 18:10

CashCow