Tech Support > Microsoft Windows > Development Resources > Pointers and shared memory
Pointers and shared memory
Posted by Inca on February 15th, 2005


I want multiple instances of a library to use the exact same memory.
I have placed an object in shared memory using Winapi functions
CreateFileMapping and MapViewOfFile.
This works fine, however, inside this object is a pointer to another object
(of which I cannot change the source code) and this doens't work.

I found two problems:

First, an object created inside the shared object will be put in the local
address space and not in the 'shared space' so the inner object is destroyed
when the first instance is closed. This could be overcome for one level
deep, but I don't know how many levels I need to check since the inner
object and all its functions are from another lib.

Second, the pointer will not be correct for the second instance.

Does anyone know how I can share the full object *including* all its
descendants?
--
Inca


Posted by Scott McPhillips [MVP] on February 15th, 2005


Inca wrote:

You cannot share an object that contains pointers in shared memory. You
must convert the object into a sharable representation consisting of
plain old data types. This could be quite similar to serializing the
object to a file. Another possibility is to convert the object to one
that uses a custom memory allocator with __based pointers.

--
Scott McPhillips [VC++ MVP]


Posted by Severian on February 16th, 2005


On Tue, 15 Feb 2005 20:44:17 +0100, "Inca"
<shadow*movements@wanadoo.invalid> wrote:

I would recommend not storing direct addresses; use offsets from the
beginning of mapped memory. The day you add a DLL to your project
which overlaps your address (or start a thread that creates a stack
there, or any number of things), you'll be in trouble.

Sounds like you need to create your own memory manager for objects in
the shared memory. Like my first comment, these should use offsets or
self-relative queues.

Yep.

If this library is a DLL, you could also create a shared data section,
but storing your object there would still not help if the DLLs are
loaded at different addresses in different processes, unless you
create a custom memory allocator as above (either within the shared
data section, or within mapped shared memory.)

Most of these options are relatively simple in C, but if you're
dealing with C++ objects, they may be quite a bit more complex.

--
Sev


Similar Posts