c++ builder / Windowsソフト間通信 > Named File Mapping > 読出し側コード


動作環境
C++ Builder XE4 on Windows 7 pro

http://qiita.com/7of9/items/1e473d014568ff84e925
でFile Mapping書出ししたメッセージを読出す。

Receiver.cpp
//---------------------------------------------------------------------------

#include <vcl.h>
#pragma hdrstop

#include "Receiver.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm3 *Form3;
//---------------------------------------------------------------------------
__fastcall TForm3::TForm3(TComponent* Owner)
    : TForm(Owner)
{
}
//---------------------------------------------------------------------------

#define BUF_SIZE 256
#if 1
TCHAR szName[] = TEXT("GlobalMyfileMappingObject");
#else
TCHAR szName[] = TEXT("Global\\MyFileMappingObject");
#endif

void __fastcall TForm3::Button1Click(TObject *Sender)
{
    HANDLE hMapFile;
    LPCTSTR pBuf;

#if 0
    // SECTION_MAP_WRITE | SECTION_MAP_READ
    hMapFile = OpenFileMapping(
                   SECTION_MAP_WRITE | SECTION_MAP_READ,   // read/write access
                   FALSE,                 // do not inherit the name
                   szName);               // name of mapping object
#else
    hMapFile = OpenFileMapping(
                   FILE_MAP_ALL_ACCESS,   // read/write access
                   FALSE,                 // do not inherit the name
                   szName);               // name of mapping object
#endif

    if (hMapFile == NULL){
        String msg = String().sprintf(L"Could not create file mapping object (%d)\n", GetLastError());
        ShowMessage(msg);
        return;
    }

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

    if (pBuf == NULL){
        String msg = String().sprintf(L"Could not map view of file (%d)\n", GetLastError());
        ShowMessage(msg);
        CloseHandle(hMapFile);
        return;
    }

    MessageBox(NULL, pBuf, TEXT("Process2"), MB_OK);

    UnmapViewOfFile(pBuf);

    CloseHandle(hMapFile);
}
//---------------------------------------------------------------------------

Sender.exeの方でB_sendを押してからReceiver.exeでButton1を押すと読み出しできる。