延迟构造静态成员对象 [英] Delay the construction of a static member object
问题描述
项目被编译为dll文件,然后注入可执行文件中
The project is compiled into a dll to be injected into an executable
该项目依赖于API,该API最初是在main()中初始化的,如下所示:
The project relies on an API which is initialized at the very beginning in main() like so:
int DLL_main()
{
TheApi::Initialize();
AnObject anObjectInstance;
//..
}
有一个用类似于以下内容的类定义构造的对象:
There is an object that is constructed with a class definition similar to this:
class AnObject()
{
AnObject();
~AnObject();
static ApiHelper apiHelperObject; //This object assists in making certain api features easier to use
}
//Inside AnObject.cpp
ApiHelper AnObject::apiHelperObject;
在 apiHelperObject
的构造函数中,有一些API函数调用
In the constructor of apiHelperObject
, there are some API function calls
在注入dll之后,什么也没有发生(也没有错误消息),从 apiHelperObject
中删除static关键字后,一切正常
Upon injection of the dll, nothing happens (no error message as well) however,
when the static keyword is removed from apiHelperObject
all works fine
问题似乎是在初始化API之前 构造了静态成员
The issue seems to be that the static member is being constructed before the API is initialized
无法在 apiHelperObject
的构造函数中调用 TheApi :: Initialize()
,因为存在多个不同的api帮助器对象,这将导致TheApi :: Initialize()
被多次调用
It is not possible to call TheApi::Initialize()
in apiHelperObject
's constructor because there are multiple different api helper objects, and that would cause TheApi::Initialize()
to be called more than once
所以问题是:
在构造静态成员对象之前初始化api的最佳方法是什么?或者,延迟静态成员构建的最佳方法是什么?
What is the best way of initializing the api before the static member object is constructed? Or, what is the best way to delay the construction of the static member?
最好不要使用指针,因为语法并不特别受欢迎
Preferably, a pointer is not used as the syntax is not especially favored
谢谢
推荐答案
在普通标准C ++中,始终可以通过将 static
对象设置为访问函数的本地对象来延迟其初始化.
In ordinary standard C++ you can always delay the initialization of a static
object by making it local to an accessor function.
从本质上讲,这是迈耶斯的单身人士:
Essentially that's a Meyers' singleton:
auto helper_object()
-> ApiHelper&
{
static ApiHelper the_object;
return the_object;
}
在这里,在标准C ++中,对象在执行第一次通过声明时被初始化.
Here, in standard C++, the object is initialized the first time execution passes through the declaration.
但是C ++标准不主动支持动态库,更不用说DLL注入了.因此,很难说这将如何进行.提防线程问题.
But the C++ standard does not actively support dynamic libraries, much less DLL injection. So it's difficult to say how this is going to play out. Beware of threading issues.
这篇关于延迟构造静态成员对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!