当有多个相同固件的USB设备连接到同一台PC上时,应该怎样分别控制他们呢?
源码来源:ChaitanyaV_61
在USB设备枚举过程中,Windows系统将为每个设备分配一个特定的设备枚举索引。此外,设备枚举过程将为每个USB设备创建唯一的设备实例路径。在本文定义的函数的帮助下,通过将设备的实例路径映射到其各自的设备枚举索引,可以使用此设备实例路径来区分具有相同VID和PID的设备。
添加头文件并链接库。
#include
#pragma comment(lib, "setupapi.lib")
在源码的基础上做了调整,使得函数可以返回一个 string 类型的路径。
#include
void Wchar_tToString(string& szDst, wchar_t *wchar)
{
wchar_t * wText = wchar;
DWORD dwNum = WideCharToMultiByte(CP_OEMCP, NULL, wText, -1, NULL, 0, NULL, FALSE);//WideCharToMultiByte的运用
char *psText; // psText为char*的临时数组,作为赋值给std::string的中间变量
psText = new char[dwNum];
WideCharToMultiByte(CP_OEMCP, NULL, wText, -1, psText, dwNum, NULL, FALSE);//WideCharToMultiByte的再次运用
szDst = psText;// std::string赋值
delete[]psText;// psText的清除
}
string GetDevicePath(int deviceNumber)
{
//Initialization
string usbDevicePath = "";
GUID CyDrvGuid = { 0xae18aa60, 0x7f6a, 0x11d4, 0x97, 0xdd, 0x0, 0x1, 0x2, 0x29, 0xb9, 0x59 }; // cyusb3 guid
SP_DEVINFO_DATA devInfoData;
SP_DEVICE_INTERFACE_DATA devInterfaceData;
PSP_INTERFACE_DEVICE_DETAIL_DATA functionClassDeviceData;
ULONG requiredLength = 0;
HDEVINFO hwDeviceInfo = SetupDiGetClassDevs((LPGUID)& CyDrvGuid, //Returns a handle to the device information set
NULL,
NULL,
DIGCF_PRESENT | DIGCF_INTERFACEDEVICE);
if (hwDeviceInfo != INVALID_HANDLE_VALUE) { //checks if the handle is invalid
devInterfaceData.cbSize = sizeof(devInterfaceData); //get the size of devInterfaceData structure
//enumerates the device interfaces that are contained in a device information set
if (SetupDiEnumDeviceInterfaces(hwDeviceInfo, 0, (LPGUID)& CyDrvGuid,
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);
//Retrieve the information from Plug and Play including the device path
if (SetupDiGetInterfaceDeviceDetail(hwDeviceInfo,
&devInterfaceData,
functionClassDeviceData,
predictedLength,
&requiredLength,
&devInfoData)) {
wprintf(L"%ls\n", functionClassDeviceData->DevicePath); //打印设备实例路径,wchar类型的变量需使用 wprintf 函数或者 wcout 函数。
Wchar_tToString(usbDevicePath,functionClassDeviceData->DevicePath);
}
}
}
SetupDiDestroyDeviceInfoList(hwDeviceInfo);
return usbDevicePath;
}