C++如何在DLL中存储程序的初始状态/识别未初始化的变量
我正在用 C++ 编写一个 DLL,以便与 VB6 一起使用。因此,我无法在 DLL 中调用构造函数(根据 此讨论< /a>)。但是,我需要在内部维护类的实例 - 因此我打算将对象保留为全局变量并从全局函数调用构造函数,然后使用另一个全局函数调用该对象的方法。
我的想法是,也许一个函数就足够了:它将检查全局变量中是否存在实例,如果不存在,则创建它,然后调用对象上的方法(或者,如果存在,则立即调用方法。)
现在,我怎样才能知道实例是否已经创建?我不能在声明中为全局变量分配任何值,对吧?据我了解,它们在 C++ 中也没有保证的默认值。
因此我的问题是:这是否可能以及如何实现?
或者我可以使用 BOOL APIENTRY DllMain( HMODULE hModule, DWORD ul_reason_for_call, LPVOID lp保留 ) 函数初始化变量?如果是这样,有人可以告诉我 ul_reason_for_call 情况到底是什么,以及当 VB6 加载 DLL 时自动调用其中哪一个,如我的链接示例中所示?
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,
function to initialize variables? If so, can someone fill me in on what the
DWORD ul_reason_for_call,
LPVOID lpReserved
)ul_reason_for_call
cases exactly are and which of these is automatically called when VB6 loads the DLL as in my linked example?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以在 CPP 文件中使用全局静态变量或文件范围变量:
这些赋值语句将在 DllMain 内部调用,稍后您可以测试它们是否已正确初始化。
您可以将指针声明为 auto_ptr(如果您使用 stl 或等效的东西),以便在退出时调用析构函数。
You can use global static variables or file scope variables in your CPP files:
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.假设您希望可以全局访问
MyClass
的实例。您可以拥有一个带有静态成员的类,您的全局函数将访问该类:
...然后您的全局方法将调用 GlobalHelper::GetInstance()->Whatever() 来完成其工作。
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:
...and then your global methods would be calling
GlobalHelper::GetInstance()->Whatever()
to do their work.您甚至不需要函数:
my_global_thingy
将在程序启动时、DllMain 执行之前实例化。You don't even need a function:
my_global_thingy
will be instantiated at program startup, before DllMain is executed.