Knowledge Base Nr: 00046 memory_mapped_files.cpp - http://www.swe-kaiser.de
Downloads:
Win32: beispiel für memory mapped files unter win nt
/////////////////////////////////////
typedef struct //diesen struct anpassen
{
short nVal1;
short nVal2;
} MMFPARAM, *LPMMFPARAM;
int InitMMFData(); //initialisieren des memory mapped files (bei programmstart)
int CleanupMMFData(); //freigeben des memory mapped files (bei programmende)
int ReadWriteMMFData(LPMMFPARAM lpMMFPARAM, bool bWrite); //(zugriff auf den struct)
//diese funktionen sind auf den struct zugeschnitten!
short ReadDIOValue();
short WriteDIOValue(short nValue);
/////////////////////////////////////
HANDLE g_hFileMap = NULL;
int InitMMFData()
{
if (g_hFileMap == NULL) //noch nicht offen
{
g_hFileMap = CreateFileMapping((HANDLE)0xffffffff,
NULL,
PAGE_READWRITE,
0,
sizeof(MMFPARAM),
_T("DIOMemoryMappedFile"));
if (g_hFileMap == NULL)
return ::GetLastError();
}
if (GetLastError() == ERROR_ALREADY_EXISTS)
{
//file existiert bereits -> es kann z.b. gelesen werden
}
return 0;
}
int CleanupMMFData()
{
if (g_hFileMap != NULL) //nur wenn offen
{
BOOL bSucc = ::CloseHandle(g_hFileMap);
if (!bSucc)
return ::GetLastError();
}
return 0;
}
int ReadWriteMMFData(LPMMFPARAM lpMMFPARAM, bool bWrite)
{
InitMMFData(); //wenn schon initialisiert kehrt die funktion sofort zurück
if (g_hFileMap == NULL)
return -4711;
LPVOID lpView = MapViewOfFile(g_hFileMap,
FILE_MAP_READ | FILE_MAP_WRITE,
0,
0,
0);
if (lpView == NULL)
{
CleanupMMFData();
return ::GetLastError();
}
LPMMFPARAM lpMMFPARAMFile = (LPMMFPARAM) lpView;
if (bWrite) //schreiben
memcpy(lpMMFPARAMFile, lpMMFPARAM, sizeof(LPMMFPARAM));
else //lesen
memcpy(lpMMFPARAM, lpMMFPARAMFile, sizeof(LPMMFPARAM));
BOOL bSucc = UnmapViewOfFile(lpView);
if (!bSucc)
{
CleanupMMFData();
return ::GetLastError();
}
return 0;
}
/////////////////////////////////////
//beispielfunktionen abhängig vom definierten struct
short ReadDIOValue()
{
MMFPARAM sMMFPARAM;
int nRes = ReadWriteMMFData(&sMMFPARAM, false);
return sMMFPARAM.nVal1;
}
short WriteDIOValue(short nValue)
{
MMFPARAM sMMFPARAM;
sMMFPARAM.nVal1 = nValue;
int nRes = ReadWriteMMFData(&sMMFPARAM, true);
return sMMFPARAM.nVal1;
}
/////////////////////////////////////
//beispielnutzung
void CSharememDlg::OnLesen()
{
short nValue = ReadDIOValue();
CString str;
str.Format("%d", nValue);
GetDlgItem(IDC_VAL)->SetWindowText(str);
}
void CSharememDlg::OnSchreiben()
{
CString str;
GetDlgItem(IDC_VAL)->GetWindowText(str);
short nValue = atoi(str);
WriteDIOValue(nValue);
}