2015-05-05 91 views
0

我想使我們的內存管理的端口,其中一些分配器使用虛擬內存機制預留的地址空間,而(開頭)分配任何物理內存,後來只有當他們分配內存需要。C++在OS移植VirtualFree X

該代碼是基於Windows的VirtualAlloc和VirtualFree使事情工作,現在我試圖將此代碼移植到Apple OS X,據我所知,沒有這樣的API,後而我想出下面的代碼:

//to reserve virtual address space 
//equivalent of VirtualAlloc(NULL, size, MEM_RESERVE, PAGE_NOACCESS) 
void* ptr = mmap(NULL, size, PROT_NONE, (MAP_PRIVATE | MAP_ANON), -1, 0); 
msync(ptr, size, (MS_SYNC | MS_INVALIDATE)); 

//to free ALL virtual address space 
//equivalent of VirtualFree(addr, 0, MEM_RELEASE) 
//where "size" is the size of the entire virtual address space and "addr" the starting address 
msync(addr, size, MS_SYNC); 
munmap(addr, size); 

//to allocate physical memory 
//equivalent of VirtualAlloc(addr, size, MEM_COMMIT, PAGE_READWRITE) 
void* ptr = mmap(addr, size, (PROT_READ | PROT_WRITE), (MAP_FIXED | MAP_SHARED | MAP_ANON), -1, 0); 
msync(addr, size, (MS_SYNC | MS_INVALIDATE)); 

我想不通的唯一的事情就是使用VirtualFree如何端口釋放/取消提交只有物理內存的一部分,模仿VirtualFree電話:

VirtualFree(addr, size, MEM_DECOMMIT); 

我試圖調用munmap與所需的地址和大小,但它不釋放內存......同時調用它來完全釋放所有虛擬空間。

有人可以幫助我在這個任務?

+1

你移植到Linux或OS X?請相應地更改標籤。因爲看起來'MADV_REMOVE'符合你的需要,但是它是Linux特有的標誌。 – myaut

+0

我正在移植到OS X,標記已更改:) – Daniel

回答

1

我發現我自己的問題感謝的回答了這個博客: http://blog.nervus.org/managing-virtual-address-spaces-with-mmap/

我還張貼在這裏他的情況下,溶液中的鏈接死:

void DecommitMemory(void* addr, size_t size) 
{ 
    // instead of unmapping the address, we're just gonna trick 
    // the TLB to mark this as a new mapped area which, due to 
    // demand paging, will not be committed until used. 

    mmap(addr, size, PROT_NONE, MAP_FIXED|MAP_PRIVATE|MAP_ANON, -1, 0); 
    msync(addr, size, MS_SYNC|MS_INVALIDATE); 
}