VC++ FileMapping

声明:本人一个菜鸟,网上搜罗了很多关于VC++编程的资料,可每本资料都是涵盖面太广,难以细致。英语又太烂,所以不得意只得摸索,恐又忘记所以记在此处,若有不对的地方,烦劳指出,不胜感激。

author:[email protected]

license:GPL

IDE:Visual Studio 2008


alice

#include "stdafx.h"
#include <iostream>
#include <Windows.h>
#include <string>
#include <afx.h>
// 貌似多线程需要在共享DLL中使用MFC

int _tmain(int argc, _TCHAR* argv[])
{
    std::cout << "Begin pro_alice" <<std::endl;

    TCHAR szFileMapName[] = _T("g_FileMapName");
    HANDLE hFileMap = CreateFileMapping(
        INVALID_HANDLE_VALUE,   //页交换文件
        NULL,                   //安全属性
        PAGE_READWRITE,         //读写
        0,                      //内存映射高4位字节
        1024,                   //内存映射低4位字节
        szFileMapName           //名字
        );
    if (NULL == hFileMap)
    {
        std::cout << "CreateFileMapping failed!" <<std::endl;
        return 1;
    }

    PVOID pvFile = MapViewOfFile(
        hFileMap,            //内存映射句柄
        FILE_MAP_WRITE,      //只写
        0,                   //偏移量高4位字节
        0,                   //偏移量低4位字节
        0                    //全部映射
        );
    if (NULL == pvFile)
    {
        std::cerr<<"MapViewOfFile failed!" <<std::endl;
        return 2;
    }
    _tcscpy((PTSTR)pvFile,_T("hello world"));  //向内存映射中写入东东
    system("pause");

	return 0;
}

bob

#include "stdafx.h"
#include <iostream>
#include <Windows.h>
#include <string>
#include <afx.h>
// 貌似多线程需要在共享DLL中使用MFC

int _tmain(int argc, _TCHAR* argv[])
{
    std::cout << "Begin All pro_bob" <<std::endl;
    TCHAR szFileMapName[] = _T("g_FileMapName");
    HANDLE hFileMap = OpenFileMapping(
        FILE_MAP_READ,   //以只读方式映射内存
        FALSE,           //不继承句柄
        szFileMapName    //内存映射名字
        );

    PVOID pvFile = MapViewOfFile(hFileMap,FILE_MAP_READ,0,0,0);
    if (NULL == pvFile)
    {
        std::cout << "MapViewOfFile failed!" <<std::endl;
        return 1;
    }
    TCHAR dst[1024] = {0};
    CString str = (PTSTR)pvFile;
    std::cout << str <<std::endl;

    std::cout << "End pro_bob" <<std::endl;
	return 0;
}


你可能感兴趣的:(多线程,File,null,System,dll,vc++)