简体   繁体   中英

Unhandled exception when trying to load a COM wrapped DLL in C++

I have an assembly in .NET , which I have exposed via COM and strongly named.

Upon deployment, this assembly needs to be present in the GAC . However, I need to check whether it exists before creating its object.

Unfortunately, even putting the object creation within a try / catch results in unhandled exception during runtime, if the assembly is not present in the GAC.

So there has to be some way for me to verify, if the DLL is indeed installed in the GAC before I go on to create the object.

HINSTANCE histLib;
    histLib = LoadLibrary("CLSInterOpLibrary.dll");
    if (histLib == NULL)
        return false;
    encode();

    CoInitialize(NULL);
    try
    {
        CLSInterOpLibrary::CLSInterOpInterfacePtr p(__uuidof(CLSInterOpLibrary::CLSInterOpClass));
        if (p == nullptr)
            return false;
        com_ptr = p;
    }
    catch (exception &e)
    {

    }

LoadLibrary gives a NULL, regardless of whether the library is present in GAC or not, probably needs some sort of path..., and

CLSInterOpLibrary::CLSInterOpInterfacePtr p(__uuidof(CLSInterOpLibrary::CLSInterOpClass));

..gives an unhandled exception if the DLL is not present.

So how would one check if a DLL is installed in GAC with C++? Or is there a more elegant solution to this?

Do not call LoadLibrary(), the odds that this will work are very small, especially so if the assembly is actually installed in the GAC. Finding the DLL is the job of COM, it uses the registry keys that were written when you registered the assembly.

You need to fix your error handling, the CLSInterOpInterfacePtr smart pointer type you got from the #import directive turns HRESULT error codes into exceptions. You need try/catch to catch the _com_error exception . Trying to catch std::exception won't work, _com_error does not derive from it.

Which is good enough to also diagnose a problem with the registration or a missing DLL. The boilerplate _com_error::Error value you get is REGDB_E_CLASSNOTREG (0x80040154), "Class not registered" if the COM server was not registered, something more specific if the CLR has trouble locating the DLL. The _com_error::Description() method provides you with a somewhat reasonable message you can display or log. The holy stacktrace is out of reach.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM