Sign in to follow this  
Giallanon

DLL and static data member

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
{
   ...
};

Before loading the DLL I allocate memory for the static var:
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 this post


Link to post
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 this post


Link to post
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...

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this