Is it possible to run managed initialization code for a c++/cli dynamic library? I have a large collection of managed classes all wrapping underlying unmanaged functionality, used by many different solutions. I now need to call some managed code before anything else is executed, and I've tried several attempts but haven't been successful yet.
I initially tried running the code in the DllMain function, but quickly realized that you cannot call managed code inside DllMain, as it's not safe and LoaderLock occurs. I then discovered I could code my own Module Constructor like so:
#pragma warning( disable : 4483 )
void __clrcall __identifier(".cctor")()
{
// Do managed code initialisation here
}
However, this seems to override the default Module Constructor, and I get a lot of linker warnings like:
warning LNK4210: .CRTMP section exists; there may be unhandled static initializers or terminators
Some research indicates that the default module constructor _DllMainCRTStartup calls _CRT_INIT, which initializes the the C/C++ static objects. The general consensus seems that it's a very bad idea to override the entry point for the dll, and I don't want to cause more problems for myself down the line.
The last thing I tried was creating a global static object of the managed initializer class in global scope, hoping that it may be initialized inside _CRT_INIT, but that doesn't seem to be the case.
Is there ANY way I can execute some managed code as a module initialization or even execute delayed code that is still guaranteed to be called before anything else in the module?
Thanks, at the moment I am relying on providing a static initialization function that is called on an application level, but I obviously can't enforce all users of this library to do that in their applications. The other option I see is to add the initialization call in all managed class constructors, but again, I can't be sure anyone building on this library will follow the same design pattern, and it seems like a lot to maintain, especially if there is an easy way to do CLR module initialization.