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 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 |
#pragma once template<class T> class CSessionGlobalMemory { public: explicit CSessionGlobalMemory(LPCSTR pName) { h_=NULL; p_=NULL; m_=NULL; size_t len=lstrlenA(pName); m_pName = (LPSTR)LocalAlloc(LMEM_FIXED, len+sizeof(char)); lstrcpyA(m_pName, pName); m_pMutexName = (LPSTR)LocalAlloc(LMEM_FIXED, len+sizeof("_Mutex")-1+sizeof(char)); lstrcpyA(m_pMutexName, pName); lstrcatA(m_pMutexName, "_Mutex"); } ~CSessionGlobalMemory(){ release(); } operator T() { return get(); } void operator =(const T& t) { set(t); //return t; } private: class Locker { public: HANDLE m_; Locker(HANDLE m) { m_=m; WaitForSingleObject(m,INFINITE); } ~Locker() { ReleaseMutex(m_); } }; void release() { if(p_) { UnmapViewOfFile(p_); p_=NULL; } if(h_) { CloseHandle(h_); h_=NULL; } if(m_) { CloseHandle(m_); m_=NULL; } LocalFree(m_pName); LocalFree(m_pMutexName); } void ensure() { if(!m_) { m_=CreateMutexA(NULL,FALSE,m_pMutexName); } bool first=false; if(!h_) { h_=CreateFileMappingA( INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0,sizeof(T), m_pName); if(h_ && GetLastError()!=ERROR_ALREADY_EXISTS) { first = true; } } if(!p_) { p_=MapViewOfFile( h_, FILE_MAP_READ|FILE_MAP_WRITE, 0,0, sizeof(T)); } if(first) { Locker l(m_); if(first) { memset(p_,0,sizeof(T)); first=false; } } } T get() { ensure(); Locker l(m_); T t; memcpy(&t,p_,sizeof(t)); return t; } void set(const T& t) { ensure(); Locker l(m_); memcpy(p_, &t, sizeof(t)); } bool first_; HANDLE h_; void* p_; HANDLE m_; LPSTR m_pName; LPSTR m_pMutexName; }; |
最初に0クリアする方法がいまいちわからなかった。
カーネルオブジェクトの名前にLocal/やglobal/をつければセッション間でもできるみたいだがスルー