Reputation:
The project is compiled into a dll to be injected into an executable
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;
In the constructor of apiHelperObject
, there are some API function calls
Upon injection of the dll, nothing happens (no error message as well) however,
when the static keyword is removed from apiHelperObject
all works fine
The issue seems to be that the static member is being constructed before the API is initialized
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
And so the question is:
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
Thank you
Upvotes: 2
Views: 775
Reputation: 145359
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;
}
Here, in standard C++, the object is initialized the first time execution passes through the declaration.
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.
Upvotes: 5