Windows core programming 17 memory ing File

Source: Internet
Author: User
Memory ing File Memory ing files can be used for three purposes: 1. Access to .exe or dll2 files through memory ing files to access files on the disk. 3. inter-process communication


1. Execute the program. EXE. Generally, the base address to load is 0x00400000, while the base address to load the DLL is 0x10000000.
2. Multiple instances of the same execution program or DLL do not share static data.
3. The Memory Page attribute used by EXE and DLL is copy-on-write.

How can I share static data in different instances of the same execution program or DLL? For example, you want to know that the same program runs multiple instances!
Use the segment information of the EXE file structure. "Shared" indicates that multiple instances in the shared segment are shared.
# Pragma data_seg ("shared ")
Volatile long g_lapplicationinstances = 0;
# Pragma data_seg ()

// Tell the linker to make the shared section readable, writable, and shared.
# Pragma comment (linker, "/section: shared, RWS ")

/******************************************************************************Module:  AppInst.cppNotices: Copyright (c) 2008 Jeffrey Richter & Christophe Nasarre******************************************************************************/#include "..\CommonFiles\CmnHdr.h"     /* See Appendix A. */#include <windowsx.h>#include <tchar.h>#include "Resource.h"///////////////////////////////////////////////////////////////////////////////// The system-wide window message, unique to the applicationUINT g_uMsgAppInstCountUpdate = WM_APP+123;///////////////////////////////////////////////////////////////////////////////// Tell the compiler to put this initialized variable in its own Shared // section so it is shared by all instances of this application.#pragma data_seg("Shared")volatile LONG g_lApplicationInstances = 0;#pragma data_seg()// Tell the linker to make the Shared section readable, writable, and shared.#pragma comment(linker, "/Section:Shared,RWS")///////////////////////////////////////////////////////////////////////////////BOOL Dlg_OnInitDialog(HWND hWnd, HWND hWndFocus, LPARAM lParam) {   chSETDLGICONS(hWnd, IDI_APPINST);   // Force the static control to be initialized correctly.   PostMessage(HWND_BROADCAST, g_uMsgAppInstCountUpdate, 0, 0);   return(TRUE);}///////////////////////////////////////////////////////////////////////////////void Dlg_OnCommand(HWND hWnd, int id, HWND hWndCtl, UINT codeNotify) {   switch (id) {      case IDCANCEL:         EndDialog(hWnd, id);         break;   }}///////////////////////////////////////////////////////////////////////////////INT_PTR WINAPI Dlg_Proc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {   if (uMsg == g_uMsgAppInstCountUpdate) {      SetDlgItemInt(hWnd, IDC_COUNT, g_lApplicationInstances, FALSE);   }   switch (uMsg) {      chHANDLE_DLGMSG(hWnd, WM_INITDIALOG, Dlg_OnInitDialog);      chHANDLE_DLGMSG(hWnd, WM_COMMAND,    Dlg_OnCommand);   }   return(FALSE);}///////////////////////////////////////////////////////////////////////////////int WINAPI _tWinMain(HINSTANCE hInstExe, HINSTANCE, PTSTR, int) {   // Get the numeric value of the systemwide window message used to notify    // all top-level windows when the module's usage count has changed.   g_uMsgAppInstCountUpdate =      RegisterWindowMessage(TEXT("MsgAppInstCountUpdate"));   // There is another instance of this application running   InterlockedExchangeAdd(&g_lApplicationInstances, 1);   DialogBox(hInstExe, MAKEINTRESOURCE(IDD_APPINST), NULL, Dlg_Proc);   // This instance of the application is terminating   InterlockedExchangeAdd(&g_lApplicationInstances, -1);   // Have all other instances update their display   PostMessage(HWND_BROADCAST, g_uMsgAppInstCountUpdate, 0, 0);   return(0);}//////////////////////////////// End of File //////////////////////////////////

