-
Notifications
You must be signed in to change notification settings - Fork 4
/
MemoryMappedFile.cs
57 lines (50 loc) · 1.95 KB
/
MemoryMappedFile.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
using System;
using System.IO;
using System.Runtime.InteropServices;
namespace GT2Vol
{
public static class MemoryMappedFile
{
private static uint PAGE_READONLY = 0x2;
private static uint FILE_MAP_READ = 0x4;
[DllImport("kernel32.dll", ExactSpelling = true, CallingConvention = CallingConvention.StdCall, SetLastError = true)]
private extern static IntPtr CreateFileMappingW(
IntPtr fileHandle,
IntPtr sec,
uint protect,
uint maxHigh,
uint maxLow,
[MarshalAs(UnmanagedType.LPWStr)]
string name
);
[DllImport("kernel32.dll", ExactSpelling = true, CallingConvention = CallingConvention.StdCall, SetLastError = true)]
private extern static int UnmapViewOfFile(IntPtr pFile);
[DllImport("kernel32.dll", ExactSpelling = true, CallingConvention = CallingConvention.StdCall, SetLastError = true)]
private extern static IntPtr MapViewOfFileEx(
IntPtr mapHandle,
uint access,
uint offLow,
uint offHigh,
IntPtr bytesToMap,
IntPtr baseAddress
);
[DllImport("kernel32.dll", ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
private static extern int CloseHandle(IntPtr handle);
public static IntPtr Map(FileStream file)
{
IntPtr fileHandle = file.SafeFileHandle.DangerousGetHandle();
IntPtr mapHandle = CreateFileMappingW(fileHandle, IntPtr.Zero, PAGE_READONLY, 0, 0, null);
if (mapHandle != IntPtr.Zero)
{
IntPtr pFile = MapViewOfFileEx(mapHandle, FILE_MAP_READ, 0, 0, IntPtr.Zero, IntPtr.Zero);
CloseHandle(mapHandle);
mapHandle = pFile;
}
return mapHandle;
}
public static void UnMap(IntPtr pFile)
{
UnmapViewOfFile(pFile);
}
}
}