На главную

On-line справка по Win32 API

Написать письмо
БЕСПЛАТНАЯ ежедневная online лотерея! Выигрывай каждый день БЕСПЛАТНО!
Список всех статей A-B-C-D-E-F-G-H-I-J-K-L-M-N-O-P-Q-R-S-T-U-V-W-X-Y-Z | Скачать Вниз

MapViewOfFileEx



The MapViewOfFileEx function maps a view of a file into the address space of the calling process. This extended function allows the calling process to specify a suggested memory address for the mapped view.

This function is available for Win32-based applications only.

LPVOID MapViewOfFileEx(

HANDLE hFileMappingObject, // file-mapping object to map into address space
DWORD dwDesiredAccess, // access mode
DWORD dwFileOffsetHigh, // high-order 32 bits of file offset
DWORD dwFileOffsetLow, // low-order 32 bits of file offset
DWORD dwNumberOfBytesToMap, // number of bytes to map
LPVOID lpBaseAddress // suggested starting address for mapped view
);


Parameters

hFileMappingObject

Identifies an open handle to a file-mapping object. The CreateFileMapping and OpenFileMapping functions return this handle.

dwDesiredAccess

Specifies the type of access to the file-mapping object and, therefore, the page protection of the pages mapped by the file. This parameter can be one of the following values:

Value Meaning
FILE_MAP_WRITE Read-and-write access. The hFileMappingObject parameter must have been created with PAGE_READWRITE protection. A read-write view of the file is mapped.
FILE_MAP_READ Read-only access. The hFileMappingObject parameter must have been created with PAGE_READWRITE or PAGE_READONLY protection. A read-only view of the file is mapped.
FILE_MAP_ALL_ACCESS Same as FILE_MAP_WRITE.
FILE_MAP_COPY Copy on write access. If you create the map with PAGE_WRITECOPY and the view with FILE_MAP_COPY, you will receive a view to the file. If you write to it, the pages are automatically swappable and the modifications you make will not go to the original data file.Windows 95: You must pass PAGE_WRITECOPY to CreateFileMapping; otherwise, an error will be returned.If you share the mapping between multiple processes using DuplicateHandle or OpenFileMapping and one process writes to a view, the modification is propagated to the other process. The original file does not change.Windows NT: There is no restriction as to how the hFileMappingObject parameter must be created. Copy on write is valid for any type of view. If you share the mapping between multiple processes using DuplicateHandle or OpenFileMapping and one process writes to a view, the modification is not propagated to the other process. The original file does not change.


dwFileOffsetHigh

Specifies the high-order 32 bits of the file offset where mapping is to begin.

dwFileOffsetLow

Specifies the low-order 32 bits of the file offset where mapping is to begin. The combination of the high and low offsets must specify an offset within the file that matches the system's memory allocation granularity, or the function fails. That is, the offset must be a multiple of the allocation granularity. Use the GetSystemInfo function, which fills in the members of a SYSTEM_INFO structure, to obtain the system's memory allocation granularity.

dwNumberOfBytesToMap

Specifies the number of bytes of the file to map. If dwNumberOfBytesToMap is zero, the entire file is mapped.

lpBaseAddress

Points to the memory address in the calling process's address space where mapping should begin. This must be a multiple of the system's memory allocation granularity, or the function fails. Use the GetSystemInfo function, which fills in the members of a SYSTEM_INFO structure, to obtain the system's memory allocation granularity. If there is not enough address space at the specified address, the function fails.
If lpBaseAddress is NULL, the operating system chooses the mapping address. In this case, this function is equivalent to the MapViewOfFile function.



Return Values

If the function succeeds, the return value is the starting address of the mapped view.
If the function fails, the return value is NULL. To get extended error information, call GetLastError.

Remarks

Mapping a file makes the specified portion of the file visible in the address space of the calling process.
If a suggested mapping address is supplied, the file is mapped at the specified address (rounded down to the nearest 64K boundary) if there is enough address space at the specified address. If there is not, the function fails.
Typically, the suggested address is used to specify that a file should be mapped at the same address in multiple processes. This requires the region of address space to be available in all involved processes. No other memory allocation, including use of the VirtualAlloc function to reserve memory, can take place in the region used for mapping.

Windows 95: If the lpBaseAddress parameter specifies a base offset, the function succeeds only if the same memory region is available for the memory mapped file in all other 32-bit processes.
Windows NT: If the lpBaseAddress parameter specifies a base offset, the function succeeds if the given memory region is not already in use by the calling process. the system does not guarantee that the same memory region is available for the memory mapped file in other 32-bit processes.

Multiple views of a file (or a file-mapping object and its mapped file) are said to be "coherent" if they contain identical data at a specified time. This occurs if the file views are derived from the same file-mapping object. A process can duplicate a file-mapping object handle into another process by using the DuplicateHandle function, or another process can open a file-mapping object by name by using the OpenFileMapping function.
A mapped view of a file is not guaranteed to be coherent with a file being accessed by the ReadFile or WriteFile function.

See Also

CreateFileMapping, DuplicateHandle, GetSystemInfo, MapViewOfFile, OpenFileMapping, ReadFile, UnmapViewOfFile, SYSTEM_INFO, VirtualAlloc
, WriteFile


Пригласи друзей и счет твоего мобильника всегда будет положительным!
Предыдущая статья
 
Сайт Народ.Ру Интернет
Следующая статья
Пригласи друзей и счет твоего мобильника всегда будет положительным!

MapViewOfFileEx



Функция MapViewOfFileEx отображает вид файла в пространство адреса вызова процесса. Эта расширенная функция позволяет вызов процесса, чтобы определять предложенный адрес памяти для отображенного вида.

Эта функция доступна для базирующихся приложений Win32 только.

LPVOID MapViewOfFileEx(

РУЧКА hFileMappingObject, // файловое-распределение возражают против карты в пространство адреса DWORD dwDesiredAccess, // способа доступа DWORD dwFileOffsetHigh, // старшие 32 бита файловой компенсации DWORD dwFileOffsetLow, // младшие 32 бита файловой компенсации DWORD dwNumberOfBytesToMap, // количества байтов, чтобы отображать предложенный запуск адреса LPVOID lpBaseAddress // для отображенного вида
);


Параметры

hFileMappingObject

Идентифицирует открытую ручку в файловое распределение объекта. CreateFileMapping И возврат функций OpenFileMapping этой ручки.

dwDesiredAccess

Определяет тип доступа к файловому распределению объекта и, следовательно, страничная защита страниц отображалась файлом. Этот параметр может быть одним из следующего величин:

Значение Величины
FILE_MAP_WRITE был Прочитан-и-доступ записи. Параметр hFileMappingObject по-видимому создан защитой PAGE_READWRITE. Чтение-запись вида файла отображено.
Только для чтения доступ FILE_MAP_READ. Параметр hFileMappingObject по-видимому создан PAGE_READWRITE или защитой PAGE_READONLY. Только для чтения вид файла отображен.
FILE_MAP_ALL_ACCESS Также, как FILE_MAP_WRITE.
Копия FILE_MAP_COPY в писать доступе. Если Вы создаете карту с PAGE_WRITECOPY и видом с FILE_MAP_COPY, Вы получите вид в файл. Если Вы записываете этому, страницы являются автоматически swappable и модификациями, которыми Вы делаете, не пойдет в оригинальный файл данных.Windows 95: Вы должны передать PAGE_WRITECOPY на CreateFileMapping; в противном случае, ошибка будет возвращана.Если Вы распространяете распределение между многочисленными процессами, использовавшими DuplicateHandle или OpenFileMapping и один процесс записывается в вид, модификация распространиться в другой процесс. Оригинальный файл не изменяется.Windows NT: Нет ограничения как то как параметр hFileMappingObject должен быть создан. Копия в записи - в силе для любого типа вида. Если Вы распространяете распределение между многочисленными процессами, использовавшими DuplicateHandle или OpenFileMapping и один процесс записывается в вид, модификация не распространиться в другой процесс. Оригинальный файл не изменяется.


dwFileOffsetHigh

Определяет старшие 32 бита файлового смещения где распределение должно начинаться.

dwFileOffsetLow

Определяет младшие 32 бита файлового смещения где распределение должно начинаться. Комбинация высокого и низкого смещений должна определить смещение в пределах файла, который соответствует степени детализации распределения системной памяти, или функция терпит неудачу. То есть, смещение должно быть кратным степени детализации распределения. Используйте функцию GetSystemInfo, которая заполняет участников структуры SYSTEM_INFO, чтобы получать степень детализации распределения системной памяти.

dwNumberOfBytesToMap

Определяет количество байтов файла, чтобы отображаться. Если dwNumberOfBytesToMap - нуль, целый файл отображен.

lpBaseAddress

Точки на адрес памяти в пространстве адреса процесса вызова где распределение должно начинаться. Это должно быть кратным степени детализации распределения системной памяти, или функция терпит неудачу. Используйте функцию GetSystemInfo, которая заполняет участников структуры SYSTEM_INFO, чтобы получать степень детализации распределения системной памяти. Если нет достаточно пространства адреса по определенному адресу, функция терпит неудачу.
Если lpBaseAddress НЕДЕЙСТВИТЕЛЕН, операционная система выбирает распределение адреса. В этом случае, эта функция является эквивалентом функции MapViewOfFile.



Обратные Величины

Если функция добивается успеха, обратная величина является стартовым адресом отображенного вида.
Если функция терпит неудачу, обратная величина НЕДЕЙСТВИТЕЛЬНА. Для того, чтобы расширять информацию ошибки, назовите GetLastError.

Замечания

Распределение файла делает определенной частью файла видимой в пространстве адреса вызова обрабатываться.
Если предложенное распределение адреса поставлено, файл отображен по определенному адресу (округленное в меньшую сторону на ближайшую границу 64K) если есть достаточно пространства адреса по определенному адресу. Если нет, функция терпит неудачу.
Обычно, предложенный адрес использован, чтобы определять, что файл будет отображен по тому же адресу во многочисленных процессах. Это требует область пространства адреса, чтобы быть доступно во всех включившее процессы. Никакое другое распределение памяти, включая использование функции VirtualAlloc, чтобы резервировать память, может произойти в области использованной для распределения.

Windows 95: Если параметр lpBaseAddress определяет базовое смещение, функция добивается успеха только если та же область памяти доступна для памяти отобразившей файл во всех других 32- битовых процессах.
Windows NT: Если параметр lpBaseAddress определяет базовое смещение, функция добивается успеха если данная область памяти - не уже в использовании вызовом process. система не гарантирует, что та же область памяти доступна для памяти отобразившей файл в других 32- битовых процессах.

Многочисленные виды файла (или файловое-распределение объектный и отображенный файл) говорят, что быть "когерентными" если они содержат идентичные данные в определенном времени. Это происходит если файловые виды производные от того же файлового распределения объекта. Процесс может продублировать файловую-объектную ручку распределения в другой процесс используя функцию DuplicateHandle, или другой процесс может открыть файловое распределение объекта по имени используя функцию OpenFileMapping.
Отображенный вид файла не гарантирован, чтобы быть когерентным с доступным файлом ReadFile или функция WriteFile.

Смотри Также

CreateFileMapping, DuplicateHandle, GetSystemInfo, MapViewOfFile, OpenFileMapping, ReadFile, UnmapViewOfFile, SYSTEM_INFO, VirtualAlloc , WriteFile


Вверх Version 1.3, Oct 26 2010 © 2007, 2010, mrhx Вверх
 mrhx software  Русский перевод OpenGL  Русский перевод Win32 API
 
Используются технологии uCoz