我需要在program1中创建一个vector< int >
数据,然后使用CreateFileMapping
在program2中使用它:
以下是program1的代码:
#include "stdafx.h"
#include <windows.h>
#include <stdio.h>
#include <conio.h>
#include <tchar.h>
#include <vector>
#include <string>
#include <iostream>
using namespace std;
int main(){
HANDLE hMapFile = CreateFileMapping(INVALID_HANDLE_VALUE,NULL,PAGE_READWRITE,1,L"MyFileMappingObject");
HANDLE hBuffer = MapViewOfFile(hMapFile, FILE_MAP_ALL_ACCESS, 0, 0, 0);
vector<int>* pBuf = (vector<int>*)hBuffer;
for (int i = 0; i < 200; i++)
pBuf->push_back(i);
_getch();//wating for pressing any key
UnmapViewOfFile(hBuffer);
CloseHandle(hMapFile);
Return 0;
}
程序2的代码是:
//headers…
int main(){
HANDLE hMapFile = OpenFileMapping(FILE_MAP_ALL_ACCESS, FALSE, L"MyFileMappingObject");
HANDLE hBuffer = MapViewOfFile(hMapFile, FILE_MAP_ALL_ACCESS, 0, 0, 0);
vector<int>* pBuf = (vector<int>*)hBuffer;
for (int i = 0; i < 200; i++)
cout << pBuf->at(i) << endl;
//pBuf->push_back(i);
UnmapViewOfFile(hBuffer);
CloseHandle(hMapFile);
Return 0;
}
当我运行program1时,我可以将项添加到向量中,但在program2中我无法读取和添加和修改项。在program2中,我看到调试中每个向量项的“无法读取内存”; 有什么问题,如何解决这个问题?