user1580348
user1580348

Reputation: 6051

Delphi XE2: Sharing a variable between two different processes?

I need to share the value of a Boolean variable between 2 running programs (e.g. MyProgramA.exe and MyProgramB.exe); these are different programs, not instances of the same program. I would prefer a global variable in memory over IPC with Windows messages because I think setting a global variable in memory which can be accessed by different programs is faster (i.e. instantaneous), more secure and more reliable than IPC with Windows messages.

Upvotes: 0

Views: 1483

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 595712

You can allocate a block of shared memory using the Win32 API CreateFileMapping() function, and then use the MapViewOfFile() function to access that memory. Both processes need to call CreateFileMapping() with the same name in order to share the same mapping, but they will each receive their own local view of the mapping.

For example:

uses
  ..., Windows;

var
  Mapping: THandle = 0;
  MyBoolean: PBoolean = nil;

...

Mapping := CreateFileMapping(INVALID_HANDLE_VALUE, nil, PAGE_READWRITE, 0, SizeOf(Boolean), 'MyMappedBoolean');
if Mapping <> 0 then
  MyBoolean := PBoolean(MapViewOfFile(Mapping, FILE_MAP_WRITE, 0, 0, SizeOf(Boolean));

...

if MyBoolean <> nil then
  MyBoolean^ := ...;

...

if MyBoolean <> nil then
begin
  if MyBoolean^ then
    ...
  else
    ...
end;

...

if MyBoolean <> nil then
  UnmapViewOfFile(MyBoolean);
if Mapping <> 0 then
  CloseHandle(Mapping);

Upvotes: 5

Related Questions