static void Main(string[] args) { SafeFileMappingHandle hMapFile = null; IntPtr pView = IntPtr.Zero; try { // Create the file mapping object. hMapFile = NativeMethod.CreateFileMapping( INVALID_HANDLE_VALUE, // Use paging file - shared memory IntPtr.Zero, // Default security attributes FileProtection.PAGE_READWRITE, // Allow read and write access 0, // High-order DWORD of file mapping max size MapSize, // Low-order DWORD of file mapping max size FullMapName // Name of the file mapping object ); if (hMapFile.IsInvalid) { throw new Win32Exception(); } Console.WriteLine("The file mapping ({0}) is created", FullMapName); // Map a view of the file mapping into the address space of the // current process. pView = NativeMethod.MapViewOfFile( hMapFile, // Handle of the map object FileMapAccess.FILE_MAP_ALL_ACCESS, // Read and write access 0, // High-order DWORD of file offset ViewOffset, // Low-order DWORD of file offset ViewSize // Byte# to map to the view ); if (pView == IntPtr.Zero) { throw new Win32Exception(); } Console.WriteLine("The file view is mapped"); // Prepare a message to be written to the view. Append '\0' to // mark the end of the string when it is marshaled to the native // memory. byte[] bMessage = Encoding.Unicode.GetBytes(Message + '\0'); // Write the message to the view. Marshal.Copy(bMessage, 0, pView, bMessage.Length); Console.WriteLine("This message is written to the view:\n\"{0}\"", Message); // Wait to clean up resources and stop the process. Console.Write("Press ENTER to clean up resources and quit"); Console.ReadLine(); } catch (Exception ex) { Console.WriteLine("The process throws the error: {0}", ex.Message); } finally { if (hMapFile != null) { if (pView != IntPtr.Zero) { // Unmap the file view. NativeMethod.UnmapViewOfFile(pView); pView = IntPtr.Zero; } // Close the file mapping object. hMapFile.Close(); hMapFile = null; } } }