Search code examples
windowswinapimfcgdi

Shared bitmap across processes


How to create a device independent bitmap in windows using win32/mfc that will be shared among all processes running on the machine?

Looking for a best and fastest way of sharing a DIB between all processes on windows XP/7 machine. Processes should be able to lock the contents of bitmap and make drawing on this bitmap and other processes can use this bitmap for reading also.

For e.g. initially this DIB will be created by a main application. When some other process want to draw something on this process, can lock the contents of this DIB and draw on this bitmap. If some other process want to read the contents of this bitmap, can lock the bitmap and read the bitmap.

Please suggest a best way both in time complexity and space complexity manner. Space complexity means, a process which wants to draw contents on this bitmap should not need to copy all contents on local memory and draw, it should directly be able to take this bitmap in device context and draw in the bitmap.


Solution

  • There is, unfortunately*, no supported way to share GDI handles (such as to bitmaps) between processes.

    There is a supported way however to get multiple bitmaps (in multiple processes) to share the same storage.

    In your primary process, create a memory section using the CreateFileMapping API.

    You have several ways to get the section handle to your various processes -

    The simplest of which (as pointed out by Hans Passant) is to simply name the section when calling CreateFileMapping... and then using OpenFileMapping. If you have a main process that launches the other processes ensure that the section is created with the bInheritHandle of the SECURITY_ATTRIBUTES set to TRUE and the handle will be automatically duplicated into any sub processes - its usual to pass the handle value on the command line of the new process. Otherwise use DuplicateHandle function to copy the handle into other processes - but you will still need some other kind of IPC to get the handle to the process.

    However it happens - You can then call CreateDIBSection in each process to create GDI bitmaps that are backed by the same memory section. Note the comments on synchronizing access to the bitmap. If you have multiple processes trying to write to the bitmap you might need to serialize access at that level.

    • As an ironic note: Because Win32 is based on Win16 there are a lot of Win16 legacy APIs that deal with window messages and the clipboard that do in fact expect HBITMAP's to be usable from multiple processes. Also (as an implementation detail) on Windows NT 5.x and 6.x bitmaps are allocated by kernel mode drivers from a single system wide handle table and are thus technically valid in any process - However, GDI also stores the process ID of each GDI object in that table and GDI API calls explicitly check the process ID and fail out if called on a GDI handle belonging to another process.