I have a Delphi 6 application and also a DLL that share a memory mapped file to transfer data between them. I know soft page faults are a normal side effect of memory mapped files, but I am getting a lot more than I think should (high PF Delta values in the Task Manager of about 2000 per second). Therefore I am posting the parts of my code that create the memory mapped file, write to it, and read from it to see if anyone can see some flaw in my approach. Here are the code excerpts below. Note, I am using a desired file size of 1MB:
// Uses pagefile.sys
procedure initFile(
theFilename: string;
theDesiredFilesize: integer;
out theViewHandle: THandle;
out theBaseAddressPtr: Pointer);
var
MaximumSizeLow, MaximumSizeHigh: Cardinal;
begin
I64ToCardinals(theDesiredFilesize, MaximumSizeLow, MaximumSizeHigh);
theViewHandle :=
CreateFileMapping(
INVALID_HANDLE_VALUE,
nil,
PAGE_READWRITE or SEC_COMMIT,
MaximumSizeHigh,
MaximumSizeLow,
PChar(theFilename));
if theViewHandle = 0 then
RaiseLastOSError;
theBaseAddressPtr := MapViewOfFile (theViewHandle, FILE_MAP_ALL_ACCESS, 0, 0, 0);
end;
procedure TShareMem.doSaveBuffer(const theSourceBufPtr: Pointer; numBytes: integer);
var
newSize: Int64;
begin
if not Assigned(theSourceBufPtr) then
raise Exception.Create('(doSaveBuffer) The source buffer pointer is unassigned.');
newSize := numBytes;
Move(theSourceBufPtr^, FDataBufferPtr^, newSize);
// Increment the write count.
Inc(FDataBufferHeader.writeCount);
// Update the variable that lets others know the actual size of the
// object/data we just stored.
FDataBufferHeader.sizeInUse := numBytes;
// Update the header file.
updateHeaderFile;
end;
procedure TShareMem.loadStream(theDestStream: TMemoryStream);
var
theSize: Int64;
begin
if not Assigned(theDestStream) then
raise Exception.Create('(loadStream) The destination stream is unassigned.');
updateHeader;
// Rewind the destination stream.
theDestStream.Position := 0;
theSize := FDataBufferHeader.sizeInUse;
theDestStream.Size := theSize;
// Read data from the memory mapped data buffer into the stream.
// theDestStream.WriteBuffer(FDataBufferPtr^, FDataBufferHeader.size);
Move(FDataBufferPtr^, theDestStream.Memory^, theSize);
end;