2

我有一个 Delphi 6 应用程序和一个 DLL,它们共享一个内存映射文件以在它们之间传输数据。我知道软页面错误是内存映射文件的正常副作用,但我得到的比我想象的要多得多(任务管理器中的高 PF Delta 值约为每秒 2000)。因此,我发布了创建内存映射文件、写入文件并从中读取的代码部分,以查看是否有人能看到我的方法中的一些缺陷。以下是下面的代码摘录。请注意,我使用的是 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;
4

0 回答 0