linko13 linko13 - 1 year ago 46
C++ Question

Delay the construction of a static member object

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()
AnObject anObjectInstance;

There is an object that is constructed with a class definition similar to this:

class 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
, 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
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
's constructor because there are multiple different api helper objects, and that would cause
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

Answer Source

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.