Windows core programming code analysis based on Visual C ++ (22) Mapping File Programming

Source: Internet
Author: User

Mapping is a technology that maps file content to the virtual address space of a process. A view is a virtual address space. A process can use a view to access the content of a file. A view is a piece of memory and can use a pointer to operate the view. After file ing is used, reading and writing files is as simple as reading and writing memory. When using file ing, you need to create a ing object. The ing object is divided into named and unnamed. The ing object also has access permissions.

There are at least three advantages of using file ing. One is because the file storage is on the hard disk, while the file view is a piece of memory, which makes it easier to use file ing. The other is higher efficiency; third, data can be shared between different processes.

File ing depends on the paging mechanism of System Virtual Memory Management.

Key APIs

Getsysteminfo

Obtain system information, which is used in subsequent instances to obtain the system memory allocation granularity.

Createfilemapping

Create a mapping object. The function prototype is as follows:/X should be the kernel object for creating a file ing/

Createfilemapping (

Handle hfile,

Lpsecurity_attributes lpattributes,

DWORD dwmaximumsizehigh,

DWORD dwmaximumsizelow,

Lptstr lpname

);

Parameters

Hfile: Enter the file handle of the file to be mapped created by createfile.

Lpattributes: the input parameter pointing to the security_attributes structure pointer. Generally, use the default attribute to assign this parameter to null.

Flprotect: input parameter, memory protection attribute, which can be page_readonly, page_readwrite, page_writecopy, page_execute_read, and page_execute_readwrite. You can also use bitwise OR operations to append the following attributes: security_attributes, sec_commit, sec_image, sec_large_pages, sec_nocache, and sec_reserve.

Dwmaximumsizehigh: The 32-bit high of the maximum ing size.

Dwmaximumsizelow: input parameter, which is 32-bit lower than the maximum ing size.

Lpname: input parameter, ing object name, which can be null.

Return Value:

Returns the handle value and the ing object handle. If the return value is null, the operation fails. You can use the getlasterror function to obtain error information.

Mapviewoffile

Create a view and map the file ing to the virtual memory address space of the current process. The function prototype is as follows:

Lpvoid mapviewoffile (

Handle hfilemappingobject,

DWORD dwdesiredaccess,

DWORD dwfileoffsethigh,

DWORD dwfileoffsetlow,

Size_t dwnumberofbytestomap

);

Parameters

Hfilemappingobject: the handle of the input data and file mapping object, which is returned by the createfilemapping function or openfilemapping function.

Dwdesiredaccess: input parameter, access type, which can be file_map_write, file_map_read, file_map_copy, and file_map_execute.

Dwfileoffsethigh: The 32-bit height of the mapped file offset.

Dwfileoffsetlow: input parameter, which is a 32-bit low offset of the mapped file.

Dwnumberofbytestomap: number of bytes mapped to view by the input parameter.

Return Value:

Returns the lpvoid value pointing to the mapped memory value. If it is null, it indicates an error.

Flushviewoffile

Write the file data in the view to the disk. After this parameter is called, memory operations on the ing view will be promptly reflected to files on the hard disk. The function prototype is as follows:

Bool flushviewoffile (

Lpvoid lpbaseaddress,

Size_t dwnumberofbytestoflush

);

Parameters

Lpbaseaddress: Enter the parameter, which is the starting position of the data to be written to the file.

Dwnumberofbytestoflush: number of bytes written by the input parameter. If it is 0, the entire view is written back.

Return Value:

Returns the bool value, indicating whether it is successful.

Instructions for use

If you do not call this function, the data will eventually be written back to the hard disk. After you call this function, the data will be immediately written back to the hard disk.

Fillmemory and copymemory. Memory operation functions: Memory filling and replication memory.

 

Example of improving file read/write efficiency using Mapping File

