我在获取设备信息的结构上遇到了麻烦。据我了解,正确设置cbSize有点棘手,因此API正在将数据写入超出其应有的位置(导致堆栈损坏)。到目前为止,我有以下代码:

GUID guid;
HidD_GetHidGuid(&guid);

HDEVINFO info;
info = SetupDiGetClassDevs(&guid, NULL, NULL, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);

SP_DEVINFO_DATA DeviceInfoData;

memset(&DeviceInfoData, 0, sizeof(SP_DEVINFO_DATA));
DeviceInfoData.cbSize = sizeof(SP_DEVINFO_DATA);


int deviceIndex = 0;
while (SetupDiEnumDeviceInfo(info, deviceIndex++, &DeviceInfoData))
{
    SP_INTERFACE_DEVICE_DATA data;
    data.cbSize = sizeof(SP_INTERFACE_DEVICE_DATA);

    int interfaceIndex = 0;


    while (SetupDiEnumDeviceInterfaces(info, &DeviceInfoData, &guid, interfaceIndex++, &data))
    {

        //https://msdn.microsoft.com/en-us/library/windows/hardware/ff551120%28v=vs.85%29.aspx
        //Get the required buffer size. Call SetupDiGetDeviceInterfaceDetail with a NULLDeviceInterfaceDetailData pointer,
        //a DeviceInterfaceDetailDataSize of zero, and a valid RequiredSize variable. In response to such a call, this function
        //returns the required buffer size at RequiredSize and fails with GetLastError returning ERROR_INSUFFICIENT_BUFFER.

        SP_DEVICE_INTERFACE_DETAIL_DATA interfaceData;
        interfaceData.cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA);

        DWORD bufferSize = 0;
        SetupDiGetDeviceInterfaceDetail(info, &data, NULL, 0, &bufferSize, nullptr);

        if (GetLastError() == ERROR_INSUFFICIENT_BUFFER)
        {
            //Call the function again
            SetupDiGetDeviceInterfaceDetail(info, &data, &interfaceData, bufferSize, NULL, &DeviceInfoData);

            DWORD error = GetLastError();
            if (error != ERROR_SUCCESS)
            {
                printf("Could not obtain device interface details. Error: %d \n", error);
            }
        }
    }


我得到的错误是:

    Run-Time Check Failure #2 - Stack around the variable 'DeviceInfoData' was corrupted.


尽管我已经看到SP_INTERFACE_DEVICE_DATASP_DEVICE_INTERFACE_DETAIL_DATA导致相同的错误

任何帮助是极大的赞赏!

最佳答案

看来您的interfaceData缓冲区太小。

再次检查the documentationDeviceInterfaceDetailDataSetupDiGetDeviceInterfaceDetail参数。

关于c++ - 使用SetupDiXxx结构的堆栈损坏,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28619910/

10-10 16:17