面临的问题:使用文件映射共享的列表不提供列表内的任何数据...
我有一个进程 1,在其中我将所有数据存储为 hash_map 列表,然后我尝试使用文件映射来共享它......在 Process2 中,当我尝试检索列表中的数据时,在列表中找不到数据..
PS:我的exe与dll捆绑在一起,我将我的dll作为process1和exe作为process2 ...
这是我的代码,
过程1
/* this is in common headerFile */
typedef hash_map <std::wstring,std::wstring> AttrValues;
CString FileName = L"E:\\DataLog.txt";
TCHAR szName[]=TEXT("Local\MyFileMappingObject");
struct ADstruct
{
std::list<AttrValues> StList;
int i;
};
/*Sharememory.cpp*/
DWORD SharedMemory()
{
AttrValues HardCode;//Sample data which i am hard coding for testing
HardCode[L"NAme"] = L"Test";
HardCode[L"D.Name"] = L"SAP";
std::list <AttrValues> HardCodedList;
HardCodedList.push_back(HardCode);
ADstruct CheckStruct;
CheckStruct.i = 10;
CheckStruct.StList = HardCodedList;
HANDLE hFile = INVALID_HANDLE_VALUE;// HANDLE hFile;
hFile = CreateFile(FileName.GetBuffer(), GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_ALWAYS, 0, NULL);
if(hFile == INVALID_HANDLE_VALUE)
{
printf("Error in creating a file..!");
return 0;
}
hMapFile = CreateFileMapping(
hFile, // use paging file
NULL, // default security
PAGE_READWRITE, // read/write access
0, // maximum object size (high-order DWORD)
sizeof(ADstruct), // maximum object size (low-order DWORD)
szName); // name of mapping object
if (hMapFile == NULL)
{
_tprintf(TEXT("Could not create file mapping object (%d).\n"),
GetLastError());
return 1;
}
ADstruct *ADobj = new ADstruct;
ADobj = (ADstruct *) MapViewOfFile(hMapFile, // handle to map object
FILE_MAP_ALL_ACCESS, // read/write permission
0,
0,
sizeof(ADstruct) );
CopyMemory( (ADstruct *) ADobj, &CheckStruct , sizeof(ADstruct) );
UnmapViewOfFile(pBuf);
CloseHandle(hMapFile);
return 0
}
过程2:
BOOL ReadMemoryMapping()
{
hash_map<LPWSTR,LPWSTR> ADdata;
HANDLE hMapFile;
HANDLE hFile = INVALID_HANDLE_VALUE;
hMapFile = OpenFileMapping(
FILE_MAP_ALL_ACCESS, // read/write access
FALSE, // do not inherit the name
szName); // name of mapping object
if (hMapFile == NULL)
{
_tprintf(TEXT("Could not open file mapping object (%d).\n"),
GetLastError());
return 1;
}
ADstruct * readstruct;
readstruct = (ADstruct *) MapViewOfFile(hMapFile, // handle to map object
FILE_MAP_ALL_ACCESS, // read/write permission
0,
0,
sizeof(ADstruct));
_tprintf(L"\nprint data%d\n",readstruct->i);
AttrValues At ;
for(std::list<AttrValues>::iterator list_iter = readstruct->StList.begin();
list_iter != readstruct->StList.end(); list_iter++)
{
At.clear();
At = *list_iter; //*****Here the code crashes as there is no datas inside***
if(At.empty() == 1)
printf("List is empty\n");
std::wcout<<endl<<endl<<"Attribute List In EXE : StList"<<endl;
for(AttrValues :: iterator it1 = list_iter->begin(); it1!= list_iter->end(); it1++)
{
std::wcout<<it1->first<<endl;
std::wcout<<it1->second<<endl;
}
}
UnmapViewOfFile(readstruct);
CloseHandle(hMapFile);
return 0;
}