获取服务对象

设备对象公开一个名为 Services 的属性,该属性返回服务对象的集合,该集合包含设备导出的每个服务的服务对象。 应用程序可以使用其服务 ID 按顺序遍历此集合,或请求特定服务。

VBScript 示例

以下示例是 VBScript 代码,用于提取设备导出的两个服务的服务对象。

' Get the service objects
services = device.Services
    
Set appService = services( "urn:upnp-org:serviceId:DVDVideo" )
Set xportService = services( "urn:upnp-org:serviceId:AVTransport" )

第一行通过查询 Services 属性从 Device 对象中提取 服务 集合。 接下来的两行通过指定服务 ID 从集合中获取两个所需服务对象。 还可以使用每个服务集合按顺序遍历 ...next 循环。

C++ 示例

以下示例演示从设备获取服务对象所需的 C++ 代码。 首先,示例代码查询传递给函数的接口上的 IUPnPDevice::Services 属性。 这会使用 IUPnPServices 接口返回服务集合。 若要获取单个服务对象,请使用 Item 方法,并指定请求的服务 ID。 若要按顺序遍历集合,请使用 IEnumVARIANT::ResetIEnumVARIANT::NextIEnumVARIANT::Skip 方法。 此示例类似于用于遍历 IUPnPDevices 集合的示例。

#include <windows.h>
#include <upnp.h>

#pragma comment(lib, "oleaut32.lib")


HRESULT ExtractServices(IUPnPDevice * pDevice)
{
    // Create a BSTR to hold the service name
    BSTR bstrServiceName = SysAllocString(L"urn:upnp-org:servicId:DVDVideo");
    if (NULL == bstrServiceName)
    {
        return E_OUTOFMEMORY;
    }
    // Get the list of services available on the device
    IUPnPServices * pServices = NULL;
    HRESULT hr = pDevice->get_Services(&pServices);
    if (SUCCEEDED(hr))
    {
        // Retrieve the service we are interested in
        IUPnPService * pAppService = NULL;
        hr = pServices->get_Item(bstrServiceName, &pAppService);
        if (SUCCEEDED(hr))
        {
            // Do something interesting with the service object
            pAppService->Release();
        }
        pServices->Release();
    }
    SysFreeString(bstrServiceName);
    return hr;
}