[b]uses[/b] windows,sysutils;
[b]type[/b]
TcsMMFDemo = [b]class[/b](TObject)
[b]private[/b]
FdwReadSize : DWORD;
FdwPosition : DWORD;
FszBuffer : PChar;
FdwFileSize : DWORD;
[b]procedure[/b] SetPosition([b]const[/b] Value: DWORD);
[b]public[/b]
[b]constructor[/b] Create([b]const[/b] p_sFilePath : [b]string[/b]);
[b]destructor[/b] Destroy; override;
[b]function[/b] ReadMMF([b]const[/b] p_dwSize: DWORD;[b]var[/b] p_dwBytesRead : DWORD) : [b]string[/b];
[b]property[/b] Position : DWORD read FdwPosition write SetPosition;
[b]property[/b] Size : DWORD read FdwFileSize;
[b]end[/b];
[b]implementation[/b]
[color=#000080]{ TcsMMFDemo }[/color]
[b]constructor[/b] TcsMMFDemo.Create([b]const[/b] p_sFilePath: [b]string[/b]);
[b]var[/b]
aSA : TSecurityAttributes;
dwSize : DWORD;
hFile : DWORD;
hMMF : DWORD;
[b]begin[/b]
[b]inherited[/b] Create;
aSA.nLength := SizeOf(TSecurityAttributes);
aSA.bInheritHandle := true;
aSA.lpSecurityDescriptor := [b]nil[/b];
hFile := CreateFile(PChar(p_sFilePath),GENERIC_READ,FILE_SHARE_READ,@aSA,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,0);
[b]try[/b]
[b]if[/b] hFile = INVALID_HANDLE_VALUE [b]then[/b]
[b]begin[/b]
[b]raise[/b]
Exception.CreateFmt('Datei %s konnte nicht geöffnet werden',[p_sFilePath]);
[b]end[/b];
FdwFileSize := GetFileSize(hFile,[b]nil[/b]);
hMMF := CreateFileMapping(hFile,@aSA,PAGE_READONLY [b]or[/b] SEC_COMMIT,0,FdwFileSize,[b]nil[/b]);
[b]if[/b] hMMF = 0 [b]then[/b]
[b]begin[/b]
[b]raise[/b]
Exception.Create('File Mapping fehlgeschlagen');
[b]end[/b];
[b]finally[/b]
CloseHandle(hFile);
[b]end[/b];
FdwPosition := 0;
FszBuffer := MapViewOfFile(hMMF,FILE_MAP_READ,0,0,FdwFileSize);
[b]try[/b]
[b]if[/b] FszBuffer = [b]nil[/b] [b]then[/b]
[b]begin[/b]
[b]raise[/b]
Exception.Create('View Mapping fehlgeschlagen');
[b]end[/b];
[b]finally[/b]
CloseHandle(hMMF);
[b]end[/b];
[b]end[/b];
[b]destructor[/b] TcsMMFDemo.Destroy;
[b]begin[/b]
UnmapViewOfFile(FszBuffer);
[b]inherited[/b] Destroy;
[b]end[/b];
[b]procedure[/b] TcsMMFDemo.SetPosition([b]const[/b] Value: DWORD);
[b]begin[/b]
[b]if[/b] Value < FdwFileSize [b]then[/b]
[b]begin[/b]
FdwPosition := Value;
[b]end[/b]
[b]else[/b]
[b]begin[/b]
FdwPosition := FdwFileSize-1;
[b]end[/b];
[b]end[/b];
[b]function[/b] TcsMMFDemo.ReadMMF([b]const[/b] p_dwSize: DWORD;[b]var[/b] p_dwBytesRead : DWORD) : [b]string[/b];
[b]begin[/b]
Result := '';
[b]if[/b] p_dwSize = 0 [b]then[/b]
[b]begin[/b]
exit;
[b]end[/b];
FdwReadSize := p_dwSize;
[b]if[/b] (FdwPosition + FdwReadSize) > FdwFileSize [b]then[/b]
[b]begin[/b]
FdwReadSize := FdwFileSize - FdwPosition;
[b]end[/b];
p_dwBytesRead := FdwReadSize;
Result := StringOfChar(#00,FdwReadSize);
StrLCopy(@Result[1],(FszBuffer+FdwPosition),FdwReadSize);
FdwPosition := FdwPosition + FdwReadSize;
[b]end[/b];
[b]end[/b].