/* Header file */<br/> # include <windows. h> <br/> # include <stdio. h> <br/>/* pre-statement */<br/> # define buffsize 1024 // memory size <br/> # define file_map_start 0x28804 // start of file ing location <br/>/* global variable */<br/> lptstr lpcthefile = text ("test. dat "); // file name </P> <p> /***************************** * ******* <br/> * int main (void) <br/> * function demonstration file mapping <br/> * No parameter <br/> * If the return value is 0, the execution is complete, 1 indicates an error <br/> ***************************** * ********/<Br/> int main (void) <br/>{< br/> handle hmapfile; // handle of the File Memory ing area <br/> handle hfile; // file handle <br/> DWORD dbyteswritten; // number of written bytes <br/> DWORD dwfilesize; // file size <br/> DWORD dwfilemapsize; // file ing size <br/> DWORD dwmapviewsize; // View Size <br/> DWORD dwfilemapstart; // start position of the file ing view <br/> DWORD dwsysgran; // granularity of system memory allocation <br/> system_info sysinfo; // System Information <br/> lpvoid lpmapaddress; // start position of the inner ing area <Br/> pchar pdata; // data <br/> int I; // cyclic variable <br/> int idata; <br/> int iviewdelta; <br/> byte cmapbuffer [32]; // store the data counted from mapping </P> <p> // create a file <br/> hfile = createfile (lpcthefile, <br/> generic_read | generic_write, <br/> 0, <br/> null, <br/> create_always, <br/> file_attribute_normal, <br/> null ); <br/> // determine whether the file is successfully created <br/> If (hfile = invalid_handle_value) <br/>{< br/> printf ("createfile error \ n ", getlasterr Or); <br/> return 1; <br/>}< br/> // write integers in sequence, A total of 65535 integers are written <br/> // on a 32-bit platform, the size is 65535*32 <br/> for (I = 0; I <65535; I ++) <br/>{< br/> writefile (hfile, & I, sizeof (I), & dbyteswritten, null ); <br/>}< br/> // view the file size after writing <br/> dwfilesize = getfilesize (hfile, null ); <br/> printf ("file size: % d \ n", dwfilesize); </P> <p> // obtain system information, memory allocation granularity <br/> // obtain the allocation granularity and perform the following calculations. <br/> // The purpose is to align the ing data with the system memory allocation granularity, improves memory access efficiency <br/> getsysteminfo (& Sys Info); <br/> dwsysgran = sysinfo. dwallocationgranularity; </P> <p> // start position of mapping calculation <br/> dwfilemapstart = (file_map_start/dwsysgran) * dwsysgran; <br/> // calculate the Mapping View Size <br/> dwmapviewsize = (file_map_start % dwsysgran) + buffsize; <br/> // calculate the mapping size <br/> dwfilemapsize = file_map_start + buffsize; <br/> // calculate the offset of the data to be read <br/> iviewdelta = file_map_start-dwfilemapstart; </P> <p> // create file mapping <br /> Hmapfile = createfilemapping (hfile, // handle of the file to be mapped <br/> null, // Security Options: Default <br/> page_readwrite, // readable, writable <br/> 0, // mapping object size, high <br/> dwfilemapsize, // mapping object size, low <br/> null ); // mapping object name <br/> If (hmapfile = NULL) <br/>{< br/> printf ("createfilemapping error: % d \ n ", getlasterror (); <br/> return 1; <br/>}</P> <p> // view ing view <br/> lpmapaddress = mapviewoffile (hmapfile, // handle of the Mapping object <br/> F Ile_map_all_access, // readable, writable <br/> 0, // ing file offset, high 32-bit <br/> dwfilemapstart, // ing file offset, low 32-bit <br/> dwmapviewsize); // data size mapped to the view <br/> If (lpmapaddress = NULL) <br/>{< br/> printf ("mapviewoffile error: % d \ n", getlasterror (); <br/> return 1; <br/>}</P> <p> printf ("start position of the map View File relative to the file: 0x % x \ n", <br/> dwfilemapstart ); <br/> printf ("file map view size: 0x % x \ n", dwmapviewsize); <br/> printf ("file mapping object size: 0x % x \ N ", dwfilemapsize); <br/> printf (" reads data from the position relative to map view 0x % x bytes, ", iviewdelta ); </P> <p> // offset the pointer pointing to the data to the point we care about <br/> pdata = (pchar) lpmapaddress + iviewdelta; <br/> // read data and assign the value to the variable <br/> idata = * (pint) pdata; <br/> // display the read data <br/> printf (": 0x %. 8x \ n ", idata); </P> <p> // copy data from ing, 32 bytes, and print <br/> copymemory (cmapbuffer, lpmapaddress, 32); <br/> printf ("the starting 32 bytes of lpmapaddress are:"); <br/> for (I = 0; I <32; I ++) <br/> {<Br/> printf ("0x %. 2x ", cmapbuffer [I]); <br/>}< br/> // fill the first 32 bytes of mapping with 0xff <br/> fillmemory (lpmapaddress, 32, (byte) 0xff); <br/> // write the ing data back to the hard disk <br/> flushviewoffile (lpmapaddress, dwmapviewsize ); <br/> printf ("\ n has filled 32 bytes starting with lpmapaddress with 0xff. \ N "); </P> <p> // close the mapping object <br/> If (! Closehandle (hmapfile) <br/>{< br/> printf ("\ nclosing the mapping object error % d! ", <Br/> getlasterror (); <br/>}< br/> // close the file <br/> If (! Closehandle (hfile) <br/>{< br/> printf ("\ nerror % LD occurred closing the file! ", <Br/> getlasterror (); <br/>}</P> <p> return 0; <br/>}

 

