views:

474

answers:

4

I have written a C++ class that I need to share an instance of between at least two windows processes. What are the various ways to do this?

Initially I looked into #pragma data_seg only to be disappointed when I realised that it will not work on classes or with anything that allocates on the heap.

The instance of the class must be accessible via a dll because existing, complete applications already use this dll.

+4  A: 

You can potentially use memory-mapped files to share data between processes. If you need to call functions on your object, you'd have to use COM or something similar, or you'd have to implement your own RPC protocol.

Anton Gogolev
A: 

Is it a POD or do you need to be able to share a single instance across processes? Have you considered using the Singleton pattern (static initialization version, for thread safety reasons)? You will need to use Mutexes as well to protect concurrent writes and stuff.

On Windows, you can use COM as well.

dirkgently
+2  A: 

Look into Boost::interprocess. It takes a bit of getting used to, but it works very well. I've made relatively complex data structures in shared memory that worked fine between processes.

edit: it works with memory-mapped files too. The point is you can use data in a structured way; you don't have to treat the memory blocks (in files or shared memory) as just raw data that you have to carefully read/write to leave in a valid state. Boost::interprocess takes care of that part and you can use STL containers like trees, lists, etc.

Jason S
A: 

You can use placement new to create the object in a shared memory zone. As long as the object doesn't use any pointers, that sould be fine.

Marc