当前位置: 首页>>代码示例>>C++>>正文


C++ IEnumWbemClassObject类代码示例

本文整理汇总了C++中IEnumWbemClassObject的典型用法代码示例。如果您正苦于以下问题:C++ IEnumWbemClassObject类的具体用法?C++ IEnumWbemClassObject怎么用?C++ IEnumWbemClassObject使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了IEnumWbemClassObject类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: testForHyperv

/**
 * Test to see whether we are running on a system with Hyper-V enabled.
 * We consider Hyper-V to be running (and can export per vm stats) if
 * the Hyper-V related services (nvspwmi, vmm, vhdsvc) are running and
 * we can access the WMI namespace root\virtualization (ie v1 for Win 2008
 * and v2 for Win 2012).
 * We need to check for the v2 namespace and use in preference to v1, 
 * since v1 was deprecated and all classes removed in Win 2012 R2. So
 * we also set the global variable wmiVirtNs to the preferred namespace.
 * The ability connect to the sFlow filter for export of packet samples 
 * and counter samples for the virtual switch is made separately.
 */
BOOL testForHyperv()
{
	BSTR path = SysAllocString(WMI_CIMV2_NS);
	HRESULT hr = S_FALSE;
	IWbemServices *pNamespace = NULL;

	hr = connectToWMI(path, &pNamespace);
	SysFreeString(path);
	if (WBEM_S_NO_ERROR != hr) {
		myLog(LOG_ERR,"testForHyperv: connectToWMI failed for namespace %S", path);
		return false;
	}
	//Test for Hyper-V services
	BOOL gotHyperV = false;
	BSTR queryLang = SysAllocString(L"WQL");
	BSTR query = SysAllocString(L"SELECT * FROM Win32_Service WHERE Name=\"nvspwmi\" OR Name=\"vmms\" OR Name=\"vhdsvc\"");
	IEnumWbemClassObject *serviceEnum = NULL;
	hr = pNamespace->ExecQuery(queryLang, query, WBEM_FLAG_FORWARD_ONLY, NULL, &serviceEnum);
	SysFreeString(query);
	SysFreeString(queryLang);
	if (WBEM_S_NO_ERROR != hr) {
		myLog(LOG_ERR, "testForHyperv: ExecQuery() failed for %S error=0x%x", query, hr);
	} else {
		IWbemClassObject *serviceObj = NULL;
		ULONG uReturned = 0;
		BOOL gotHyperVSvc = false;
		hr = serviceEnum->Next(WBEM_INFINITE, 1, &serviceObj, &uReturned);
		if (SUCCEEDED(hr)) {
			if (uReturned == 1) {
				gotHyperVSvc = true;
				serviceObj->Release();
			}
		}
		serviceEnum->Release();
		pNamespace->Release();
		if (gotHyperVSvc) { //now check that we have the v2 virtualization namespace
			CoUninitialize();
			path = SysAllocString(WMI_VIRTUALIZATION_NS_V2);
			hr = connectToWMI(path, &pNamespace);
			SysFreeString(path);
			if (WBEM_NO_ERROR == hr) {
				gotHyperV = true;
				wmiVirtNsVer = 2;
				pNamespace->Release();
			} else {
				CoUninitialize();
				path = SysAllocString(WMI_VIRTUALIZATION_NS_V1);
				hr = connectToWMI(path, &pNamespace);
				SysFreeString(path);
				if (WBEM_NO_ERROR == hr) {
					gotHyperV = true;
					wmiVirtNsVer = 1;
					pNamespace->Release();
				}
			}
			if (!(wmiVirtNsVer == 1 || wmiVirtNsVer == 2)) {
				myLog(LOG_ERR, "testForHyperv: unknown wmiVirtNsVer=%u", wmiVirtNsVer);
			}
		}
	}
	CoUninitialize();
	myLog(LOG_INFO, "testForHyperv: HyperV=%u wmiVirtNsVer=%u", gotHyperV, wmiVirtNsVer);
	return gotHyperV;
}
开发者ID:svn2github,项目名称:host-sflow,代码行数:76,代码来源:hypervUtil.c

示例2: main


//.........这里部分代码省略.........
        return 1;                // Program has failed.
    }

    //cout << "Connected to ROOT\\CIMV2 WMI namespace" << endl;


    // Step 5: --------------------------------------------------
    // Set security levels on the proxy -------------------------

    hres = CoSetProxyBlanket(
        pSvc,                        // Indicates the proxy to set
        RPC_C_AUTHN_WINNT,           // RPC_C_AUTHN_xxx
        RPC_C_AUTHZ_NONE,            // RPC_C_AUTHZ_xxx
        nullptr,                        // Server principal name 
        RPC_C_AUTHN_LEVEL_CALL,      // RPC_C_AUTHN_LEVEL_xxx 
        RPC_C_IMP_LEVEL_IMPERSONATE, // RPC_C_IMP_LEVEL_xxx
        nullptr,                        // client identity
        EOAC_NONE                    // proxy capabilities 
        );

    if (FAILED(hres))
    {
        cout << "Could not set proxy blanket. Error code = 0x"
            << hex << hres << endl;
        pSvc->Release();
        pLoc->Release();
        CoUninitialize();
        return 1;               // Program has failed.
    }

    // Step 6: --------------------------------------------------
    // Use the IWbemServices pointer to make requests of WMI ----

    // For example, get the name of the operating system
    IEnumWbemClassObject* pEnumerator = nullptr;
    hres = pSvc->ExecQuery(
        bstr_t("WQL"),
        bstr_t("SELECT * FROM Win32_Process"),
        WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY,
        nullptr,
        &pEnumerator);

    if (FAILED(hres))
    {
        cout << "Query for processes failed."
            << " Error code = 0x"
            << hex << hres << endl;
        pSvc->Release();
        pLoc->Release();
        CoUninitialize();
        return 1;               // Program has failed.
    }

    // Step 7: -------------------------------------------------
    // Get the data from the query in step 6 -------------------

    IWbemClassObject *pclsObj = nullptr;
    ULONG uReturn = 0;
    int i = 0;
    while (pEnumerator)
    {
        i++;
        HRESULT hr = pEnumerator->Next(WBEM_INFINITE, 1,
            &pclsObj, &uReturn);

        if (0 == uReturn)
        {
            break;
        }

        VARIANT vtId;
        pclsObj->Get(L"ProcessId", 0, &vtId, nullptr, nullptr);
        wprintf_s(L"%d\n", vtId.intVal);
        VARIANT vtName;
        pclsObj->Get(L"Name", 0, &vtName, nullptr, nullptr);
        if (vtName.bstrVal != nullptr)
            wprintf_s(L"%ls\n", vtName.bstrVal);
        else
            wprintf_s(L"\n");
        VARIANT vtCmd;
        pclsObj->Get(L"CommandLine", 0, &vtCmd, nullptr, nullptr);
        if (vtCmd.bstrVal != nullptr)
            wprintf_s(L"%ls\n", vtCmd.bstrVal);
        else
            wprintf_s(L"\n");
        VariantClear(&vtId);
        VariantClear(&vtName);
        VariantClear(&vtCmd);

        pclsObj->Release();
    }
    // Cleanup
    // ========

    pSvc->Release();
    pLoc->Release();
    pEnumerator->Release();
    CoUninitialize();
    return 0;   // Program successfully completed.
}
开发者ID:DonJayamanne,项目名称:intellij-community,代码行数:101,代码来源:main.cpp

