unit uGameStatusTypeDefs;

interface

uses Classes, SysUtils, {$IFDEF MSWINDOWS} Windows, {$ENDIF} uHCDefines,
  uHCTypeDefs;

type
  // ALE 20150713 Forward type declarations so we can use them in later types
  PMMFGameStatus = ^TMMFGameStatus;

  // ALE 20150819 Structure for the memory mapped file
  TMMFGameStatus = record
    version: integer; // ALE 20150820 DLL and Viewer Server must have same version
    read: Boolean; // ALE 20150819 the consumer will set this to True when the information has been read
    gamestartdatetime: THCDateTimeRec;
    gametime: long;
    gametimeleft: long;
    killcounts: array [0 .. 9, 0 .. SIDES - 1] of ulong;
  end;

{$IFDEF MSWINDOWS}

  TTGPMemMappedFile = class
  private
    fHMapFile: THandle;
  public
    fPSharedData: Pointer;
    constructor Create; overload;
    destructor Destroy; override;
    function CreateNamedFileMapping(const Name: String;
      const pBufSize: NativeInt; pSharedData: Pointer): THandle;
    function GetSharedData(const Name: String;
      const pBufSize: NativeInt): Pointer;
  end;
{$ENDIF}

implementation

{$IFDEF MSWINDOWS}

constructor TTGPMemMappedFile.Create;
begin
  inherited;
  fHMapFile := CreateNamedFileMapping('HCGameStatus', SizeOf(TMMFGameStatus),
    fPSharedData);
end;

destructor TTGPMemMappedFile.Destroy;
begin
  UnmapViewOfFile(fPSharedData);
  CloseHandle(fHMapFile);
  inherited;
end;

function TTGPMemMappedFile.CreateNamedFileMapping(const Name: String;
  const pBufSize: NativeInt; pSharedData: Pointer): THandle;
begin
  Result := CreateFileMapping(INVALID_HANDLE_VALUE, nil, PAGE_READWRITE, 0,
    pBufSize, PChar(Name));

  Win32Check(Result > 0);

  fPSharedData := MapViewOfFile(Result, FILE_MAP_ALL_ACCESS, 0, 0, pBufSize);

  Win32Check(Assigned(fPSharedData));
end;

function TTGPMemMappedFile.GetSharedData(const Name: String;
  const pBufSize: NativeInt): Pointer;
begin
  fHMapFile := OpenFileMapping(FILE_MAP_ALL_ACCESS, False, PChar(Name));
  Win32Check(fHMapFile > 0);

  Result := MapViewOfFile(fHMapFile, FILE_MAP_ALL_ACCESS, 0, 0, pBufSize);

  Win32Check(Assigned(Result));
end;
{$ENDIF}

end.
