2011-05-09 71 views
0

我閱讀有關共享內存和操作系統的書我讀提供了以下生產者/消費者計劃:內存映射,文件在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的':無法從 'LPVOID' 到 '字符*'

什麼問題轉換參數1?

+0

可能的重複[如何寫入共享內存在C++?](http://stackoverflow.com/questions/1423031/how-do-i-write-to-shared-memory-in-c) – Joe 2011-05-10 00:11:28

回答

0

在C++中,從'void *'到指向非void的指針的轉換需要顯式強制轉換。

sprintf需要char *,所以必須施放void指針。