示例3: readWMISwitchPorts

/**
 * Gets the switch port info from WMI (switch port friendly name, ifSpeed) 
 * and merges into the list of existing ports.
 */
void readWMISwitchPorts(HSP *sp)
{
	myLog(LOG_INFO, "entering readWMISwitchPorts");
	BSTR path = SysAllocString(WMI_VIRTUALIZATION_NS_V2);
	HRESULT hr = S_FALSE;
	IWbemServices *pNamespace = NULL;

	hr = connectToWMI(path, &pNamespace);
	if (FAILED(hr)) {
		//only try the v2 namespace since this will only be present
		//with the extensible switch that supports sampling.
	    //don't try to get counters if there is no sampling.
		SysFreeString(path);
		myLog(LOG_INFO, "readWMISwitchPorts: virtualization namespace v2 not found");
		return;
	} else {
		SysFreeString(path);
	}

	BSTR queryLang = SysAllocString(L"WQL");
	wchar_t *query = L"SELECT * FROM Msvm_EthernetSwitchPort";
	IEnumWbemClassObject *switchPortEnum = NULL;
	hr = pNamespace->ExecQuery(queryLang, query, WBEM_FLAG_FORWARD_ONLY, NULL, &switchPortEnum);
	SysFreeString(queryLang);
	if (FAILED(hr)) {
		myLog(LOG_ERR,"readWMISwitchPorts: ExecQuery() failed for query %S error=0x%x", query, hr);
		pNamespace->Release();
		return;
	}

	if (sp->vAdaptorList == NULL) {
		sp->vAdaptorList = adaptorListNew();
	}
	IWbemClassObject *switchPortObj = NULL;

	hr = WBEM_S_NO_ERROR;
	while (WBEM_S_NO_ERROR == hr) {
		SFLAdaptor *vAdaptor = NULL;
		ULONG uReturned = 1;
		hr = switchPortEnum->Next(WBEM_INFINITE, 1, &switchPortObj, &uReturned);
		if (0 == uReturned) {
			break;
		}
		wchar_t *guidString = stringFromWMIProperty(switchPortObj, PROP_NAME);
		if (guidString != NULL) {
			char portGuid[FORMATTED_GUID_LEN+1];
			guidToString(guidString, (UCHAR *)portGuid, FORMATTED_GUID_LEN);
			myLog(LOG_INFO, "readWMISwitchPorts: portGuid=%s", portGuid);
			my_free(guidString);
			vAdaptor = adaptorListGet(sp->vAdaptorList, portGuid);
		}
		if (vAdaptor != NULL) {
			HVSVPortInfo *portInfo = (HVSVPortInfo *)vAdaptor->userData;
			wchar_t *switchName = stringFromWMIProperty(switchPortObj, PROP_SYSTEM_NAME);
			if (switchName != NULL) {
				if (portInfo->switchName != NULL) {
					my_free(portInfo->switchName);
				}
				portInfo->switchName = switchName;
			}
			wchar_t *friendlyName = stringFromWMIProperty(switchPortObj, PROP_ELEMENT_NAME);
			if (friendlyName != NULL) {
				if (portInfo->portFriendlyName != NULL) {
					my_free(portInfo->portFriendlyName);
				}
				portInfo->portFriendlyName = friendlyName;
			}
			setPortCountersInstance(vAdaptor);
			wchar_t *speedString = stringFromWMIProperty(switchPortObj, PROP_SPEED);
			if (speedString != NULL) {
				ULONGLONG ifSpeed = _wcstoui64(speedString, NULL, 10);
				vAdaptor->ifSpeed = ifSpeed;
				my_free(speedString);
			}
			//could also get ifDirection but FullDuplex=True always

			//Get the MACs and VM system name when we enumerate the vms.
			myLog(LOG_INFO, 
				  "readWMISwitchPorts: updated switch port %s %S portId=%u ifIndex=%u ifSpeed=%llu counterName=%S", 
				  vAdaptor->deviceName, portInfo->portFriendlyName, portInfo->portId, vAdaptor->ifIndex, 
				  vAdaptor->ifSpeed, portInfo->portCountersInstance);
		} else {
			myLog(LOG_INFO, "readWMISwitchPorts: vAdapter not found");
		}
		switchPortObj->Release();
	}
	switchPortEnum->Release();
	pNamespace->Release();
}
开发者ID:svn2github,项目名称:host-sflow,代码行数:93,代码来源:hypervSwitch.c

示例4: ExecuteMethodsInClass

HRESULT
ExecuteMethodsInClass(
    __in     IWbemServices* WbemServices,
    __in_opt PWCHAR UserId,
    __in_opt PWCHAR Password,
    __in_opt PWCHAR DomainName
    )

/*++

Routine Description:

    This routine enumerates the instances of the Toaster method class and
    executes the methods in the class for each instance.

Arguments:

    WbemServices - Pointer to the WBEM services interface used for accessing
        the WMI services.

    UserId - Pointer to the user id information or NULL.

    Password - Pointer to password or NULL. If the user id is not specified,
        this parameter is ignored.

    DomainName - Pointer to domain name or NULL. If the user id is not specified,
        this parameter is ignored.

Return Value:

    HRESULT Status code.

--*/

