團(tuán)購網(wǎng)站如何優(yōu)化百度推廣免費
在開發(fā)軟件過程里,也經(jīng)常碰到進(jìn)程間共享數(shù)據(jù)的需求。比如A進(jìn)程創(chuàng)建計算數(shù)據(jù),B進(jìn)程進(jìn)行顯示數(shù)據(jù)的圖形。這樣的開發(fā)方式可以把一個大程序分開成獨立的小 程序,提高軟件的成功率,也可以更加適合團(tuán)隊一起開發(fā),加快軟件的開發(fā)速度。下面就來使用文件映射的方式進(jìn)行共享數(shù)據(jù)。先要使用函數(shù) CreateFileMapping來創(chuàng)建一個想共享的文件數(shù)據(jù)句柄,然后使用MapViewOfFile來獲取共享的內(nèi)存地址,然后使用 OpenFileMapping函數(shù)在另一個進(jìn)程里打開共享文件的名稱,這樣就可以實現(xiàn)不同的進(jìn)程共享數(shù)據(jù)。?
??
函數(shù)CreateFileMapping、MapViewOfFile聲明如下:?
WINBASEAPI?
__out?
HANDLE?
WINAPI?
CreateFileMappingA(?
????__in?????HANDLE?hFile,?
????__in_opt?LPSECURITY_ATTRIBUTES?lpFileMappingAttributes,?
????__in?????DWORD?flProtect,?
????__in?????DWORD?dwMaximumSizeHigh,?
????__in?????DWORD?dwMaximumSizeLow,?
????__in_opt?LPCSTR?lpName?
????);?
WINBASEAPI?
__out?
HANDLE?
WINAPI?
CreateFileMappingW(?
????__in?????HANDLE?hFile,?
????__in_opt?LPSECURITY_ATTRIBUTES?lpFileMappingAttributes,?
????__in?????DWORD?flProtect,?
????__in?????DWORD?dwMaximumSizeHigh,?
????__in?????DWORD?dwMaximumSizeLow,?
????__in_opt?LPCWSTR?lpName?
????);?
#ifdef?UNICODE?
#define?CreateFileMapping?CreateFileMappingW?
#else?
#define?CreateFileMapping?CreateFileMappingA?
#endif?//?!UNICODE?
??
WINBASEAPI?
__out?
LPVOID?
WINAPI?
MapViewOfFile(?
????__in?HANDLE?hFileMappingObject,?
????__in?DWORD?dwDesiredAccess,?
????__in?DWORD?dwFileOffsetHigh,?
????__in?DWORD?dwFileOffsetLow,?
????__in?SIZE_T?dwNumberOfBytesToMap?
????);?
hFile是創(chuàng)建共享文件的句柄。?
lpFileMappingAttributes是文件共享的屬性。?
flProtect是當(dāng)文件映射時讀寫文件的屬性。?
dwMaximumSizeHigh是文件共享的大小高位字節(jié)。?
dwMaximumSizeLow是文件共享的大小低位字節(jié)。?
lpName是共享文件對象名稱。?
hFileMappingObject是共享文件對象。?
dwDesiredAccess是文件共享屬性。?
dwFileOffsetHigh是文件共享區(qū)的偏移地址。?
dwFileOffsetLow是文件共享區(qū)的偏移地址。?
dwNumberOfBytesToMap是共享數(shù)據(jù)長度。?
??
調(diào)用函數(shù)的例子如下:?
#001??//文件共享。?
#002??//蔡軍生?2007/10/27?QQ:9073204?深圳?
#003??void?FileMapping(void)?
#004??{?
#005?????????//打開共享的文件對象。?
#006?????????m_hMapFile?=?OpenFileMapping(FILE_MAP_ALL_ACCESS,?
#007??????????????FALSE,_T("TestFileMap"));?
#008?????????if?(m_hMapFile)?
#009?????????{?
#010???????????????//顯示共享的文件數(shù)據(jù)。?
#011??????????????LPTSTR?lpMapAddr?=?(LPTSTR)MapViewOfFile(m_hMapFile,FILE_MAP_ALL_ACCESS,?
#012???????????????????0,0,0);?
#013???????????????OutputDebugString(lpMapAddr);?
#014?????????}?
#015?????????else?
#016?????????{?
#017???????????????//創(chuàng)建共享文件。?
#018???????????????m_hMapFile?=?CreateFileMapping(?(HANDLE)0xFFFFFFFF,NULL,?
#019???????????????????PAGE_READWRITE,0,1024,_T("TestFileMap"));?
#020??
#021???????????????//拷貝數(shù)據(jù)到共享文件里。?
#022???????????????LPTSTR?lpMapAddr?=?(LPTSTR)MapViewOfFile(m_hMapFile,FILE_MAP_ALL_ACCESS,?
#023????????????????????0,0,0);?
#024???????????????std::wstring?strTest(_T("TestFileMap"));?
#025???????????????wcscpy(lpMapAddr,strTest.c_str());??????????????????
#026??
#027???????????????FlushViewOfFile(lpMapAddr,strTest.length()+1);?
#028?????????}?
#029??}?