有人有使用 c/c++ IOCTL 调用的经验吗? 基本上我试图确定 USB 内存棒插入哪个端口。 我有所有 USB 信息和音量信息。显然,要链接这两个信息 block ,我需要驱动程序 key 或序列号。 但是,当调用 DeviceIoControl 时,我得到无效句柄作为“最后一个错误代码”
我的U盘挂载到c:\中的一个目录(不是盘符)见下
//get a handle on the volume
HANDLE hVolume;
DWORD dwAccessFlags;
dwAccessFlags = GENERIC_READ | GENERIC_WRITE;
hVolume = CreateFile(L"C:\_USB\MP1",
dwAccessFlags,
FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL,
OPEN_EXISTING,
0,
NULL );
if (hVolume == INVALID_HANDLE_VALUE) {
printf("Invalid Handle");
}
//use the handle
MEDIA_SERIAL_NUMBER_DATA* pserialNumberData = new MEDIA_SERIAL_NUMBER_DATA;
wstring result;
//HANDLE hVolume = OpenVolume(vname.substr(0, vname.length() - 1).c_str());
DWORD bytesReturned = 0;
LPDWORD lpBytesReturned = &bytesReturned;
OVERLAPPED over;
LPOVERLAPPED lpOver = &over;
BOOL success = 1;
success = DeviceIoControl(
(HANDLE) hVolume, // handle to device
IOCTL_STORAGE_GET_MEDIA_SERIAL_NUMBER, // dwIoControlCode
NULL, // lpInBuffer
0, // nInBufferSize
(LPVOID) pserialNumberData, // output buffer
(DWORD) sizeof(MEDIA_SERIAL_NUMBER_DATA), // size of output buffer
(LPDWORD) lpBytesReturned, // number of bytes returned
(LPOVERLAPPED) lpOver // OVERLAPPED structure
);
wcout << L"--> GetSn() DeviceIoControl success " << success << endl;
wcout << L"--> GetSn() DeviceIoControl Last error number " << GetLastError() << endl;
wcout << L"--> GetSn() DeviceIoControl Bytes Returned " << bytesReturned << endl;
wcout << L"--> GetSn() DeviceIoControl struct size " << sizeof(MEDIA_SERIAL_NUMBER_DATA) << endl;
最佳答案
如果您查看 DeviceIoControl 的备注部分功能,它说:
To retrieve a handle to the device, you must call the
CreateFile
function with either the name of a device or the name of the driver associated with a device. To specify a device name, use the following format:
\\.\DeviceName
DeviceIoControl can accept a handle to a specific device. For example, to open a handle to the logical drive A: with
CreateFile
, specify\\.\a:
. Alternatively, you can use the names\\.\PhysicalDrive0
,\\.\PhysicalDrive1
, and so on, to open handles to the physical drives on a system.
您没有打开设备句柄,因此 DeviceIoControl 不适用于这种情况。
关于c++ - 调用 IOCTL_STORAGE_GET_MEDIA_SERIAL_NUMBER 时句柄无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9808220/