Windows中的内存映射文件

时间:2011-05-09 23:35:11

标签: memory virtual memory-mapped-files

我正在阅读有关共享内存的内容以及我正在阅读的OS书籍给出了以下生产者/消费者计划:

制片:

#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 *'

有什么问题?

1 个答案:

答案 0 :(得分:0)

在C ++中,从'void *'到指向非void的指针需要显式转换。

sprintf需要char *,所以必须转换void指针。