MyException - 我的异常网
当前位置:我的异常网» VC/MFC » 内存映射文件,这样弄不知行不行?解决办法

内存映射文件,这样弄不知行不行?解决办法

www.MyException.Cn  网友分享于:2013-12-28  浏览:13次
内存映射文件,这样弄不知行不行?

HANDLE handle=CreateFileMapping((HANDLE)-1,0,PAGE_READWRITE,0,1024*1024*256,0);
LPVOID px=MapViewOfFile(handle,FILE_MAP_ALL_ACCESS,0,1024*64,0);

------解决方案--------------------
报错,无效句柄
------解决方案--------------------
C/C++ code

#include <windows.h>
#include <stdio.h>
#include <conio.h>

#define BUF_SIZE 256
TCHAR szName[]=TEXT("Global\\MyFileMappingObject");
TCHAR szMsg[]=TEXT("Message from first process");

int main()
{
   HANDLE hMapFile;
   LPCTSTR pBuf;

   hMapFile = CreateFileMapping(
                 INVALID_HANDLE_VALUE,    // use paging file
                 NULL,                    // default security 
                 PAGE_READWRITE,          // read/write access
                 0,                       // max. object size 
                 BUF_SIZE,                // buffer size  
                 szName);                 // name of mapping object
 
   if (hMapFile == NULL) 
   { 
      printf("Could not create file mapping object (%d).\n", 
             GetLastError());
      return 1;
   }
   pBuf = (LPTSTR) MapViewOfFile(hMapFile,   // handle to map object
                        FILE_MAP_ALL_ACCESS, // read/write permission
                        0,                   
                        0,                   
                        BUF_SIZE);           
 
   if (pBuf == NULL) 
   { 
      printf("Could not map view of file (%d).\n", 
             GetLastError()); 
      return 2;
   }

   
   CopyMemory((PVOID)pBuf, szMsg, strlen(szMsg));
   _getch();

   UnmapViewOfFile(pBuf);

   CloseHandle(hMapFile);

   return 0;
}

文章评论

软件开发程序错误异常ExceptionCopyright © 2009-2015 MyException 版权所有