我尝试了一个来自 MSDN 的示例,该示例展示了如何使用 fileMapping 函数进行读写。我在此处粘贴代码供您从 MSDN 参考。该链接是http://msdn.microsoft.com/en-us/library/windows/desktop/aa366551(v=vs.85).aspx
#include"stdafx.h"
#include <windows.h>
#include <stdio.h>
#include <conio.h>
#include <tchar.h>
#include<iostream>
#pragma comment(lib, "user32.lib")
using namespace std;
#define BUF_SIZE 256
TCHAR szName[]=TEXT("/Global/MyFileMappingObject");
int _tmain()
{
HANDLE hMapFile;
LPTSTR pBuf;
hMapFile = OpenFileMapping(
FILE_MAP_ALL_ACCESS, // read/write access
FALSE, // do not inherit the name
szName); // name of mapping object
if (hMapFile == NULL)
{
_tprintf(TEXT("Could not open file mapping object\n"),
GetLastError());
//cout<<"Could not create file mapping object"<<endl;
_getche();
return 1;
}
pBuf = (LPTSTR) MapViewOfFile(hMapFile, // handle to map object
FILE_MAP_ALL_ACCESS, // read/write permission
0,
0,
BUF_SIZE);
if (pBuf == NULL)
{
_tprintf(TEXT("Could not map view of file (%d).\n"),
GetLastError());
//cout<<"Could not map view of file"<<endl;
_getche();
CloseHandle(hMapFile);
return 1;
}
//_tprintf(Text("Message from process 1 is %s",&pBuf));
//Convert LPTSTR to char
cout<<"Pbuf is "<<*pBuf<<endl;
size_t size = wcstombs(NULL,pBuf,0);
const wchar_t* charStr = new wchar_t[size+1];
//wcstombs(pBuf,charStr,size+1);
MessageBox(NULL, pBuf, TEXT("Process2"), MB_OK);
UnmapViewOfFile(pBuf);
CloseHandle(hMapFile);
_getche();
return 0;
}
如果你看到有这个语句 MessageBox(NULL, pBuf, TEXT("Process2"), MB_OK); 它接受 pBuf(LPCTSTR 变量)并打印文件中输入的内容。我想检索 pBuf 指向的内容,或者有人可以指导消息框如何读取该值。我尝试使用 *pBuf 但它给了我一些位置。我只是被困在这里。请帮忙。