共用方式為


實作裝置存取物件

本主題說明如何具現化裝置存取物件,並用它來存取裝置。 具現化類別會實作 IDeviceIoControlICreateDeviceAccessAsync 介面。

指示

步驟 1

若要具現化裝置存取物件,您必須先呼叫 CreateDeviceAccessInstance 函式。 如果 CreateDeviceAccessInstance 成功,您可以呼叫 Wait 方法來等候異步操作完成。 如果 Wait 成功,您可以從 GetResult 方法擷取 IDeviceIoControl 物件(或適當的錯誤)。

HRESULT
CMyServer::Initialize(
        PCWSTR   pszDeviceInterfacePath
    )

/*++
Routine Description:

    This routine is called to initialize the Device Access object.
    It's not part of the constructor as the initialization can fail.
    It opens the device and gets the IDeviceIoControl interface to the device instance
    via the broker.

Arguments:
    pszDeviceInterfacePath - the device interface string that needs to be opened

Return Value:

    HRESULT

--*/

{
    HRESULT hr;
    ICreateDeviceAccessAsync *pDeviceAccess;

     //
     // Here's the actual open call.  This will *fail* if your lowbox does
     // not have the capability mapped to the interface class specified.
     // If you are running this as normal user, it will just pass through to
     // create file.
     //

   hr = CreateDeviceAccessInstance(pszDeviceInterfacePath,
                                   GENERIC_READ|GENERIC_WRITE,
                                   &pDeviceAccess);

    if (FAILED(hr)) {
        return hr;
    }

    if (SUCCEEDED(hr)) {
        hr = pDeviceAccess->Wait(INFINITE);
    }

    if (SUCCEEDED(hr)) {
        hr = pDeviceAccess->GetResult(IID_IDeviceIoControl,
                                            (void **)&m_pDeviceIoControl);
    }

    pDeviceAccess->Release();

    return hr;
}

步驟 2

這是呼叫 DeviceIoControlSync 方法的範例。

IFACEMETHODIMP 
CMyServer::put_SevenSegmentDisplay(
    BYTE   value
    )
/*++

Routine Description:
    This routine puts the display value into the device.

Arguments:
    
    value - The value to be written to the device.
    
Return Value:

    HRESULT

--*/
{
    BYTE sevenSegment = 0;
    HRESULT hr;

    if (value >= ARRAYSIZE(g_NumberToMask)) {
        return E_INVALIDARG;
    }


    sevenSegment = g_NumberToMask[value];
    hr = m_pDeviceIoControl->DeviceIoControlSync(
                         IOCTL_OSRUSBFX2_SET_7_SEGMENT_DISPLAY,
                         &sevenSegment,
                         sizeof(BYTE),
                         NULL,
                         0,
                         NULL
                         );

    return hr;
}

備註

您也可以使用 DeviceIoControlAsync 方法,以異步方式傳送 IOCTL。 在此情況下,您必須實 作 IDeviceRequestCompletionCallback 介面。

自定義驅動程式存取範例適用於內部裝置的 UWP 裝置應用程式,硬體開發人員中心