如何在 C++ 中写入共享内存?
我想写入共享内存,然后将内容转储到 win32 api 中的文件中。 目前我有这样的代码:
HANDLE hFile, hMapFile;
LPVOID lpMapAddress;
hFile = CreateFile("input.map",
GENERIC_READ | GENERIC_WRITE,
0,
NULL,
OPEN_EXISTING,
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(MapViewOfFile, "<output 1>");
UnmapViewOfFile(lpMapAddress);
CloseHandle(hFile);
CloseHandle(hMapFile);
但是,第 31 行( sprintf 调用)给出了错误:
error: cannot convert `void*(*)(void*, DWORD, DWORD, DWORD, DWORD)'
to `char*' for argument `1' to `int sprintf(char*, const char*, ...)'
我尝试将 lpMapAddress 转换为 LPTSTR ,但它没有效果。我做错了什么?或者有更好的方法吗?
I'd like to write to shared memory and then dump the contents to a file in the win32 api.
Currently I have this code:
HANDLE hFile, hMapFile;
LPVOID lpMapAddress;
hFile = CreateFile("input.map",
GENERIC_READ | GENERIC_WRITE,
0,
NULL,
OPEN_EXISTING,
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(MapViewOfFile, "<output 1>");
UnmapViewOfFile(lpMapAddress);
CloseHandle(hFile);
CloseHandle(hMapFile);
However, line 31 (the sprintf call) gives the error:
error: cannot convert `void*(*)(void*, DWORD, DWORD, DWORD, DWORD)'
to `char*' for argument `1' to `int sprintf(char*, const char*, ...)'
I've tried casting the lpMapAddress to LPTSTR, but it has no effect. What am I doing wrong? Or is there a better way to do it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在该
行中,您需要
lpMapAddress
,而不是MapViewOfFile
。或者准确地说是(char*)lpMapAddress
。In the
line, you wanted
lpMapAddress
, notMapViewOfFile
. Or(char*)lpMapAddress
to be precise.您正在尝试写入常规文件。要写入共享内存,您应该将
INVALID_HANDLE_VALUE
传递给CreateFileMapping
。请参阅这篇文章了解更多详细信息。You are trying to write to a regular file. To write to shared memory you should pass
INVALID_HANDLE_VALUE
toCreateFileMapping
. Check out this article for more details.在 sprintf 中,您传递函数 MapViewOfFile 的地址。相反,您应该传递映射的内存地址。
In sprintf you are passing the address of the function MapViewOfFile. Instead you should pass the mapped memory address.
回答“有更好的方法吗?”:看看 Boost.Interprocess,内存映射部分尤其如此。
Answering the "is there a better way to do it?": Take a look at Boost.Interprocess, the section on memory mapping in particular.