Shared DLL Module State

Global and static variables in a DLL module are, by default, not shared between processes which load the DLL, as a result, each process has its own instance of a DLL’s global and static variables.

To share DLL global and static variables amongst all processes which load the DLL, you must place the shared variables in a new data segment;

#pragma data_seg(".DATASEGNAME")
int nSomeSharedVariable = 0// initialise variable
#pragma data_seg()

You then need to tell the linker about this data segment and mark it “shared”.

#pragma comment(linker, "/SECTION:.DATASEGNAME,RWS")

Having done this, variable nSomeSharedVariable is shared between all processes which load the DLL.  This obviously means that you must protect such variables from access by multiple threads.

Published by

Phil Harding

SharePoint Consultant, Developer, Father, Husband and Climber.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.