C ++ runtime call from DllMain or global initializers

The question is inspired by this discussion .
It seems that the fears associated with C ++ runtime calls from DllMain (or from ctor's global variables) are slightly outdated. I often use global initializers in dlls without any glitches, and now I have run a special test program (compiled with VC2010 Express without SP) containing an exe module with static runtime and dynamic link dlls. Dll is loaded manually from exe using LoadLibrary ().
The dll creates and populates the map object during global initialization (and therefore uses the runtime library of at least the memory allocation function). Dll Code:

#include <map>
using namespace std;

struct A{
  char* p;
  static const int num=1000;
  map<int,string> m;
  A(){ 
    for(int i=0; i<num; ++i){m[i]= *new string("some text");}
  }
};

A a;

extern "C"{
_declspec(dllexport) const char* getText(int i){ return a.m[i].data(); }
}


Exe ( Release, MSVCR100D.DLL ):

#include <windows.h>
typedef const char* (*pfunc_t)(int idx);

int main(int argc, TCHAR* argv[])
{
  HMODULE h_crt= GetModuleHandle("MSVCR100.DLL");
  // ensure that runtime library is NOT loaded yet:
  MessageBox(NULL,(NULL==h_crt)? "CRT NOT loaded by .exe module": "CRT Loaded by .exe module"  ,"before LoadLibrary",MB_OK);

  HMODULE hlib=LoadLibrary("dll_example.dll");
  h_crt= GetModuleHandle("MSVCR100.DLL");
  MessageBox(NULL,(NULL==h_crt)? "CRT NOT loaded": "CRT Loaded"  ,"after LoadLibrary",MB_OK);

  pfunc_t pfunc= (pfunc_t)(void*)GetProcAddress(hlib,"getText");
  MessageBox(NULL,pfunc(99),"map[99]",MB_OK);

    return 0;
}

, :

before LoadLibrary: CRT NOT loaded by .exe module
after LoadLibrary: CRT Loaded
map[99]: some text

, , ..

DependencyWalker , runtime lib (MSVCR100.DLL) LoadLibrary ( exe).

, dll_example.dll .

?

PS. init; , (?).

+3
2

CRT DLL - , , COM-. , CRT, , , , api. , CLR , . , . , , . .

, , DLL, CRT. , . DLL, ++. const char *, . .

+3

, DLLMain. , , CRT promises, .

, DLL, , .

+4

Source: https://habr.com/ru/post/1794747/


All Articles