复制内存块

时间:2013-08-22 13:51:56

标签: c++ memory serialization memory-management file-mapping

//include headers.
#include <windows.h>
#include <iostream>
#define BUF_SIZE 256
TCHAR szName[]=TEXT("MyFileMappingObject");
LPCTSTR pBuf;

//my data stracture.
struct NetworkVariabel
{
    int ServerTime;
    int Value1;
    int Value2;
};

//main program.
int  main()
{
    //map file handel.
    HANDLE hMapFile;
    hMapFile = CreateFileMapping(
        INVALID_HANDLE_VALUE,    // use paging file
        NULL,                    // default security
        PAGE_READWRITE,          // read/write access
        0,                       // maximum object size (high-order DWORD)
        BUF_SIZE,                // maximum object size (low-order DWORD)
        szName);                 // name of mapping object

    //if null.
    if (hMapFile == NULL){
        return 0;
    }

    pBuf = (LPTSTR) MapViewOfFile(hMapFile,   // handle to map object
        FILE_MAP_ALL_ACCESS, // read/write permission
        0,
        0,
        BUF_SIZE);

    //if null.
    if (pBuf == NULL){ 
        CloseHandle(hMapFile); 
        return 0;
    }

    //my memory block data
    NetworkVariabel BaseGlobalNetData;
    BaseGlobalNetData.ServerTime=100;
    BaseGlobalNetData.Value1=50;
    BaseGlobalNetData.Value2=80;

    CopyMemory((PVOID)pBuf, &BaseGlobalNetData,sizeof(BaseGlobalNetData)   );//fill memory block this line work fine.

    //my new memory block data
    NetworkVariabel ReplaceNewGlobalNetData;
    ReplaceNewGlobalNetData.Value1=988;

    //now just want to replace 4byte(the Value1 variable data) into memory block so add to next 3 byte offset and 4byte Len because its integer ;
    CopyMemory((PVOID)pBuf+3, &ReplaceNewGlobalNetData,    sizeof(int)   );

    //get a key.
    getchar();

    //unmap.
    UnmapViewOfFile(pBuf);

    //close map.
    CloseHandle(hMapFile);

    return 0;
}

我想只复制4个字节:(“value1”整数变量到我的内存块中)。

当我尝试编译时,我收到此错误:

  

错误1错误C2036:'PVOID':未知大小

1 个答案:

答案 0 :(得分:0)

向指针使用(PBYTE)添加3个字节,而不是(PVOID)