Getting a Handle to the Driver

CYUSB3

Getting a Handle to the Driver

Top Previous Next

In order to use the IOCTL codes supported by the driver, you will need to obtain a Windows handle to the driver.

 

A very simple way to accomplish this is to utilize the CyAPI class library. After creating a CCyUSBDevice object, a handle to the driver will have been setup automatically. Closing or deleting the CCyUSBDevice object frees the handle.

 

Example 1:

 

CCyUSBDevice *USBDevice = new CCyUSBDevice();

HANDLE hDevice = USBDevice->DeviceHandle();

.

.

.

.

delete USBDevice;

 

 

 

The more typical (and complex) way to obtain a handle is to make a sequence of SetupDi calls, passing the driver GUID declared in CyAPI.h. The default driver guid is defined as:

 

// {AE18AA60-7F6A-11d4-97DD-00010229B959}

static GUID CYUSBDRV_GUID = {0xae18aa60, 0x7f6a, 0x11d4, 0x97, 0xdd, 0x0, 0x1, 0x2, 0x29, 0xb9, 0x59};

 

The CyAPI library uses the following code to obtain a handle, using the GUID.

 

 

 

Example 2:

 

 

SP_DEVINFO_DATA devInfoData;

SP_DEVICE_INTERFACE_DATA  devInterfaceData;

PSP_INTERFACE_DEVICE_DETAIL_DATA functionClassDeviceData;

 

ULONG requiredLength = 0;

int deviceNumber = 0; // Can be other values if more than 1 device connected to driver

 

HDEVINFO hwDeviceInfo = SetupDiGetClassDevs ( (LPGUID) &CYUSBDRV_GUID,

                                            NULL,

                                            NULL,

                                            DIGCF_PRESENT|DIGCF_INTERFACEDEVICE);

 

if (hwDeviceInfo != INVALID_HANDLE_VALUE) {

 

devInterfaceData.cbSize = sizeof(devInterfaceData);

 

if (SetupDiEnumDeviceInterfaces ( hwDeviceInfo, 0, (LPGUID) &CYUSBDRV_GUID,

                                 deviceNumber, &devInterfaceData)) {

 

 SetupDiGetInterfaceDeviceDetail ( hwDeviceInfo, &devInterfaceData, NULL, 0,

                                   &requiredLength, NULL);

 

 ULONG predictedLength = requiredLength;

 

 functionClassDeviceData = (PSP_INTERFACE_DEVICE_DETAIL_DATA) malloc (predictedLength);

 functionClassDeviceData->cbSize = sizeof (SP_INTERFACE_DEVICE_DETAIL_DATA);

 

 devInfoData.cbSize = sizeof(devInfoData);

 

if (SetupDiGetInterfaceDeviceDetail (hwDeviceInfo,

                                      &devInterfaceData,

                                      functionClassDeviceData,

                                      predictedLength,

                                      &requiredLength,

                                      &devInfoData)) {

 

   hDevice = CreateFile (functionClassDeviceData->DevicePath,

                       GENERIC_WRITE | GENERIC_READ,

                       FILE_SHARE_WRITE | FILE_SHARE_READ,

                       NULL,

                       OPEN_EXISTING,

                       FILE_FLAG_OVERLAPPED,

                       NULL);

 

   free(functionClassDeviceData);

   SetupDiDestroyDeviceInfoList(hwDeviceInfo);

 }