Wednesday, March 16, 2011

.NET 4 has added support for programming with Memory-Mapped Files (MMF)


First of all, what is a memory-mapped file or MMF? MMF is a kernel object that maps a disk file to a region of memory address space as the committed physical storage. In plain English, MMF allows you to reserve a range of addresses and use a disk file as the physical storage for the reserved addresses. When a MMF is created, you access the disk file as if you were accessing memory. MMF makes accessing files extremely easy. For example, Windows loads EXEs or DLLs using MMF. As a matter of fact, MMF is a corner stone for almost all modern forms of inter-process communication (or IPC) with Windows programming. I felt inconvenient when early .NET Framework releases did not support MMF. The good news is that starting version 4, .NET Framework has built-in support for MMF!


Imagine you have got some modules or applications written in native C/C++ and you want to use them. The old modules use MMF to exchange data. Without MMF support in earlier .NET, you can do two things among others:


  • Platform Invoke Win32 MMF support. You need to handle lots of marshalling between managed and unmanaged worlds.

  • You can always use Windows debug symbol support, which allows to access variables as symbols. However, this mechanism is rather involving and beyond beginners' comfort level. You have to fiddle with marshalling as well.

With .NET Framework 4, you just write an MMF-enabled application to exchange data with old C/C++ applications directly. For programming details, read my article "Programming Memory-Mapped Files with the .NET Framework" on "www.CodeProject.com". This article will demonstrate how to write MMF-enabled .NET applications. I started from basic examples and then moved on to more advanced use of MMF in the shared memory design.

Labels: