tags:

views:

399

answers:

2

The function CreateFileMapping can be used to allocate space in the pagefile (if the first argument is INVALID_HANDLE_VALUE). The allocated space can later be memory mapped into the process virtual address space.

Why would I want to do this instead of using just VirtualAlloc?

It seems that both functions do almost the same thing. Memory allocated by VirtualAlloc may at some point be pushed out to the pagefile. Why should I need an API that specifically requests that my pages be allocated there in the first instance? Why should I care where my private pages live?

Is it just a hint to the OS about my expected memory usage patterns? (Ie, the former is a hint to swap out those pages more aggressively.)

Or is it simply a convenience method when working with very large datasets on 32-bit processes? (Ie, I can use CreateFileMapping to make >4Gb allocations, then memory map smaller chunks of the space as needed. Using the pagefile saves me the work of manually managing my own set of files to "swap" to.)

PS. This question is sparked by an article I read recently: http://blogs.technet.com/markrussinovich/archive/2008/11/17/3155406.aspx

+1  A: 

From the CreateFileMappingFunction:

A single file mapping object can be shared by multiple processes.

Can the Virtual memory be shared across multiple processes?

Kieveli
Ahh yes, bingo:http://msdn.microsoft.com/en-us/library/aa366551(VS.85).aspxI havn't had reason yet to use shared memory on Win32 so I wasn't aware that CreateFileMapping was the way to do it.
pauldoo
So does this mean that all shared memory in Win32 is allocated from the pagefile? What's wrong with normal physical memory allocations that get swapped when needed?
pauldoo
The memory model doesn't allow you to address memory that is in another process' memory space.
Kieveli
+1  A: 

One reason is to share memory among different processes. Different processes by only knowing the name of the mapping object can communicate over page file. This is preferable over creating a real file and doing the communications. Of course there may be other use cases. You can refer to Using a File Mapping for IPC at MSDN for more information.

Szere Dyeri