码迷,mamicode.com
首页 > 编程语言 > 详细

c/c++常用代码 -- 共享内存

时间:2014-11-02 00:24:48      阅读:228      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   color   os   ar   sp   div   on   

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

标签:style   blog   io   color   os   ar   sp   div   on   

原文地址:http://www.cnblogs.com/wansui/p/4067968.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!