0

I use the following to share a shortstring between 2 executables:

Type
  PInstanceInfo = ^TInstanceInfo;
  TInstanceInfo = packed record
    MainAppHandle: THandle;
    SessionPath: String[255];
  end;
Var MappingHandle: THandle;
    InstanceInfo: PInstanceInfo;

  MappingHandle := CreateFileMapping(INVALID_HANDLE_VALUE,
                                     nil,
                                     PAGE_READWRITE,
                                     0,
                                     SizeOf(TInstanceInfo),
                                     PChar('MyApp'));

  InstanceInfo := MapViewOfFile(MappingHandle, FILE_MAP_ALL_ACCESS, 0, 0, SizeOf(TInstanceInfo));
  InstanceInfo^.MainAppHandle := Application.Handle;

I use SessionPath to store the path to a file. This works fine when both apps are x86 or x64, but when App1 is 32-bit and App2 is 64-bit, App2 is missing the first 4 characters of the string when I read it. What's different in the ShortString structure in this case?

hikari
  • 3,393
  • 1
  • 33
  • 72

1 Answers1

3

THandle is pointer sized. So it is 32 or 64 bit depending on the platform. That explains the missing 4 bytes. In fact this could easily be seen yourself by using the SizeOf function in test programs.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
  • Fixed it by changing THandle to FixedUInt. Thanks – hikari Sep 21 '19 at 12:39
  • I'm assuming that memory mapping is the right solution but it often is not. – David Heffernan Sep 21 '19 at 12:40
  • Note that `Application.Handle` is an `HWND` not a `THandle`. And you can freeing transfer `HWND`s across process boundaries. Although an `HWND` is a pointer-sized type so you still run into the same byte size issue, `HWND`s are designed to be 32bit values so they can safely be extended when passed from 32bit to 64bit and truncated when passed from 64bit to 32bit. See [How can I share HWND between 32 and 64 bit applications in Win x64?](https://stackoverflow.com/questions/1822667/) – Remy Lebeau Sep 21 '19 at 17:59
  • Both THandle and HWND point to the same NativeUInt type, so it's the same issue. – hikari Sep 22 '19 at 02:39