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;
};

 

posted @ 2014-11-01 23:38  崇山峻岭  阅读(255)  评论(0编辑  收藏  举报