Sharing data array between two applications in Delphi

前端 未结 2 620
Happy的楠姐
Happy的楠姐 2020-12-09 19:41

I want to share array data between two applications. In my mind, first program create the array and the second program can read the array from already allocated memory area.

2条回答
  •  没有蜡笔的小新
    2020-12-09 20:28

    A Named File Mapping would be the easiest solution, here is some short example code. In this sample there is a main program that writes some data and reader(s) that only read from it.

    Main:

    type
      TSharedData = record
        Handle: THandle;
      end;
      PSharedData = ^TSharedData;
    
    const
      BUF_SIZE = 256;
    var
      SharedData: PSharedData;
      hFileMapping: THandle;  // Don't forget to close when you're done
    
    function CreateNamedFileMapping(const Name: String): THandle;
    begin
      Result := CreateFileMapping(INVALID_HANDLE_VALUE, nil, PAGE_READWRITE, 0,
        BUF_SIZE, PChar(Name));
    
      Win32Check(Result > 0);
    
      SharedData := MapViewOfFile(Result, FILE_MAP_ALL_ACCESS, 0, 0, BUF_SIZE);
    
      Win32Check(Assigned(SharedData));
    end;
    
    procedure TForm1.Button1Click(Sender: TObject);
    begin
      hFileMapping := CreateNamedFileMapping('MySharedMemory');
      Win32Check(hFileMapping > 0);
      SharedData^.Handle := CreateHiddenWindow;
    end;
    

    reader:

    var
      hMapFile: THandle;   // Don't forget to close
    
    function GetSharedData: PSharedData;
    begin
      hMapFile := OpenFileMapping(FILE_MAP_ALL_ACCESS, False, 'MySharedMemory');
      Win32Check(hMapFile > 0);
    
      Result := MapViewOfFile(hMapFile, FILE_MAP_ALL_ACCESS, 0, 0, BUF_SIZE);
    
      Win32Check(Assigned(Result));
    end;
    

提交回复
热议问题