2010年5月4日 星期二

[.NETCF] How to declare memory-mapped file API with C# in WinCE

public class WinCEConst
{
public const UInt32 STANDARD_RIGHTS_REQUIRED = 0x000F0000;
public const UInt32 SECTION_QUERY = 0x0001;
public const UInt32 SECTION_MAP_WRITE = 0x0002;
public const UInt32 SECTION_MAP_READ = 0x0004;
public const UInt32 SECTION_MAP_EXECUTE = 0x0008;
public const UInt32 SECTION_EXTEND_SIZE = 0x0010;
public const UInt32 SECTION_ALL_ACCESS = (STANDARD_RIGHTS_REQUIRED SECTION_QUERY|
SECTION_MAP_WRITE|
SECTION_MAP_READ|
SECTION_MAP_EXECUTE|
SECTION_EXTEND_SIZE);
public const UInt32 FILE_MAP_ALL_ACCESS = SECTION_ALL_ACCESS;

public static IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1);

public const int PAGE_READWRITE = 0x04;
public const int PAGE_READONLY = 0x02;
public const int FILE_MAP_READ = 0x0004;
public const int FILE_MAP_WRITE = 0x0002;
}

public class WinCE
{
// * WinCE using coredll.dll
// * Windows using keneral32.dll

[DllImport("Coredll.dll", SetLastError = true, CharSet = CharSet.Auto)]
public static extern IntPtr CreateFileMapping(
IntPtr hFile,
object lpFileMappingAttributes,
uint flProtect,
uint dwMaximumSizeHigh,
uint dwMaximumSizeLow,
string lpName);

public static IntPtr OpenFileMapping(uint dwDesiredAccess, bool bInheritHandle, string lpName)
{
IntPtr t_pHandle = CreateFileMapping(new IntPtr(-1), null,
WinCEConst.PAGE_READWRITE, 0, 0, lpName);
return t_pHandle;
}

[DllImport("Coredll.dll", SetLastError = true)]
public static extern bool CloseHandle(IntPtr hObject);

[DllImport("Coredll.dll", SetLastError = true)]
public static extern IntPtr MapViewOfFile(
IntPtr hFileMappingObject,
uint dwDesiredAccess,
uint dwFileOffsetHigh,
uint dwFileOffsetLow,
uint dwNumberOfBytesToMap);

[DllImport("Coredll.dll", SetLastError = true)]
public static extern bool UnmapViewOfFile(IntPtr lpBaseAddress);
}


If we want to communicate information at different process , we can use memory-mapped file.

If we want to use memory-mapped file in C#, we must use DllImport to declare API.

Memory-mapped files (MMFs) offer a unique memory management feature that allows applications to access files on disk in the same way they access dynamic memory—through pointers. With this capability you can map a view of all or part of a file on disk to a specific range of addresses within your process's address space. And once that is done, accessing the content of a memory-mapped file is as simple as dereferencing a pointer in the designated range of addresses.

You can see the reference for Win32 on MSDN.

沒有留言:

張貼留言

Hello