• 12
• 10
• 10
• 13
• 10

# DLL and static data member

This topic is 3956 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Hello, I need some help with DLL. I've a base class defined in my main exe. The base class has a static variable..something like this
class BaseClass
{
public:
BaseCase ();
~BaseCase();
...
...
static int *counter;
};


The DLL code is something like this
#include "BaseClass.h"

class DerivedClass : public BaseClass
{
...
};


BaseClass::counter = new int[8];


Then I load the DLL. What is happening is that the static "int *counter" is set to NULL inside the DLL while is not NULL in the main application. The static int *counter is not shared between the base class and the derived one. I think there should be some (__dllimport) (__dllexport) magic to use in order to let this work but I can't figure it out. Any advices ?

##### Share on other sites
Static variables get initialized in each module (DLL or exe) at load time, on their separate heaps.
So, there exist two copies of BaseClass::counter: one in the EXE, and one in the DLL. The one in the EXE, you fill with the call to new, the one in the DLL never gets set (so is NULL in debug builds, and random mess in release).

Using static and global variables over a DLL-boundary is a very bad idea. You'd better either devise some method so you don't need to share those variables, or put these values in thread-local storage (see GetTls()).

##### Share on other sites
Thank you, I see the problem now.
I will try a different approach.

Thank you for the fast answer

##### Share on other sites
For a DLL loaded by two processes: Read only data in the DLL is shared between both processes. The first write to a variable in the DLL causes a copy of the variable to be made in that processes address space - the value of the copy isn't seen by the other process.

It is possible to make a shared section of writable memory in the DLL to do what you want, see the last post in the following topic for an example:

http://www.gamedev.net/community/forums/topic.asp?topic_id=361392

It should be noted though that sharing DLL memory between processes does open up potential security holes...