测试创建和打开文件映射的时候老是得到"句柄无效"的错误, 仔细看了MSDN以后才发觉是函数认识不透, 这里把相关的解释翻译出来
HANDLE CreateFileMapping(
HANDLE hFile, //物理文件句柄
LPSECURITY_ATTRIBUTES lpAttributes, //安全设置
DWORD flProtect, //保护设置
DWORD dwMaximumSizeHigh, //高位文件大小
DWORD dwMaximumSizeLow, //低位文件大小
LPCTSTR lpName //共享内存名称
);
1) 物理文件句柄
任何可以获得的物理文件句柄, 如果你需要创建一个物理文件无关的内存映射也无妨, 将它设置成为 0xFFFFFFFF(INVALID_HANDLE_VALUE)就可以了.
如果需要和物理文件关联, 要确保你的物理文件创建的时候的访问模式和"保护设置"匹配, 比如: 物理文件只读, 内存映射需要读写就会发生错误. 推荐你的物理文件使用独占方式创建.
如果使用 INVALID_HANDLE_VALUE, 也需要设置需要申请的内存空间的大小, 无论物理文件句柄参数是否有效, 这样 CreateFileMapping 就可以创建一个和物理文件大小无关的内存空间给你, 甚至超过实际文件大小, 如果你的物理文件有效, 而大小参数为0, 则返回给你的是一个和物理文件大小一样的内存空间地址范围. 返回给你的文件映射地址空间是可以通过复制, 集成或者命名得到, 初始内容为0.
2) 保护设置
就是安全设置, 不过一般设置NULL就可以了, 使用默认的安全配置. 在win2k下如果需要进行限制, 这是针对那些将内存文件映射共享给整个网络上面的应用进程使用是, 可以考虑进行限制.
3) 高位文件大小
弟兄们, 我想目前我们的机器都是32位的东东, 不可能得到超过32位进程所能寻址的私有32位地址空间, 一般还是设置0吧, 我没有也不想尝试将它设置超过0的情况.
4) 低位文件大小
这个还是可以进行设置的, 不过为了让其他共享用户知道你申请的文件映射的相关信息, 我使用的时候是在获得的地址空间头部添加一个结构化描述信息, 记录内存映射的大小, 名称等, 这样实际申请的空间就比输入的增加了一个头信息结构大小了, 我认为这样类似BSTR的方式应该是比较合理的.
5) 共享内存名称
这个就是我今天测试的时候碰壁的祸根, 因为为了对于内存进行互斥访问, 我设置了一个互斥句柄, 而名称我选择和命名共享内存同名, 之下就是因为他们使用共同的namespace导致了错误, 呵呵.
7) 调用CreateFileMapping的时候GetLastError的对应错误
ERROR_FILE_INVALID 如果企图创建一个零长度的文件映射, 应有此报
ERROR_INVALID_HANDLE 如果发现你的命名内存空间和现有的内存映射, 互斥量, 信号量, 临界区同名就麻烦了
ERROR_ALREADY_EXISTS 表示内存空间命名已经存在
8) 相关服务或者平台的命名保留
Terminal Services:
命名可以包含 "Global" 或者 "Local" 前缀在全局或者会话名空间初级文件映射. 其他部分可以包含任何除了()以外的字符, 可以参考 Kernel Object Name Spaces.
Windows 2000 or later:
如果 Terminal Services 没有运行 "Global" 和 "Local" 前缀的特殊含义就被忽略了
相关映射代码
Code
var
Form1: TForm1;
Data: Pointer; // holds a pointer to the memory mapped file
hMapping: THandle; // holds a handle to the memory mapped file object
implementation
function OpenMappedFile(FileName: string; var FileSize: DWORD): Boolean;
var
hFile: THandle; // a handle to the opened file
HighSize: DWORD; // the high order double word of the file size
begin
{initialize the result of the function in case of errors}
Result := FALSE;
{if no filename was specified, exit}
if Length(FileName) = 0 then
Exit;
{open the file for reading and writing. indicate a
sequential scan access for better optimization}
hFile := CreateFile(PChar(FileName), GENERIC_READ or GENERIC_WRITE,
FILE_SHARE_READ, nil, OPEN_EXISTING,
FILE_FLAG_SEQUENTIAL_SCAN, 0);
{if the file was not opened, exit;}
if hFile = INVALID_HANDLE_VALUE then
Exit;
{retrieve the size of the file}
FileSize := GetFileSize(hFile, @HighSize);
{create a read/write mapping of the opened file}
hMapping := CreateFileMapping(hFile, nil, PAGE_READWRITE, 0, 0,
'Delphi File Mapping Example');
{if the file mapping failed, exit}
if (hMapping = 0) then
begin
CloseHandle(hFile);
Exit;
end;
{close the file handle, as we no longer need it}
CloseHandle(hFile);
{map a view of the file}
Data := MapViewOfFile(hMapping, FILE_MAP_WRITE, 0, 0, 0);
{if a view of the file was not created, exit}
if (Data = nil) then
Exit;
{to insure that the file's data can be displayed directly as
a string, set the very last byte in the file data to a null terminator}
PChar(Data)[FileSize] := #0;
{the file was successfully opened and mapped}
Result := TRUE;
end;
function OpenPreviousMappedFile(var FileSize: Integer): Boolean;
begin
{initialize the result of the function incase of errors}
Result := FALSE;
{open an existing file mapping}
hMapping := OpenFileMapping(FILE_MAP_WRITE, FALSE,
'Delphi File Mapping Example');
{if there was an error opening the existing file mapping, exit}
if hMapping = 0 then
Exit;
{map a view of the file}
Data := MapViewOfFile(hMapping, FILE_MAP_WRITE, 0, 0, 0);
{if a view of the file was not created, exit}
if (Data = nil) then
Exit;
{retrieve the length of the data (which can be represented as a null
terminated string due to adding the null terminator to the end when
the file was opened}
FileSize := StrLen(PChar(Data));
{indicate that the file was successfully opened and mapped}
Result := TRUE;
end;
procedure DisplayMappedFile(FileName: string; Size: Integer);
var
Index: Integer; // general loop counter
DataPtr: PChar; // a pointer to the mapped file data
HexString: PChar; // a pointer to a concatenated hexadecimal string
begin
{display the name of the mapped file}
Form1.StatusBar1.SimpleText := FileName;
{allocate memory for the hexadecimal representation of the file,
and initialize it to zeros}
GetMem(HexString, Size * 3);
ZeroMemory(HexString, Size * 3);
{set the pointer to the beginning of the mapped file data}
DataPtr := Data;
{begin looping through the data}
Index := 0;
while (Index < Size) do
begin
{display the value of each byte in the file as a hexadecimal number}
StrCat(HexString, PChar(IntToHex(Byte(DataPtr[Index]), 2) + ' '));
Inc(Index);
end;
{display the hexadecimal representation of the data and the ASCII
representation of the data}
SetWindowText(Form1.Memo1.Handle, HexString);
SetWindowText(Form1.Memo2.Handle, PChar(Data));
{free the memory for the hexadecimal string}
FreeMem(HexString, Size * 3);
end;
procedure TForm1.Button1Click(Sender: TObject);
var
Size: Integer; // holds the size of the memory mapped file
begin
{open an existing file}
if OpenDialog1.Execute then
begin
{map the file}
OpenMappedFile(OpenDialog1.FileName, Size);
{and display the memory mapped file}
DisplayMappedFile(OpenDialog1.FileName, Size);
end;
end;
procedure TForm1.Button3Click(Sender: TObject);
var
Size: Integer; // holds the size of the memory mapped file
begin
{open a previously mapped file}
if OpenPreviousMappedFile(Size) then
{and display it}
DisplayMappedFile('Existing mapped file', Size);
end;
procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction);
begin
{write any changes to the file}
FlushViewOfFile(Data, 0);
{unmap the view of the file}
if not UnMapViewOfFile(Data) then
ShowMessage('Can not unmap file');
{close the mapped file handle}
if not CloseHandle(hMapping) then
ShowMessage('Can not Close File');
end;