Loader lock (regsvr32 R6033 error) with managed C+

2019-04-11 10:12发布

问题:

I have a C++ dll which implements several COM interfaces, that I'm trying to migrate to managed C++. I set the /clr compiler flag and changed the Runtime Library property from /MT to /MD to avoid the conflict between these two flags, but that's all I've changed. When it attempts to register the dll during the build process, I get the following error:

R6033 - Attempt to use MSIL code from this assembly during native code initialization This indicates a bug in your application. It is most likely the result of calling an MSIL-compiled (/clr) function from a native constructor or from DllMain.

I read about Loader Lock and can't figure it out - I have not added a single call to any managed code. Here's the entire body of the DllMain procedure:

[Edit - per comment below, I added #pragma unmanaged to the top of the cpp file with no improvement. The Module init is all code contained in the ATL libraries from what I can tell.]

extern "C"
BOOL WINAPI DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID lpReserved)
{
    lpReserved;
    if (dwReason == DLL_PROCESS_ATTACH)
    {
        _Module.Init(ObjectMap, hInstance, &MYGUID);
        DisableThreadLibraryCalls(hInstance);
    }
    else if (dwReason == DLL_PROCESS_DETACH)
        _Module.Term();
    return TRUE;    // ok
}

回答1:

You need to add the /clr compiler flag only to the files that use managed code and not for the whole project.

This is what the Visual Studio "Wizard" does, here is how I've tested:

  • Create a Visual C++ ATL Project
  • Added a ATL Simple Object, in order to have a COM interface (Project->Add Class)
  • Added a CLR Component Class. The Wizard prompted me with "You are adding a CLR component to a native project. Your project will be converted to have Common Language Runtime support."
  • Compile project, compiles fine and registers fine.
  • Checked the project settings -> "No Common Language Runtime support"
  • Checked the clrcomponennt.cpp settings -> "Common Language Runtime Support (/clr)"
  • Opened the dll in OleView -> COM interface was present
  • Opened the dll in Red Gate's .NET Reflector -> clrcomponent was present


回答2:

Using /clr flag has made your methods managed (ie. they are being compiled down to MSIL), but you're calling them for DllMain which -isn't- managed. Unfortunately, that's about as far as my limited knowledge can take it.



标签: c++ clr managed