Windows 中的内存映射文件
我正在阅读有关共享内存的内容,我正在阅读的操作系统书籍提供了以下生产者/消费者程序:
生产者:
#include <windows.h>
#include <stdio.h>
int main(int argc, char *argv[])
{
HANDLE hFile, hMapFile;
LPVOID lpMapAddress;
hFile = CreateFile("temp.txt",
GENERIC_READ | GENERIC_WRITE,
0,
NULL,
OPEN_ALWAYS,
FILE_ATTRIBUTE_NORMAL,
NULL);
hMapFile = CreateFileMapping(hFile,
NULL,
PAGE_READWRITE,
0,
0,
TEXT("SharedObject"));
lpMapAddress = MapViewOfFile(hMapFile,
FILE_MAP_ALL_ACCESS,
0,
0,
0);
sprintf(lpMapAddress, "Shared memory message");
UnmapViewOfFile(lpMapAddress);
CloseHandle(hFile);
CloseHandle(hMapFile);
}
消费者:
#include <windows.h>
#include <stdio.h>
int main(int argc, char *argv[])
{
HANDLE hMapFile;
LPVOID lpMapAddress;
hMapFile = OpenFileMapping(FILE_MAP_ALL_ACCESS,
FALSE,
TEXT("SharedObject"));
lpMapAddress = MapViewOfFile(hMapFile,
FILE_MAP_ALL_ACCESS,
0,
0,
0);
printf("Read message %s", lpMapAddress);
UnmapViewOfFile(lpMapAddress);
CloseHandle(hMapFile);
}
问题是它无法编译。 Visual C++ 2008 Express 在生产者部分给出此错误:
错误 C2664: 'sprintf' : 无法将参数 1 从 'LPVOID' 转换为 'char *'
有什么问题?
I'm reading about shared memory and the OS book I'm reading gives the following producer/consumer programs:
Producer:
#include <windows.h>
#include <stdio.h>
int main(int argc, char *argv[])
{
HANDLE hFile, hMapFile;
LPVOID lpMapAddress;
hFile = CreateFile("temp.txt",
GENERIC_READ | GENERIC_WRITE,
0,
NULL,
OPEN_ALWAYS,
FILE_ATTRIBUTE_NORMAL,
NULL);
hMapFile = CreateFileMapping(hFile,
NULL,
PAGE_READWRITE,
0,
0,
TEXT("SharedObject"));
lpMapAddress = MapViewOfFile(hMapFile,
FILE_MAP_ALL_ACCESS,
0,
0,
0);
sprintf(lpMapAddress, "Shared memory message");
UnmapViewOfFile(lpMapAddress);
CloseHandle(hFile);
CloseHandle(hMapFile);
}
Consumer:
#include <windows.h>
#include <stdio.h>
int main(int argc, char *argv[])
{
HANDLE hMapFile;
LPVOID lpMapAddress;
hMapFile = OpenFileMapping(FILE_MAP_ALL_ACCESS,
FALSE,
TEXT("SharedObject"));
lpMapAddress = MapViewOfFile(hMapFile,
FILE_MAP_ALL_ACCESS,
0,
0,
0);
printf("Read message %s", lpMapAddress);
UnmapViewOfFile(lpMapAddress);
CloseHandle(hMapFile);
}
Problem is it doesn't compile. Visual C++ 2008 Express gives this error in the producer part:
error C2664: 'sprintf' : cannot convert parameter 1 from 'LPVOID' to 'char *'
What's the problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在 C++ 中,从“void*”到非 void 指针的转换需要显式强制转换。
sprintf 需要 char *,因此必须强制转换 void 指针。
In C++, conversion from 'void*' to pointer to non-void requires an explicit cast.
sprintf needs char *, so have to cast the void pointer.