2. Data Files mapped to memory
Use memory ing file 1 to create or open the file Kernel Object createfile to create or open a file. For details about the function, see msdn
2. Create a file ing memory object handle
Winapi
Createfilemappinga (
_ In handle hfile: The created file kernel object.
_ In_opt lpsecurity_attributes lpfilemappingattributes. The security attribute is generally null.
_ In DWORD flprotect to protect attributes
_ In DWORD dwmaximumsizehigh, the file size is high byte, the file is greater than 4 GB, need to use
_ In DWORD dwmaximumsizelow: the file size is low in bytes, which is equivalent to the file size. If both parameters are 0, the file size of the file kernel object is used.
_ In_opt lpcstr lpname: name of the ing object in the file, which can be shared among different processes.
);
3. Map the data of the file ing object to the process address space lpvoid
Winapi
Mapviewoffile (
_ In handle hfilemappingobject, // file ing Kernel Object
_ In DWORD dwdesiredaccess: access permission
_ In DWORD dwfileoffsethigh, file offset high byte
_ In DWORD dwfileoffsetlow, low byte, must be an integer multiple of 64 KB
_ In size_t dwnumberofbytestomap size of bytes to be mapped
);
Mapvieoffileex can be used when memory ing files are linked lists.

After the memory ing object is used up, it must be cleared and released. 1. Cancel the association bool unmapviewoffile (plvoid pvbaseaddress) from the process address space to the file ing object. The parameter is the address returned by mapviewoffile.
2 close file ing Kernel Object closehandle3 close file Kernel Object closehandle
Sample Code:
// Memorymapfile. CPP: defines the entry point for the console application. // # include <windows. h> # include <process. h> # include <tchar. h> int _ tmain (INT argc, _ tchar * argv []) {int Len = sizeof (tchar); handle hfile = createfile (text ("1.txt"), generic_read | generic_write, file_share_read | file_share_write, null, open_always, always, null); DWORD dwsize = getfilesize (hfile, null); // create a file ing memory handle hmapfile = createfilemapping (hfile, null, page_readwrite, 0, dwsize + 1, null); // create the lping view lpstr = (lpstr) mapviewoffile (hmapfile, file_map_all_access, 0, /* file pointer offset */0, 0/* use filesize */); lpstr [dwsize] = 0; _ strrev (lpstr); // refresh the view flushviewoffile (lpstr, 10 ); // disconnect view ing unmapviewoffile (lpstr); closehandle (hmapfile); setfilepointer (hfile, dwsize, null, file_begin); setendoffile (hfile); closehandle (hfile); Return 0 ;}

Share data with memory ing files in the process

Memory ing files with Page Swap files as memory
When createfilemapping is called, pass invalid_handle_value as the first parameter. The size is parameter 4 and parameter 5.

// Memorymapfile. CPP: defines the entry point for the console application. // # include <windows. h> # include <process. h> # include <tchar. h> # include <stdio. h> int _ tmain (INT argc, _ tchar * argv []) {const DWORD dwsize = 4*1024; // create a file ing memory handle hmapfile = createfilemapping (invalid_handle_value, null, page_readwrite, 0, dwsize, text ("111"); If (error_already_exists = getlasterror () {printf ("exists \ n "); hmapfile = openfilemapping (file_map_read | file_map_write, false, text ("111"); // create a pting view ptchar lpstr = (ptchar) mapviewoffile (hmapfile, file_map_all_access, 0, /* file pointer offset */0, 0/* use filesize */); printf ("% s \ n", lpstr); goto leave ;} // create the ing view ptchar lpstr = (ptchar) mapviewoffile (hmapfile, file_map_all_access, 0,/* file pointer offset */* use filesize */); _ tcscpy (lpstr, text ("123456"); // refresh the view flushviewoffile (lpstr, 10); leave: // disconnect the view ing unmapviewoffile (lpstr); getchar (); closehandle (hmapfile ); return 0 ;}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.