summaryrefslogtreecommitdiffstats
path: root/CPP/Windows/FileMapping.h
blob: 138a175b4050cb3bb0bd216e684e3c04093887fd (plain)
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
58
59
60
61
62
// Windows/FileMapping.h

#ifndef __WINDOWS_FILEMAPPING_H
#define __WINDOWS_FILEMAPPING_H

#include "Common/Types.h"

#include "Handle.h"

namespace NWindows {

class CFileMapping: public CHandle
{
public:
  WRes Create(DWORD protect, UInt64 maxSize, LPCTSTR name)
  {
    _handle = ::CreateFileMapping(INVALID_HANDLE_VALUE, NULL, protect, (DWORD)(maxSize >> 32), (DWORD)maxSize, name);
    return ::GetLastError();
  }

  WRes Open(DWORD desiredAccess, LPCTSTR name)
  {
    #ifdef UNDER_CE
    WRes res = Create(PAGE_READONLY, 0, name);
    if (res == ERROR_ALREADY_EXISTS)
      return 0;
    Close();
    if (res == 0)
      res = ERROR_FILE_NOT_FOUND;
    return res;
    #else
    _handle = ::OpenFileMapping(desiredAccess, FALSE, name);
    if (_handle != 0)
      return 0;
    return ::GetLastError();
    #endif
  }

  LPVOID Map(DWORD desiredAccess, UInt64 fileOffset, SIZE_T numberOfBytesToMap)
  {
    return ::MapViewOfFile(_handle, desiredAccess, (DWORD)(fileOffset >> 32), (DWORD)fileOffset, numberOfBytesToMap);
  }

  #ifndef UNDER_CE
  LPVOID Map(DWORD desiredAccess, UInt64 fileOffset, SIZE_T numberOfBytesToMap, LPVOID baseAddress)
  {
    return ::MapViewOfFileEx(_handle, desiredAccess, (DWORD)(fileOffset >> 32), (DWORD)fileOffset, numberOfBytesToMap, baseAddress);
  }
  #endif
};

class CFileUnmapper
{
  const void *_data;
public:
  CFileUnmapper(const void *data) : _data(data) {}
  ~CFileUnmapper() { ::UnmapViewOfFile(_data); }
};

}

#endif