Use Mapping File to share memory between processes

 

/* Header file */<br/> # include <windows. h> <br/> # include <stdio. h> <br/> # include <conio. h> <br/>/* pre-statement */<br/> # define buf_size 256 <br/>/* global variable */<br/> lptstr szname = text (" sharedfilemappingobject "); <br/> lptstr szmsg = text ("process message "); </P> <p> /******************************** * ***** <br/> * int main (void) <br/> * function demo file mapping shared memory, write Data to shared memory <br/> * No parameter <br/> * return value 0 indicates that the execution is complete, indicates an error <br/> *********** * *************************/<Br/> void main (INT argc, pchar argv []) <br/>{< br/> // file ing handle <br/> handle hmapfile; <br/> // share data buffer pointer <br/> lptstr pbuf; <br/> // create a named file ing, does not represent files on the task hard disk <br/> hmapfile = createfilemapping (<br/> invalid_handle_value, <br/> null, <br/> page_readwrite, <br/> 0, <br/> buf_size, <br/> szname); <br/> If (hmapfile = NULL | hmapfile = invalid_handle_value) <br/>{< br/> printf ("createfilem Apping error: % d \ n ", getlasterror (); <br/> return; <br/>}< br/> // create a view <br/> pbuf = (lptstr) mapviewoffile (hmapfile, <br/> file_map_all_access, <br/> 0, <br/> 0, <br/> buf_size); <br/> If (pbuf = NULL) <br/>{< br/> printf ("mapviewoffile error % d \ n", getlasterror (); <br/> return; <br/>}< br/> // copy the shared data to the file ing. If a parameter is entered during running, use the parameter <br/> If (argc = 1) <br/>{< br/> copymemory (pvoid) pbuf, szmsg, strlen (szmsg); <br/>} <Br/> else <br/> {<br/> DWORD dwcopylen = (lstrlen (argv [1]) <buf_size )? Lstrlen (argv [1]): buf_size; <br/> copymemory (pvoid) pbuf, argv [1], dwcopylen ); <br/>}< br/> printf ("Run <SPAN class = 'wp _ keywordlink '> Program </span>. After the program is run, press any key to exit. "); <Br/> _ getch (); <br/> // cancel the ing and exit <br/> unmapviewoffile (pbuf); <br/> closehandle (hmapfile ); <br/>}

using mapping file to share memory between processes

# Include <windows. h> <br/> # include <stdio. h> <br/> # include <conio. h> <br/>/* pre-statement */<br/> # pragma comment (Lib, "user32.lib ") <br/> # define buf_size 256 <br/>/* global variable */<br/> tchar szname [] = text ("sharedfilemappingobject "); </P> <p> /******************************** * ***** <br/> * int main (void) <br/> * function demo file mapping shared memory, read Information from shared data <br/> * No parameter <br/> * return value 0 indicates execution is complete, indicates an error <br/> ********************************* * *****/<br/> void main () <br/>{< br/> handle hmapfile; <br/> lptstr pbuf; <br/> // open the file mapping <br/> hmapfile = openfilemapping (<br/> file_map_all_access, <br/> false, <br/> szname ); <br/> If (hmapfile = NULL) <br/>{< br/> printf ("openfilemapping error: % d. \ n ", getlasterror (); <br/> return; <br/>}< br/> // ing <br/> pbuf = mapviewoffile (hmapfile, <br/> file_map_all_access, <br/> 0, <br/> 0, <br/> buf_size); <br/> If (pbuf = NULL) <br/>{< br/> printf ("mapviewoffile error % d \ n", getlasterror (); <br/> return; <br/>}< br/> // shared data obtained from the message <br/> MessageBox (null, pbuf, text ("process2"), mb_ OK ); <br/> // cancel mapping, close the handle, and return <br/> unmapviewoffile (pbuf); <br/> closehandle (hmapfile); <br/>}

 

 

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.