首页 > 代码库 > 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++常用代码 -- 共享内存