在Ring Buffer's Wikipedia entry上,example code显示UNIX系统的黑客行为,其中相邻的虚拟内存对于一块内存是mapped到相同的物理内存,从而实现一个环形缓冲区,不需要任何memcpy等。我想知道是否有办法在Windows中有类似的东西?
谢谢,弗雷泽
答案 0 :(得分:10)
我并没有真正遵循维基百科中的示例的所有细节。考虑到这一点,您使用CreateFileMapping和MapViewOfFile在Windows中映射内存,但MapViewOfFile不允许您为映射指定基址。 MapViewOfFileEx可用于指定基址,因此您可以使用类似的技术。
我无论如何都不知道这是否真的有效:
// determine valid buffer size
SYSTEM_INFO info;
GetSystemInfo(&info);
// note that the base address must be a multiple of the allocation granularity
DWORD bufferSize=info.dwAllocationGranularity;
HANDLE hMapFile = CreateFileMapping(
INVALID_HANDLE_VALUE,
NULL,
PAGE_READWRITE,
0,
bufferSize*2,
L"Mapping");
BYTE *pBuf = (BYTE*)MapViewOfFile(hMapFile,
FILE_MAP_ALL_ACCESS,
0,
0,
bufferSize);
MapViewOfFileEx(hMapFile,
FILE_MAP_ALL_ACCESS,
0,
0,
bufferSize,
pBuf+bufferSize);
答案 1 :(得分:5)
问题是,MapViewOfFileEx
有时会因ERROR_INVALID_ADDRESS而失败,这意味着它无法将视图映射到pBuf+bufferSize
。这是因为之前调用的MapViewOfFile
选择了bufferSize
长度的免费地址空间(从pBuf
开始),但它并不保证此地址空间长bufferSize*2
。为什么我们需要bufferSize*2
虚拟内存?因为我们的环形缓冲区需要包装。这是第二个映射视图的用途。当读或写指针离开第一个视图时,它进入第二个视图(因为它们在内存中是连续的),但实际上它在相同的映射中重新开始。
UINT_PTR addr;
HANDLE hMapFile;
LPVOID address, address2;
hMapFile = CreateFileMapping ( // create a mapping backed by a pagefile
INVALID_HANDLE_VALUE,
NULL,
PAGE_EXECUTE_READWRITE,
0,
bufferSize*2,
"Local\\mapping" );
if(hMapFile == NULL)
FAIL(CreateFileMapping);
address = MapViewOfFile ( // find a free bufferSize*2 address space
hMapFile,
FILE_MAP_ALL_ACCESS,
0,
0,
bufferSize*2 );
if(address==NULL)
FAIL(MapViewOfFile);
UnmapViewOfFile(address);
// found it. hopefully it'll remain free while we map to it
addr = ((UINT_PTR)address);
address = MapViewOfFileEx (
hMapFile,
FILE_MAP_ALL_ACCESS,
0,
0,
bufferSize,
(LPVOID)addr );
addr = ((UINT_PTR)address) + bufferSize;
address2 = MapViewOfFileEx (
hMapFile,
FILE_MAP_ALL_ACCESS,
0,
0,
bufferSize,
(LPVOID)addr);
if(address2==NULL)
FAIL(MapViewOfFileEx);
// when you're done with your ring buffer, call UnmapViewOfFile for
// address and address2 and CloseHandle(hMapFile)