Avatar of 3mCanada
Flag for Canada

asked on 

Locate a c++ class with virtual functions in a memory file for sharing between processes?

I have a C++ application that shares data with other applications that utilize the same classes, sharing via a memory mapped file.
Each class has a matching data structure defined which contains all the variables required by the class.
Each class instance has a matching data structure instance permanently located in the memory file.
Each class has only 1 member variable, a pointer to it's matching data structure.

The first process that starts is responsible for creating the memory file and initializing all class instances' data structures therein.  The layout of the memory file then remains constant, and the data within remains active, indefinitely.

In this manner different processes can start and stop and have instant access to the various class instances' data.

This approach works, but is ugly in a number of ways.

A less ugly solution might be to locate the class instances directly in the memory file, using placement-new &/or simple pointer assignment (depending on whether it is appropriate for the constructor to be called).  Is there any reason this would not work for non-virtual classes?

Classes with virtual functions are problematic, in that I need the data members shared, while the virtual function table pointer is specific to the process.

I'm guessing the value of the V-table pointer of the class instance would get assigned when (placement)new is called.  Is that correct?

One possibility, assuming I've guaranteed only 1 process has access at a time, might be to have each process call (placement)new for each class instance, each time it takes access, thereby initializing it's V-table pointer.  Excepting initial creation, the constructor used would be empty.  
Is this a viable approach?
Does new do any default initialization of member variables?

Do any other work arounds come to mind?

Should I stick with what I have?

Thank you,

-Currently using Visual Studio 2005.
-The data exists only within 1 session of 1 machine, so cross OS/compiler compatibility is not an issue.
-None of the classes use virtual inheritance.

Avatar of undefined
Last Comment

8/22/2022 - Mon