开发者

Memory-mapped-files in Windows

开发者 https://www.devze.com 2023-03-04 14:22 出处:网络
I\'m reading about shared memory and the OS book I\'m reading gives the following producer/consumer programs:

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,
        开发者_Python百科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?


In C++, conversion from 'void*' to pointer to non-void requires an explicit cast.

sprintf needs char *, so have to cast the void pointer.

0

精彩评论

暂无评论...
验证码 换一张
取 消