首页 > 代码库 > c/c++常用代码 -- 共享内存
c/c++常用代码 -- 共享内存
#pragma once#include <stdio.h>#include <tchar.h>#include <string.h>#include <windows.h>template<class T> class CMySM{public: CMySM() { m_pMem = NULL; m_hMem = NULL; } ~CMySM() { Close(); } BOOL Create(LPCTSTR szName) { if (szName == NULL || _tcslen(szName) == 0) return FALSE; do { m_hMem = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE | SEC_COMMIT, 0, sizeof(T), szName); if (m_hMem == NULL) break; m_pMem = MapViewOfFile(m_hMem, FILE_MAP_ALL_ACCESS, 0, 0, 0); if (m_pMem == NULL) break; memset(m_pMem, 0, sizeof(T)); return TRUE; } while (FALSE); Close(); return FALSE; } BOOL Open(LPCTSTR szName) { if (szName == NULL || _tcslen(szName) == 0) return FALSE; do { m_hMem = OpenFileMapping(FILE_MAP_ALL_ACCESS, FALSE, szName); if (m_hMem == NULL) break; m_pMem = MapViewOfFile(m_hMem, FILE_MAP_ALL_ACCESS, 0, 0, 0); if (m_pMem == NULL) break; return TRUE; } while (FALSE); Close(); return FALSE; } void Close() { if (m_pMem != NULL) { UnmapViewOfFile(m_pMem); m_pMem = NULL; } if (m_hMem != NULL) { CloseHandle(m_hMem); m_hMem = NULL; } } inline T* Get(){return (T*)m_pMem;} public: PVOID m_pMem; HANDLE m_hMem;};
c/c++常用代码 -- 共享内存
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。