views:

302

answers:

2

Maybe this cannot be done, but please help or suggest how this can be achieved without writing something to disk.

Lets suppose there are two string values that I want to share between two independent applications.

You are welcome to provide code sample in any programming language.

+5  A: 

What you probably want to do is create a memory-mapped file. You can create a memory-mapped file that doesn't have any backing store on disk, but is instead backed by the system page file. Have a look at the documentation for CreateFileMapping, in particular when the first parameter is INVALID_HANDLE_VALUE.

You can give such a file mapping a unique system-wide name, and then other applications can open it using OpenFileMapping and providing the same name.

Once you have such a block of shared memory, you can put any information you like into it. Note that since the memory is shared across processes, you don't want to store any pointers into the block of memory (which precludes doing things like storing a std::string there).

Greg Hewgill
+3  A: 

The recommended approach is to create a named memory mapping (CreateFileMapping, probably with INVALID_HANDLE_VALUE as first parameter since you don't need an actual file) and put your shared data in the mapping. You'll also need a named mutex to synchronize access to this data.

A lazy approach is to use #pragma data_seg (for MSVC; other compilers have similar tools) to put your data in a shared section. Please note that MSVC requires data to be explicitly initialized; otherwise, it will go to the regular data section without even a warning.

The disadvantage of the second approach is that security is not applied here, so any user (even across sessions) will have access to the shared section. Another issue is that only instances of the same executable file (or DLL) will share the section; i.e., if you copy an .exe and run it from two different locations, the data will not be shared.

atzz
+1 for the explicit initialization warning. I've been bitten by that several times.
gooli