Friday, April 21, 2006

Share data among processes through DLLs

I ran across this problem wherein I had to notify a process of an event which is triggered by another process through a DLL. Well, more precicely, the first process would invoke (this is an event) an exported function of the DLL and this function has to notify another process about this event. Now, this function could simply post a message to the main window of the second process, if it has a handle to it. Storing this handle is the problem. One obvious solution is to declare a static data in the dll and let the second process 'register' for notification by passing its window handle. Once it is stored, subsequent notifications are easy - just call PostMessage with this hwnd parameter. But there is a caveat. Eventhough DLL's map their code into the memory of each processes, it has separate instance for globals and static variables. Now these static members will be initialised separately for each processes when the DLL is loaded, which defeates the above method of sharing the window handle. There is a solution, atleast in MSVC environment. Create a named data-section in the dll code and place the data to be shared in it.

#pragma data_seg (".sharedseg")
HWND hNotifyWnd;
#pragma data_seg()

And give the linker option: /SECTION:.sharedseg,RWS

No comments: