Memory Management

Ordinarily under Win32, it is not possible to share the block of memory
by passing the address or global handles from one process to another. Both of these
methods for sharing data work in Windows 3.x because all processes run in the same address
space, but fail under Win32 because each process has its own address space.
Memory-mapped files is the best technique for sharing memory between applications (or
shared data in a DLL covered later).
Some window messages specify the address of a block of memory in their iParam
parameter. For example, the WM_SETTEXT message uses the lParam as a pointer to a string that identifies the new
text for the window. If you send this message to a window in another process it will work
even if the address you specify refers to private memory in your address space.
This is because Win32 traps the sending of WM SETTEXT messages and repackages the
contents of the text into a block of memory to be shared with the other process. Special
processing like this has to be performed for any inter-process message whose parameters
represent a pointer. What about user defined messages like (WM_USER + i) that the system doesnt know about?
If you want to send a message which passes an address use the WM_COPYDATA message which
takes a pointer to a COPYDATASTRUCT structure. It specifies the private address of the
memory you want to share, the size of the memory and a 32-bit user-defined value which
could be used to indicate the content of the data you are sending.
Similarly to the way it deals with WM_SETTEXT, Win32 traps the sending of a WM_COPYDATA
message and repackages the contents of the memory into a block of memory to be shared with
the other process.
You must send a WM_COPYDATA message because the system must free the copied memory
after the receiving window procedure has processed the message. If you post the message,
the system doesnt know when the WM_COPYDATA message is processed.
It takes some time for the system to repackage the data into the other processs
address space which means that other thread running in the sending application process
must not modifies the contents of the memory block during the period until the SendMessage() returns.
The receiving application must make a copy of the shared memory it is given during the
processing of the WM_COPYDATA message. This is because the system deletes the memory after
the message is processed. |