简体   繁体   中英

Access Violation Exception when trying to access bstrVal field of variant object

I'm trying to get hardware information using WMI and the (Win32_Processor) class. When I try to access the "Name" property of this class through a IWbemClassObject I get the Name of the cpu and the program executes without error.

However when I try to access any other property("NumberOfCores" for example) I get an "Access Violation" exception.

Here is a part my code:

    HRESULT hres;
    IWbemClassObject* pclsObj = NULL;
    ULONG uReturn = 0;
    IEnumWbemClassObject* pEnumerator = NULL;

    // pSvc is a IWbemServices object.

    hres = pSvc->ExecQuery(
           bstr_t("WQL"),
           bstr_t("SELECT * FROM Win32_Processor"),
           WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY,
           NULL,
           &pEnumerator);

    
    while (pEnumerator)
    {
        hres = pEnumerator->Next(WBEM_INFINITE, 1,
            &pclsObj, &uReturn);

        if (0 == uReturn)
        {
            break;
        }

        VARIANT vtProp;

        VariantInit(&vtProp);
        ///////////////////////////////////
        // Accessing properties

        // hr = pclsObj->Get(SysAllocString(L"NumberOfCores"), 0, &vtProp, 0, 0);
        
        hr = pclsObj->Get(SysAllocString(L"Name"), 0, &vtProp, 0, 0);

        if(FAILED(hr))
        {
            cout<< "failed"; // it doesn't fail with either property.
            return 0;
        }

        wcout << " Name : " << vtProp.bstrVal << endl; <-this line throws the exception.

        ///////////////////////////////////

        VariantClear(&vtProp);
        pclsObj->Release();
    }

I read somewhere that you get this error when the (bstrVal) field is either empty or null, but when I checked it was neither.

Any help is much appreciated.

I'm accessing the wrong property of the VARIANT object. Instead of "bstrVal", I should access "uintVal" because the property "NumberOfCores" is an unsigned int not a BSTR object.

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