Eric
Eric

Reputation: 1243

storing state in a c++ dll

Im having issues on how to store state in a dll in c++. What i currently have is something like this:

#ifndef FOO
#define FOO

#ifdef BUILD_DLL
  #define DECLSPEC __declspec(dllexport)
#else
  #define DECLSPEC __declspec(dllimport)
#endif

namespace FOO
{
    extern "C"
    {
        DECLSPEC bool initialize();                    
        DECLSPEC void addSomething();
        DECLSPEC void removeSomething();
        DECLSPEC void shutDown();  
    }
}

#endif // FOO

Now i want my dll to be able have some sort of state. For example i want the stuff that get's added by addSomething() to be stored in a std::vector inside the dll and be able to acess that same vector from removeSomething(). Since my dll just exports a set of functions, i don't really see a clean way to do that. The only ting that currently comes to my mind are global variables inside the dll. Is there a better solution than that? I kind of want to avoid using global variables even if they are only inside the dll.

Upvotes: 1

Views: 917

Answers (1)

trojanfoe
trojanfoe

Reputation: 122391

You can choose to either use global variables to store the data or you can pass back a handle to the caller (from initialize() for example) and hang your data off that. The caller then passes back this handle when calling any of the exposed methods; for example:

typedef void *MyHandle;

// NULL would be an error
DECLSPEC MyHandle initialize();
DECLSPEC void addSomething(MyHandle handle);
DECLSPEC void destroy(MyHandle handle);

In the implementation you cast MyHandle to a concrete type which is not exposed to the caller.

This allows your DLL to be used more than once within the process and allows you to avoid the use of global variables.

I find your use of both namespace and extern "C" strange; I think you should stick to C-Linkage to make your DLL useful from more languages.

Upvotes: 3

Related Questions