{
    HRESULT status = S_OK;

    IEnumWbemClassObject* enumerator  = NULL;
    IWbemClassObject* classObj        = NULL;
    IWbemClassObject* instanceObj     = NULL;

    const BSTR className   = SysAllocString(TOASTER_METHOD_CLASS);

    VARIANT pathVariable;
    _bstr_t instancePath;
    ULONG   nbrObjsSought = 1;
    ULONG   nbrObjsReturned;

    //
    // Create an Enumeration object to enumerate the instances of the given class.
    //
    status = WbemServices->CreateInstanceEnum(className,
                                              WBEM_FLAG_SHALLOW | WBEM_FLAG_RETURN_IMMEDIATELY | WBEM_FLAG_FORWARD_ONLY,
                                              NULL,
                                              &enumerator);
    if (FAILED(status)) {
        goto exit;
    }

    //
    // Set authentication information for the interface.
    //
    status = SetInterfaceSecurity(enumerator, UserId, Password, DomainName);
    if (FAILED(status)) {
        goto exit;
    }

    //
    // Get the class object for the method definition.
    //
    status = WbemServices->GetObject(className, 0, NULL, &classObj, NULL);
    if (FAILED(status)) {
        goto exit;
    }

    do {

        //
        // Get the instance object for each instance of the class.
        //
        status = enumerator->Next(WBEM_INFINITE,
                                  nbrObjsSought,
                                  &instanceObj,
                                  &nbrObjsReturned);

        if (status == WBEM_S_FALSE) {
            status = S_OK;
            break;
        }

        if (FAILED(status)) {
            if (status == WBEM_E_INVALID_CLASS) {
                printf("ERROR: Toaster driver may not be active on the system.\n");
            }
            goto exit;
        }

        //
        // To obtain the object path of the object for which the method has to be
        // executed, query the "__PATH" property of the WMI instance object.
//.........这里部分代码省略.........
开发者ID:kcrazy,项目名称:winekit,代码行数:101,代码来源:wmiexecute.cpp

示例5: RunWMIQuery

void CHardwareMonitor::RunWMIQuery(const char* qTable, const std::string &qType)
{
	if (pServicesOHM && pServicesSystem)
	{
		HRESULT hr;
		int dindex = 0;
		std::string query = "SELECT * FROM ";
		query.append(qTable);
		query.append(" WHERE SensorType = '");
		query.append(qType);
		query.append("'");
		IEnumWbemClassObject* pEnumerator = NULL; 
		hr = pServicesOHM->ExecQuery(L"WQL", bstr_t(query.c_str()), WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY, NULL, &pEnumerator);
		if (!FAILED(hr))
		{
			// Get the data from the query
			IWbemClassObject *pclsObj = NULL;
			while (pEnumerator)
			{
				ULONG uReturn = 0;
				HRESULT hr = pEnumerator->Next(WBEM_INFINITE, 1, &pclsObj, &uReturn);
				if (FAILED(hr) || (0 == uReturn))
				{
					break;
				}

				VARIANT vtProp;

				hr = pclsObj->Get(L"Name", 0, &vtProp, 0, 0);
				if (SUCCEEDED(hr))
				{
					std::string itemName = _bstr_t(vtProp.bstrVal);
					stdreplace(itemName, "#", "");
					VariantClear(&vtProp);

					hr = pclsObj->Get(L"Value", 0, &vtProp, 0, 0);
					if (SUCCEEDED(hr))
					{
						float fItemValue = float(vtProp.fltVal);
						std::ostringstream itemValue;
						if ((qType == "Load") || (qType == "Temperature")) {
							itemValue.precision(3);
						}
						itemValue << fItemValue;
						VariantClear(&vtProp);

						//hr = pclsObj->Get(L"InstanceId", 0, &vtProp, 0, 0);
						hr = pclsObj->Get(L"Identifier", 0, &vtProp, 0, 0); // instance id seems to drift
						if (SUCCEEDED(hr))
						{
							std::string itemId = _bstr_t(vtProp.bstrVal);
							if (itemId.find("/hdd") != std::string::npos)
							{
								itemName = itemId + " " + itemName;
							}
							//itemId = "WMI"+itemId;
							//_log.Log(LOG_NORM, "Hardware Monitor: %s, %s, %s",itemId.c_str(), itemName.c_str(),itemValue.str().c_str());
							UpdateSystemSensor(qType, dindex, itemName, itemValue.str());
							VariantClear(&vtProp);
							dindex++;
						}
					}
				}
				pclsObj->Release();
			}
			pEnumerator->Release();
		}
	}
	else {
		//_log.Log(LOG_NORM, "Hardware Monitor: pservices null");
	}
}
开发者ID:saeedhadi,项目名称:domoticz,代码行数:72,代码来源:HardwareMonitor.cpp

示例6: wmi_get_battery_info

int wmi_get_battery_info() {

	std::cout << "wmi_get_battery_info" << std::endl;

	//assert(_initialized);
	//assert(pcpu_load_comp);
	//assert(pcpu_load_user);
	//assert(pcpu_load_sys);

	//float& cpu_load_comp = *pcpu_load_comp;
	//float& cpu_load_user = *pcpu_load_user;
	//float& cpu_load_sys = *pcpu_load_sys;

	IEnumWbemClassObject* enumerator = 0;
	IWbemClassObject* object = 0;

	//cpu_load_comp = 0;
	//cpu_load_user = 0;

	bool user_logged = false;

	long long current_process_id = _current_process_id;

	
	enumerator = request(
		// uint16, uint32, uint16, uint32... 
		bstr_t("SELECT"
		" Availability, BatteryRechargeTime, BatteryStatus,"
		"Caption, DesignCapacity, DesignVoltage, FullChargeCapacity"
		" FROM  Win32_Battery")
	);
		
	
	ULONG uReturn;
	for(;;) {
		
		HRESULT result = enumerator->Next(WBEM_INFINITE, 1, &object, &uReturn);
		if(0 == uReturn) {
			break;
		}

		VARIANT var;
		VariantInit(&var);
		result = object->Get(L"Voltage", 0, &var, NULL, NULL );
		
		if (SUCCEEDED(result)) {
			Print(std::wcout, var);
			//unsigned short v = var.uiVal;
			//std::cout << "Availability: " << v << std::endl; 
		}
		
		VariantInit(&var);
		result = object->Get(L"DischargeRate", 0, &var, NULL, NULL );
		
		if (SUCCEEDED(result)) {
			Print(std::wcout, var);
			//unsigned int v = var.uiVal;
			//std::cout << "BatteryRechargeTime: " << v << std::endl; 
		}

		VariantInit(&var);
		result = object->Get(L"Caption", 0, &var, NULL, NULL );
		
		if (SUCCEEDED(result)) {
			Print(std::wcout, var);
			//unsigned int v = var.uiVal;
			//std::cout << "BatteryRechargeTime: " << v << std::endl; 
		}

		VariantInit(&var);
		result = object->Get(L"DesignCapacity", 0, &var, NULL, NULL );
		
		if (SUCCEEDED(result)) {
			Print(std::wcout, var);
			//unsigned int v = var.uiVal;
			//std::cout << "DesignCapacity: " << v << std::endl; 
		}

		VariantInit(&var);
		result = object->Get(L"DesignVoltage", 0, &var, NULL, NULL );
		
		if (SUCCEEDED(result)) {
			Print(std::wcout, var);
			//unsigned long long v = var.ullVal;
			//std::cout << "DesignVoltage: " << v << std::endl; 
		}

		VariantInit(&var);
		result = object->Get(L"FullChargeCapacity", 0, &var, NULL, NULL );
		
		if (SUCCEEDED(result)) {
			Print(std::wcout, var);
			//unsigned int v = var.uiVal;
			//std::cout << "FullChargeCapacity: " << v << std::endl; 
		}


		object->Release();
	} // for(;;)

//.........这里部分代码省略.........
开发者ID:hanappe,项目名称:low-energy-boinc,代码行数:101,代码来源:wmi.cpp

示例7: CoInitialize

//-----------------------------------------------------------------------------
// Enum each PNP device using WMI and check each device ID to see if it contains 
// "IG_" (ex. "VID_045E&PID_028E&IG_00").  If it does, then it’s an XInput device
// Unfortunately this information can not be found by just using DirectInput.
// Checking against a VID/PID of 0x028E/0x045E won't find 3rd party or future 
// XInput devices.
//
// This function stores the list of xinput devices in a linked list 
// at g_pXInputDeviceList, and IsXInputDevice() searchs that linked list
//-----------------------------------------------------------------------------
HRESULT CDirectInput8Manager::SetupForIsXInputDevice()
{
    IWbemServices*          pIWbemServices = NULL;
    IEnumWbemClassObject*   pEnumDevices   = NULL;
    IWbemLocator*           pIWbemLocator  = NULL;
    IWbemClassObject*       pDevices[20]   = {0};
    BSTR                    bstrDeviceID   = NULL;
    BSTR                    bstrClassName  = NULL;
    BSTR                    bstrNamespace  = NULL;
    DWORD                   uReturned      = 0;
    bool                    bCleanupCOM    = false;
    UINT                    iDevice        = 0;
    VARIANT                 var;
    HRESULT                 hr;

    // CoInit if needed
    hr = CoInitialize(NULL);
    bCleanupCOM = SUCCEEDED(hr);

    // Create WMI
    hr = CoCreateInstance( __uuidof(WbemLocator),
                           NULL,
                           CLSCTX_INPROC_SERVER,
                           __uuidof(IWbemLocator),
                           (LPVOID*) &pIWbemLocator);
    if( FAILED(hr) || pIWbemLocator == NULL ) 
        goto LCleanup; 

    // Create BSTRs for WMI
    bstrNamespace = SysAllocString( L"\\\\.\\root\\cimv2" ); if( bstrNamespace == NULL ) goto LCleanup;
    bstrDeviceID  = SysAllocString( L"DeviceID" );           if( bstrDeviceID == NULL )  goto LCleanup;        
    bstrClassName = SysAllocString( L"Win32_PNPEntity" );    if( bstrClassName == NULL ) goto LCleanup;        
    
    // Connect to WMI 
    hr = pIWbemLocator->ConnectServer( bstrNamespace, NULL, NULL, 0L, 
                                       0L, NULL, NULL, &pIWbemServices );
    if( FAILED(hr) || pIWbemServices == NULL )
        goto LCleanup; 

    // Switch security level to IMPERSONATE
    CoSetProxyBlanket( pIWbemServices, RPC_C_AUTHN_WINNT, RPC_C_AUTHZ_NONE, NULL, 
                       RPC_C_AUTHN_LEVEL_CALL, RPC_C_IMP_LEVEL_IMPERSONATE, NULL, 0 );                    

    // Get list of Win32_PNPEntity devices
    hr = pIWbemServices->CreateInstanceEnum( bstrClassName, 0, NULL, &pEnumDevices ); 
    if( FAILED(hr) || pEnumDevices == NULL )
        goto LCleanup;

    // Loop over all devices
    for( ;; )
    {
        // Get 20 at a time
        hr = pEnumDevices->Next( 10000, 20, pDevices, &uReturned );
        if( FAILED(hr) )
            goto LCleanup;
        if( uReturned == 0 )
            break;

        for( iDevice=0; iDevice<uReturned; iDevice++ )
        {
            // For each device, get its device ID
            hr = pDevices[iDevice]->Get( bstrDeviceID, 0L, &var, NULL, NULL );
            if( SUCCEEDED( hr ) && var.vt == VT_BSTR && var.bstrVal != NULL )
            {
                // Check if the device ID contains "IG_".  If it does, then it’s an XInput device
                // Unfortunately this information can not be found by just using DirectInput 
                if( wcsstr( var.bstrVal, L"IG_" ) )
                {
                    // If it does, then get the VID/PID from var.bstrVal
                    DWORD dwPid = 0, dwVid = 0;
                    WCHAR* strVid = wcsstr( var.bstrVal, L"VID_" );
                    if( strVid && swscanf( strVid, L"VID_%4X", &dwVid ) != 1 )
                        dwVid = 0;
                    WCHAR* strPid = wcsstr( var.bstrVal, L"PID_" );
                    if( strPid && swscanf( strPid, L"PID_%4X", &dwPid ) != 1 )
                        dwPid = 0;

                    DWORD dwVidPid = MAKELONG( dwVid, dwPid );

                    // Add the VID/PID to a linked list
                    XINPUT_DEVICE_NODE* pNewNode = new XINPUT_DEVICE_NODE;
                    if( pNewNode )
                    {
                        pNewNode->dwVidPid = dwVidPid;
                        pNewNode->pNext = m_pXInputDeviceList;
                        m_pXInputDeviceList = pNewNode;
                    }
                }
            }   
            SAFE_RELEASE( pDevices[iDevice] );
//.........这里部分代码省略.........
开发者ID:ogata-lab,项目名称:DirectInputRTC,代码行数:101,代码来源:DirectInput8Manager.cpp

示例8: GetVideoMemoryViaWMI

HRESULT GetVideoMemoryViaWMI( WCHAR* strInputDeviceID, DWORD* pdwAdapterRam )
{
	HRESULT hr;
	bool bGotMemory = false;
	HRESULT hrCoInitialize = S_OK;
	IWbemLocator* pIWbemLocator = nullptr;
	IWbemServices* pIWbemServices = nullptr;
	BSTR pNamespace = nullptr;

	*pdwAdapterRam = 0;
	hrCoInitialize = CoInitialize( 0 );

	hr = CoCreateInstance( CLSID_WbemLocator,
						   nullptr,
						   CLSCTX_INPROC_SERVER,
						   IID_IWbemLocator,
						   ( LPVOID* )&pIWbemLocator );
#ifdef PRINTF_DEBUGGING
	if( FAILED( hr ) ) wprintf( L"WMI: CoCreateInstance failed: 0x%0.8x\n", hr );
#endif

	if( SUCCEEDED( hr ) && pIWbemLocator )
	{
		// Using the locator, connect to WMI in the given namespace.
		pNamespace = SysAllocString( L"\\\\.\\root\\cimv2" );

		hr = pIWbemLocator->ConnectServer( pNamespace, nullptr, nullptr, 0L,
										   0L, nullptr, nullptr, &pIWbemServices );
#ifdef PRINTF_DEBUGGING
		if( FAILED( hr ) ) wprintf( L"WMI: pIWbemLocator->ConnectServer failed: 0x%0.8x\n", hr );
#endif
		if( SUCCEEDED( hr ) && pIWbemServices != 0 )
		{
			HINSTANCE hinstOle32 = nullptr;

			hinstOle32 = LoadLibraryW( L"ole32.dll" );
			if( hinstOle32 )
			{
				PfnCoSetProxyBlanket pfnCoSetProxyBlanket = nullptr;

				pfnCoSetProxyBlanket = ( PfnCoSetProxyBlanket )GetProcAddress( hinstOle32, "CoSetProxyBlanket" );
				if( pfnCoSetProxyBlanket != 0 )
				{
					// Switch security level to IMPERSONATE.
					pfnCoSetProxyBlanket( pIWbemServices, RPC_C_AUTHN_WINNT, RPC_C_AUTHZ_NONE, nullptr,
										  RPC_C_AUTHN_LEVEL_CALL, RPC_C_IMP_LEVEL_IMPERSONATE, nullptr, 0 );
				}

				FreeLibrary( hinstOle32 );
			}

			IEnumWbemClassObject* pEnumVideoControllers = nullptr;
			BSTR pClassName = nullptr;

			pClassName = SysAllocString( L"Win32_VideoController" );

			hr = pIWbemServices->CreateInstanceEnum( pClassName, 0,
													 nullptr, &pEnumVideoControllers );
#ifdef PRINTF_DEBUGGING
			if( FAILED( hr ) ) wprintf( L"WMI: pIWbemServices->CreateInstanceEnum failed: 0x%0.8x\n", hr );
#endif

			if( SUCCEEDED( hr ) && pEnumVideoControllers )
			{
				IWbemClassObject* pVideoControllers[10] = {0};
				DWORD uReturned = 0;
				BSTR pPropName = nullptr;

				// Get the first one in the list
				pEnumVideoControllers->Reset();
				hr = pEnumVideoControllers->Next( 5000,             // timeout in 5 seconds
												  10,                  // return the first 10
												  pVideoControllers,
												  &uReturned );
#ifdef PRINTF_DEBUGGING
				if( FAILED( hr ) ) wprintf( L"WMI: pEnumVideoControllers->Next failed: 0x%0.8x\n", hr );
				if( uReturned == 0 ) wprintf( L"WMI: pEnumVideoControllers uReturned == 0\n" );
#endif

				VARIANT var;
				if( SUCCEEDED( hr ) )
				{
					bool bFound = false;
					for( UINT iController = 0; iController < uReturned; iController++ )
					{
						if ( !pVideoControllers[iController] )
							continue;

						pPropName = SysAllocString( L"PNPDeviceID" );
						hr = pVideoControllers[iController]->Get( pPropName, 0L, &var, nullptr, nullptr );
#ifdef PRINTF_DEBUGGING
						if( FAILED( hr ) )
							wprintf( L"WMI: pVideoControllers[iController]->Get PNPDeviceID failed: 0x%0.8x\n", hr );
#endif
						if( SUCCEEDED( hr ) )
						{
							if( wcsstr( var.bstrVal, strInputDeviceID ) != 0 )
								bFound = true;
						}
						VariantClear( &var );
//.........这里部分代码省略.........
开发者ID:SimFederal,项目名称:SingularityViewer,代码行数:101,代码来源:lldxhardware.cpp

示例9: getclock

static unsigned int getclock(void)
{
	unsigned int clock;
#ifdef KONOHA_ON_MACOSX
	int cpu_sels[2] = { CTL_HW, HW_CPU_FREQ };
	size_t len = sizeof(int);
	sysctl(cpu_sels, 2, &clock, &len, NULL, 0);
	clock = (unsigned int) clock / (1000 * 1000);
#elif defined(KONOHA_ON_WINDOWS)
	HRESULT hres;
	hres = CoInitializeEx(0, COINIT_MULTITHREADED);
	hres = CoInitializeSecurity(
		NULL,
		-1,                          // COM authentication
		NULL,                        // Authentication services
		NULL,                        // Reserved
		RPC_C_AUTHN_LEVEL_DEFAULT,   // Default authentication
		RPC_C_IMP_LEVEL_IMPERSONATE, // Default Impersonation
		NULL,                        // Authentication info
		EOAC_NONE,                   // Additional capabilities
		NULL                         // Reserved
		);
	IWbemLocator *pLoc = NULL;
	hres = CoCreateInstance(
		CLSID_WbemLocator,
		0,
		CLSCTX_INPROC_SERVER, 
		IID_IWbemLocator, (LPVOID *) &pLoc);
	IWbemServices *pSvc = NULL;
	hres = pLoc->ConnectServer(
		_bstr_t(L"ROOT\\CIMV2"), // Object path of WMI namespace
		NULL,                    // User name. NULL = current user
		NULL,                    // User password. NULL = current
		0,                       // Locale. NULL indicates current
		NULL,                    // Security flags.
		0,                       // Authority (e.g. Kerberos)
		0,                       // Context object
		&pSvc                    // pointer to IWbemServices proxy
		);
	hres = CoSetProxyBlanket(
		pSvc,                        // Indicates the proxy to set
		RPC_C_AUTHN_WINNT,           // RPC_C_AUTHN_xxx
		RPC_C_AUTHZ_NONE,            // RPC_C_AUTHZ_xxx
		NULL,                        // Server principal name
		RPC_C_AUTHN_LEVEL_CALL,      // RPC_C_AUTHN_LEVEL_xxx
		RPC_C_IMP_LEVEL_IMPERSONATE, // RPC_C_IMP_LEVEL_xxx
		NULL,                        // client identity
		EOAC_NONE                    // proxy capabilities
		);
	IEnumWbemClassObject* pEnumerator = NULL;
	hres = pSvc->ExecQuery(
		bstr_t("WQL"),
		bstr_t("SELECT * FROM Win32_Processor"),
		WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY,
		NULL,
		&pEnumerator);
	IWbemClassObject *pclsObj;
	ULONG uReturn = 0;
	
	while (pEnumerator) {
		HRESULT hr = pEnumerator->Next(
			WBEM_INFINITE,
			1,
			&pclsObj,
			&uReturn
			);
		if (uReturn == 0) { break; }
		VARIANT vtProp;
		hr = pclsObj->Get(L"MaxClockSpeed", 0, &vtProp, 0, 0);
		clock = (unsigned int)vtProp.bstrVal;
		VariantClear(&vtProp);
		pclsObj->Release();
	}
	pSvc->Release();
	pLoc->Release();
	pEnumerator->Release();
	CoUninitialize();
#elif defined(KONOHA_ON_LINUX)
	char buf[64] = {'\0'}, *data = buf;
	const char *cpumhz = "cpu MHz";
	size_t len = strlen(cpumhz);
	FILE *fp = fopen("/proc/cpuinfo","r");
	while (fgets( buf, 64, fp ) != NULL){
		if ( strncmp(buf, cpumhz, len) == 0){
			data = strstr(buf, cpumhz);
			break;
		}
	}
	while (!isdigit(*data)) {
		data++;
	}
	clock = (unsigned int) atoi(data) / 1000;
	fclose(fp);

#else
	TODO();
#endif
	return clock;
}
开发者ID:imasahiro,项目名称:konoha-jit-deprecated,代码行数:99,代码来源:security.c

示例10: readSystemUUID

int readSystemUUID(u_char *uuidbuf){
	int	                    gotData = NO;
	BSTR                    path = SysAllocString(L"root\\wmi");
	BSTR                    className = SysAllocString(L"MSSmBios_RawSMBiosTables");
	BSTR                    propName = SysAllocString(L"SMBiosData");
	ULONG                   uReturned = 1;
	HRESULT                 hr = S_FALSE;
	IWbemLocator            *pLocator = NULL;
	IWbemServices           *pNamespace = NULL;
	IEnumWbemClassObject    *pEnumSMBIOS = NULL;
	IWbemClassObject        *pSmbios = NULL;
	CIMTYPE                 type;
	VARIANT                 pVal;
	SAFEARRAY               *pArray = NULL;
	smbiosHeader            *smbiosData;
	u_char                  *uuidPtr;
	DWORD                   smbufSize;

	hr =  CoInitializeEx(0, COINIT_MULTITHREADED);
	if (! SUCCEEDED( hr ) ){
		myLog(LOG_ERR,"readSystemUUID: failed to initialize COM");
		gotData = NO;
		goto Cleanup;
	}
	
	hr =  CoInitializeSecurity(NULL,-1,NULL,NULL,RPC_C_AUTHN_LEVEL_DEFAULT,RPC_C_IMP_LEVEL_IMPERSONATE,NULL,EOAC_NONE,NULL);
	hr = CoCreateInstance( CLSID_WbemLocator, NULL, CLSCTX_INPROC_SERVER, IID_IWbemLocator, (LPVOID *) &pLocator );
	if(! SUCCEEDED( hr ) ){
		myLog(LOG_ERR,"readSystemUUID: failed to create WMI instance");
		gotData = NO;
		goto Cleanup;
	}

	hr = pLocator->ConnectServer(path, NULL, NULL, NULL, 0, NULL, NULL, &pNamespace );
	pLocator->Release();
	if( WBEM_S_NO_ERROR != hr ){
		myLog(LOG_ERR,"getSystemUUID: ConnectServer() failed for namespace");
		gotData = NO;
		goto Cleanup;
	}

	hr = pNamespace->CreateInstanceEnum(className, 0, NULL, &pEnumSMBIOS );
	pNamespace->Release();
	if (! SUCCEEDED( hr ) ){
		myLog(LOG_ERR,"getSystemUUID: CreateInstanceEnum() failed for MSSmBios_RawSMBiosTables");
		gotData = NO;
		goto Cleanup;
	}

	hr = pEnumSMBIOS->Next(4000, 1, &pSmbios, &uReturned );
	pEnumSMBIOS->Release();
	if ( 1 != uReturned ){
		myLog(LOG_ERR,"getSystemUUID: Next() failed for pEnumSMBIOS");
		gotData = NO;
		goto Cleanup;
	}
	
	pSmbios->Get(propName,0L,&pVal,&type,NULL);
	if ( ( VT_UI1 | VT_ARRAY) != pVal.vt){
		myLog(LOG_ERR,"getSystemUUID: Get() failed for pSmbios");
	    gotData = NO;
		goto Cleanup;
	}

	pArray = V_ARRAY(&pVal);
	smbufSize = pArray->rgsabound[0].cElements;
	smbiosData = (smbiosHeader*)my_calloc(smbufSize);
	if(!smbiosData){
		myLog(LOG_ERR,"getSystemUUID: failed to allocate buffer for smbiosData");
		gotData = NO;
		goto Cleanup;
	}
	memcpy((void*)smbiosData,pArray->pvData,smbufSize);
	uuidPtr = (u_char*)getUUIDPtr(smbufSize,smbiosData);
	if(!uuidPtr){
		myLog(LOG_ERR,"getSystemUUID: failed to find UUID in SMBIOS");
		gotData = NO;
		goto Cleanup;
	}
	memcpy((void*)uuidbuf,uuidPtr,16);
	gotData = YES;

Cleanup:
	SysFreeString(propName);
	SysFreeString(className);
	SysFreeString(path);
	if(smbiosData) my_free(smbiosData);

	return gotData;
}
开发者ID:Chansie,项目名称:host-sflow,代码行数:90,代码来源:readSystemUUID.c

示例11: CoCreateInstance

BOOL CEnumerateSerial::UsingWMI(CSimpleArray<UINT>& ports, CSimpleArray<CString>& friendlyNames)
#endif
{
  //Make sure we clear out any elements which may already be in the array(s)
#if defined CENUMERATESERIAL_USE_STL
  ports.clear();
  friendlyNames.clear();
#else
  ports.RemoveAll();
  friendlyNames.RemoveAll();
#endif  

  //What will be the return value
  BOOL bSuccess = FALSE;

  //Create the WBEM locator
  IWbemLocator* pLocator = NULL;
  HRESULT hr = CoCreateInstance(CLSID_WbemLocator, NULL, CLSCTX_INPROC_SERVER, IID_IWbemLocator, reinterpret_cast<void**>(&pLocator));
  if (SUCCEEDED(hr))
  {
    IWbemServices* pServices = NULL;
    hr = pLocator->ConnectServer(_bstr_t("\\\\.\\root\\cimv2"), NULL, NULL, NULL, 0, NULL, NULL, &pServices);
    if (SUCCEEDED(hr))
    {
      //Execute the query
      IEnumWbemClassObject* pClassObject = NULL;
      hr = pServices->CreateInstanceEnum(_bstr_t("Win32_SerialPort"), WBEM_FLAG_RETURN_WBEM_COMPLETE, NULL, &pClassObject);
      if (SUCCEEDED(hr))
      {
        bSuccess = TRUE;

        //Now enumerate all the ports
        hr = WBEM_S_NO_ERROR;

        //Final Next will return WBEM_S_FALSE
        while (hr == WBEM_S_NO_ERROR)
        {
          ULONG uReturned = 0;
          IWbemClassObject* apObj[10];
          memset(apObj, 0, sizeof(apObj));
          hr = pClassObject->Next(WBEM_INFINITE, 10, reinterpret_cast<IWbemClassObject**>(apObj), &uReturned);
          if (SUCCEEDED(hr))
          {
            for (ULONG n=0; n<uReturned; n++)
            {
              VARIANT varProperty1;
              VariantInit(&varProperty1);
              HRESULT hrGet = apObj[n]->Get(L"DeviceID", 0, &varProperty1, NULL, NULL);
              if (SUCCEEDED(hrGet) && (varProperty1.vt == VT_BSTR) && (wcslen(varProperty1.bstrVal) > 3))
              {
                //If it looks like "COMX" then add it to the array which will be returned
                if ((_wcsnicmp(varProperty1.bstrVal, L"COM", 3) == 0) && IsNumeric(&(varProperty1.bstrVal[3]), TRUE))
                {
                  //Work out the port number
                  int nPort = _wtoi(&(varProperty1.bstrVal[3]));
                #if defined CENUMERATESERIAL_USE_STL
                  ports.push_back(nPort);
                #else
                  ports.Add(nPort);
                #endif

                  //Also get the friendly name of the port
                  VARIANT varProperty2;
                  VariantInit(&varProperty2);
                  if (SUCCEEDED(apObj[n]->Get(L"Name", 0, &varProperty2, NULL, NULL)) && (varProperty2.vt == VT_BSTR))
                  {  
                #if defined CENUMERATESERIAL_USE_STL
                  #if defined _UNICODE  
                    std::wstring szName(varProperty2.bstrVal);
                  #else
                    CAutoHeapAlloc szAsciiValue;
                    int nLengthA = WideCharToMultiByte(CP_ACP, 0, varProperty2.bstrVal, -1, NULL, 0, NULL, NULL);
                    if (nLengthA)
                    {
                      if (szAsciiValue.Allocate(nLengthA))
                        WideCharToMultiByte(CP_ACP, 0, varProperty2.bstrVal, -1, static_cast<LPSTR>(szAsciiValue.m_pData), nLengthA, NULL, NULL);
                    }

                    std::string szName(static_cast<LPSTR>(szAsciiValue.m_pData));
                  #endif
                    friendlyNames.push_back(szName);
                  #else
                    friendlyNames.Add(CString(varProperty2.bstrVal));    
                  #endif
                  }
                  else
                  {
                  #if defined CENUMERATESERIAL_USE_STL
                    friendlyNames.push_back(_T(""));
                  #else
                    friendlyNames.Add(_T(""));
                  #endif  
                  }

                  //Free up the variant;
                  VariantClear(&varProperty2);
                }
              }

              //Free up the variant;
//.........这里部分代码省略.........
开发者ID:gdijaejung,项目名称:Common,代码行数:101,代码来源:enumser.cpp

示例12: if

/////////////////////////////////////////////////////////////////////////////
//++
//
//  CPartitionInfo:HrGetLogicalDisks
//
//  Description:
//      Get the logical disks for the passed in partition.
//
//  Arguments:
//      pPartitionIn
//          WMI partition object to query on.
//
//  Return Value:
//      S_OK
//          Success
//
//      S_FALSE
//          The file system was not NTFS.
//
//      Other
//          An error occurred.
//
//  Remarks:
//      None.
//
//--
//////////////////////////////////////////////////////////////////////////////
HRESULT
CPartitionInfo::HrGetLogicalDisks(
    IWbemClassObject * pPartitionIn
    )
{
    HRESULT                 hr;
    VARIANT                 var;
    WCHAR                   szBuf[ 256 ];
    IEnumWbemClassObject *  pLogicalDisks = NULL;
    IWbemClassObject *      pLogicalDisk = NULL;
    ULONG                   ulReturned;
    BSTR                    bstrQuery = NULL;
    BSTR                    bstrWQL = NULL;

    VariantInit( &var );

    bstrWQL = SysAllocString( L"WQL" );
    if ( bstrWQL == NULL )
    {
        hr = E_OUTOFMEMORY;
        STATUS_REPORT_REF(
                  TASKID_Major_Find_Devices
                , TASKID_Minor_HrGetLogicalDisks
                , IDS_ERROR_OUTOFMEMORY
                , IDS_ERROR_OUTOFMEMORY_REF
                , hr
                );
        goto Cleanup;
    } // if:

    //
    //  Need to enum the logical disk(s) of this partition to determine if it is booted
    //  bootable.
    //
    hr = HrGetWMIProperty( pPartitionIn, L"DeviceID", VT_BSTR, &var );
    if ( FAILED( hr ) )
    {
        goto Cleanup;
    } // if:

    hr = StringCchPrintfW(
                      szBuf
                    , RTL_NUMBER_OF( szBuf )
                    , L"Associators of {Win32_DiskPartition.DeviceID='%ws'} where AssocClass=Win32_LogicalDiskToPartition"
                    , var.bstrVal
                    );
    if ( FAILED( hr ) )
    {
        goto Cleanup;
    } // if:

    bstrQuery = SysAllocString( szBuf );
    if ( bstrQuery == NULL )
    {
        hr = E_OUTOFMEMORY;
        STATUS_REPORT_REF(
                  TASKID_Major_Find_Devices
                , TASKID_Minor_HrGetLogicalDisks
                , IDS_ERROR_OUTOFMEMORY
                , IDS_ERROR_OUTOFMEMORY_REF
                , hr
                );
        goto Cleanup;
    } // if:

    hr = m_pIWbemServices->ExecQuery( bstrWQL, bstrQuery, WBEM_FLAG_FORWARD_ONLY, NULL, &pLogicalDisks );
    if ( FAILED( hr ) )
    {
        STATUS_REPORT_REF(
              TASKID_Major_Find_Devices
            , TASKID_Minor_WMI_Logical_Disks_Qry_Failed
            , IDS_ERROR_WMI_DISKS_QRY_FAILED
            , IDS_ERROR_WMI_DISKS_QRY_FAILED_REF
//.........这里部分代码省略.........
开发者ID:SatishSara,项目名称:zxlooong,代码行数:101,代码来源:CPartitionInfo.cpp

示例13: GetOSName

//
//   函数: GetOSName(PWSTR, DWORD)
//
//   目的: 获取当前操作系统的名字(例如:"Microsoft Windows 7 企业版").
//
//   参数:
//   * pszName - 存放操作系统名的缓冲区. 
//   * cch - 由pszName所指向的缓冲区大小,以字符形式.
//
//   返回值: 如果函数成功返回TRUE.
//
BOOL GetOSName(PWSTR pszName, DWORD cch)
{
    HRESULT hr = S_OK;
    IWbemLocator *pLoc = NULL;
    IWbemServices *pSvc = NULL;
    IEnumWbemClassObject *pEnumerator = NULL;
    PCWSTR pszMachineName = L".";

    // 通过调用 CoInitializeEx初始化COM参数.
    hr = CoInitializeEx(0, COINIT_MULTITHREADED);
    if (FAILED(hr))
    {
        return FALSE;
    }

    // 通过调用CoInitializeSecurity初始化COM进程安全. 
    hr = CoInitializeSecurity(
        NULL, 
        -1,                             // COM 认证
        NULL,                           // 认证服务
        NULL,                           // 保留
        RPC_C_AUTHN_LEVEL_DEFAULT,      // 默认认证
        RPC_C_IMP_LEVEL_IDENTIFY,       // 默认身份 
        NULL,                           // 认证信息
        EOAC_NONE,                      // 额外的能力
        NULL                            // 保留
        );
    if (FAILED(hr))
    {
        goto Cleanup;
    }

    // 通过调用CoCreateInstance获得WMI的初始定位器. 
    hr = CoCreateInstance(CLSID_WbemLocator, 0, CLSCTX_INPROC_SERVER, 
        IID_IWbemLocator, reinterpret_cast<LPVOID *>(&pLoc));
    if (FAILED(hr))
    {
        goto Cleanup;
    }

    // 通过IWbemLocator::ConnectServer连接到WMI.
    wchar_t szPath[200];
    hr = StringCchPrintf(szPath, ARRAYSIZE(szPath), L"\\\\%s\\root\\cimv2", 
        pszMachineName);
    if (FAILED(hr))
    {
        goto Cleanup;
    }

    hr = pLoc->ConnectServer(
        bstr_t(szPath),                 // WMI名空间的路径
        NULL,                           // 用户名
        NULL,                           // 用户密码
        NULL,                           // 本地
        NULL,                           // 安全标志
        NULL,                           // 权限
        NULL,                           // 上下文对象
        &pSvc                           // IWbemServices 代理
        );
    if (FAILED(hr))
    {
        goto Cleanup;
    }

    // 在WMI连接中设置安全级别.
    hr = CoSetProxyBlanket(
        pSvc,                           // 指明代理来设置
        RPC_C_AUTHN_DEFAULT,            // RPC_C_AUTHN_xxx
        RPC_C_AUTHZ_DEFAULT,            // RPC_C_AUTHZ_xxx
        COLE_DEFAULT_PRINCIPAL,         // 主要服务器名字
        RPC_C_AUTHN_LEVEL_PKT_PRIVACY,  // RPC_C_AUTHN_LEVEL_xxx 
        RPC_C_IMP_LEVEL_IMPERSONATE,    // RPC_C_IMP_LEVEL_xxx
        NULL,                           // 客户身份
        EOAC_NONE                       // 代理功能 
        );
    if (FAILED(hr))
    {
        goto Cleanup;
    }

    // 使用IWbemServices指针提出WMI请求. 
    // 查询指明当前操作系统名的Win32_OperatingSystem.Caption.
    hr = pSvc->ExecQuery(bstr_t(L"WQL"), 
        bstr_t(L"SELECT Caption FROM Win32_OperatingSystem"),
        WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY, 
        NULL, &pEnumerator);
    if (FAILED(hr))
    {
        goto Cleanup;
//.........这里部分代码省略.........
开发者ID:cubika,项目名称:OneCode,代码行数:101,代码来源:PlatformDetector.cpp

示例14: RTDECL

RTDECL(int) RTSystemQueryDmiString(RTSYSDMISTR enmString, char *pszBuf, size_t cbBuf)
{
    AssertPtrReturn(pszBuf, VERR_INVALID_POINTER);
    AssertReturn(cbBuf > 0, VERR_INVALID_PARAMETER);
    *pszBuf = '\0';
    AssertReturn(enmString > RTSYSDMISTR_INVALID && enmString < RTSYSDMISTR_END, VERR_INVALID_PARAMETER);

    /*
     * Figure the property name before we start.
     */
    const char *pszPropName;
    switch (enmString)
    {
        case RTSYSDMISTR_PRODUCT_NAME:      pszPropName = "Name"; break;
        case RTSYSDMISTR_PRODUCT_VERSION:   pszPropName = "Version"; break;
        case RTSYSDMISTR_PRODUCT_UUID:      pszPropName = "UUID"; break;
        case RTSYSDMISTR_PRODUCT_SERIAL:    pszPropName = "IdentifyingNumber"; break;
        case RTSYSDMISTR_MANUFACTURER:      pszPropName = "Vendor"; break;

        default:
            return VERR_NOT_SUPPORTED;
    }

    /*
     * Before we do anything with COM, we have to initialize it.
     */
    HRESULT hrc = rtSystemDmiWinInitialize();
    if (FAILED(hrc))
        return VERR_NOT_SUPPORTED;

    int rc = VERR_NOT_SUPPORTED;
    BSTR pBstrPropName = rtSystemWinBstrFromUtf8(pszPropName);
    if (pBstrPropName)
    {
        /*
         * Instantiate the IWbemLocator, whatever that is and connect to the
         * DMI serve.
         */
        IWbemLocator *pLoc;
        hrc = CoCreateInstance(CLSID_WbemLocator,
                               0,
                               CLSCTX_INPROC_SERVER,
                               IID_IWbemLocator,
                               (LPVOID *)&pLoc);
        if (SUCCEEDED(hrc))
        {
            IWbemServices *pServices;
            hrc = rtSystemDmiWinConnectToServer(pLoc, "ROOT\\CIMV2", &pServices);
            if (SUCCEEDED(hrc))
            {
                /*
                 * Enumerate whatever it is we're looking at and try get
                 * the desired property.
                 */
                BSTR pBstrFilter = rtSystemWinBstrFromUtf8("Win32_ComputerSystemProduct");
                if (pBstrFilter)
                {
                    IEnumWbemClassObject *pEnum;
                    hrc = pServices->CreateInstanceEnum(pBstrFilter, 0, NULL, &pEnum);
                    if (SUCCEEDED(hrc))
                    {
                        do
                        {
                            IWbemClassObject *pObj;
                            ULONG cObjRet;
                            hrc = pEnum->Next(WBEM_INFINITE, 1, &pObj, &cObjRet);
                            if (   SUCCEEDED(hrc)
                                && cObjRet >= 1)
                            {
                                VARIANT Var;
                                VariantInit(&Var);
                                hrc = pObj->Get(pBstrPropName, 0, &Var, 0, 0);
                                if (   SUCCEEDED(hrc)
                                    && V_VT(&Var) == VT_BSTR)
                                {
                                    /*
                                     * Convert the BSTR to UTF-8 and copy it
                                     * into the return buffer.
                                     */
                                    char *pszValue;
                                    rc = RTUtf16ToUtf8(Var.bstrVal, &pszValue);
                                    if (RT_SUCCESS(rc))
                                    {
                                        rc = RTStrCopy(pszBuf, cbBuf, pszValue);
                                        RTStrFree(pszValue);
                                        hrc = WBEM_S_FALSE;
                                    }
                                }
                                VariantClear(&Var);
                                pObj->Release();
                            }
                        } while (hrc != WBEM_S_FALSE);

                        pEnum->Release();
                    }
                    SysFreeString(pBstrFilter);
                }
                else
                    hrc = E_OUTOFMEMORY;
                pServices->Release();
//.........这里部分代码省略.........
开发者ID:LastRitter,项目名称:vbox-haiku,代码行数:101,代码来源:RTSystemQueryDmiString-win.cpp

示例15: GetAndSetValuesInClass

HRESULT
GetAndSetValuesInClass(
    _In_     IWbemServices* WbemServices,
    _In_opt_ PWSTR UserId,
    _In_opt_ PWSTR Password,
    _In_opt_ PWSTR DomainName
    )

/*++

Routine Description:

    This routine enumerates the instances of the Toaster Device Information
    class and gets/sets the value of one of its Properties.

Arguments:

    WbemServices - Pointer to the WBEM services interface used for accessing
        the WMI services.

    UserId - Pointer to the user id information or NULL.

    Password - Pointer to password or NULL. If the user id is not specified,
        this parameter is ignored.

    DomainName - Pointer to domain name or NULL. If the user id is not specified,
        this parameter is ignored.

Return Value:

    HRESULT Status code.

--*/

{
    HRESULT status = S_OK;

    IEnumWbemClassObject* enumerator  = NULL;
    IWbemClassObject* classObj        = NULL;
    IWbemClassObject* instanceObj     = NULL;

    const BSTR className   = SysAllocString(TOASTER_DEVICE_INFO_CLASS);

    VARIANT instProperty;
    ULONG   nbrObjsSought = 1;
    ULONG   nbrObjsReturned;

    //
    // Create an Enumeration object to enumerate the instances of the given class.
    //
    status = WbemServices->CreateInstanceEnum(className,
                                              WBEM_FLAG_SHALLOW | WBEM_FLAG_RETURN_IMMEDIATELY | WBEM_FLAG_FORWARD_ONLY,
                                              NULL,
                                              &enumerator);
    if (FAILED(status)) {
        goto exit;
    }

    //
    // Set authentication information for the interface.
    //
    status = SetInterfaceSecurity(enumerator, UserId, Password, DomainName);
    if (FAILED(status)) {
        goto exit;
    }

    do {

        //
        // Get the instance object for each instance of the class.
        //
        status = enumerator->Next(WBEM_INFINITE,
                                  nbrObjsSought,
                                  &instanceObj,
                                  &nbrObjsReturned);

        if (status == WBEM_S_FALSE) {
            status = S_OK;
            break;
        }

        if (FAILED(status)) {
            if (status == WBEM_E_INVALID_CLASS) {
                printf("ERROR: Toaster driver may not be active on the system.\n");
            }
            goto exit;
        }

        //
        // To obtain the object path of the object for which the method has to be
        // executed, query the "__PATH" property of the WMI instance object.
        //
        status = instanceObj->Get(_bstr_t(L"__PATH"), 0, &instProperty, 0, 0);
        if (FAILED(status)) {
            goto exit;
        }

        printf("\n");
        printf("Instance Path .: %ws\n", (wchar_t*)instProperty.bstrVal);

//.........这里部分代码省略.........
开发者ID:0xhack,项目名称:Windows-driver-samples,代码行数:101,代码来源:wmigetset.cpp


注:本文中的IEnumWbemClassObject类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。