开发者

C++ how to store initial state of program in DLL / recognize uninitialized variable

I'm writing a DLL in C++ for use with VB6. As such, I cannot have a constructor called in my DLL (according to this discussion). However, I need to maintain an instance of a class internally -- so I intend to keep the object as a global variable and call the constructor from a global function, and after that, use another global function to call a method on the object.

I had the idea that maybe one function would be enough: It would check if an instance is present in a global variable, and if not, create it, and then call the method on the object (or, if it is present, immediately call the method.)

Now, how can I find out whether an instance is already created? I can't assign a global variable any value in the declaration, right? And they also don't have a guaranteed default value in C++, as far as I understand.

Therefore my question: Is this possible anyway and how?

Or can I use the BOOL APIENTRY DllMain( HMODULE hModule, DWORD ul_reason_for_call, 开发者_JAVA百科 LPVOID lpReserved ) function to initialize variables? If so, can someone fill me in on what the ul_reason_for_call cases exactly are and which of these is automatically called when VB6 loads the DLL as in my linked example?


You can use global static variables or file scope variables in your CPP files:

bool bInited = false;
MyClass* pClass = NULL;

These assignment statements will be called inside DllMain, later you can test if they have been initialized properly.

You could declare the pointers as auto_ptr (if you use stl or something equivalent), to have the destructors called on exit.


Suppose you want an instance of MyClass to be acessible globally. You can have a class with a static member which your global functions will access:

class GlobalHelper {
public:
   static MyClass* GetInstance() {
      static MyClass inst;
      return &inst;
   }
};

...and then your global methods would be calling GlobalHelper::GetInstance()->Whatever() to do their work.


You don't even need a function:

class MyThingy
{
} my_global_thingy;

my_global_thingy will be instantiated at program startup, before DllMain is executed.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