libusb_get_device_list seg fault

时间:2014-05-30 08:53:52

标签: c++ qt segmentation-fault libusb

我正在用Qt C ++编写一个文件资源管理器应用程序,并有一个libUSB函数(QList UsbDevice :: getDeviceList()),它获取所有连接的USB设备,检查每个设备供应商和产品ID,声明它们和返回他们在一个数组中。这一切都很好,我得到了我想要的设备,但是我添加了一个刷新按钮,它应该更新下拉列表中显示的设备列表(它基本上再次调用getDeviceList函数)但是它在调用时会出现错误:

int numDevices = libusb_get_device_list(NULL, &usbDevices);
第二次,我不能为我的生活看到原因。如果有人可以检查下面的代码,看看我是否错过了一些非常有用的愚蠢行为。

QList<UsbDevice*> UsbDevice::getDeviceList()
{

unsigned char manf[256] = {'\0'};

QList<UsbDevice*> usbDeviceList;

libusb_device **usbDevices;
struct libusb_device_descriptor desc;

int numDevices = libusb_get_device_list(NULL, &usbDevices);
if(numDevices < 0)
{
    libusb_free_device_list(usbDevices, 1);
    return usbDeviceList;
}
QString error;

for(int i=0; i!=numDevices; ++i)
{
    libusb_device *dev = usbDevices[i];
    libusb_get_device_descriptor(dev, &desc);

    if((desc.idVendor != VendorUsbId) && (desc.idProduct != ProductUsbId))
        continue;

    libusb_device_handle *handle = NULL;
    libusb_config_descriptor *conf_desc = NULL;

    int result = 0;

    result = libusb_open(dev, &handle);
    if(result < 0)
    {
        if(result == -3)
        {

        }
        error = QString(libusb_error_name(result));
        continue;
    }

    int config = 1;



    if( handle == NULL)
    {
        continue;
    }

    result = libusb_set_configuration(handle, config);
    if(result < 0)
    {
        error = QString(libusb_error_name(result));
        continue;
    }

    result = libusb_get_config_descriptor(dev, 0, &conf_desc);
    if(result < 0)
    {
        error = QString(libusb_error_name(result));
        continue;
    }

    result = libusb_claim_interface(handle, 0);
    if(result < 0)
    {
        error = QString(libusb_error_name(result));
        continue;
    }

    result = libusb_get_string_descriptor_ascii(handle, desc.iProduct, manf, sizeof(manf));
    if(result < 0)
    {
        error = QString(libusb_error_name(result));
        continue;
    }

    UsbDevice *newDevice = new UsbDevice();
    newDevice->setDeviceName(QString((char*)manf));
    newDevice->setHandle(handle);

    usbDeviceList << newDevice;
}

libusb_free_device_list(usbDevices, 1);

return usbDeviceList;

}

1 个答案:

答案 0 :(得分:1)

您在程序开头调用了libusb_init(),但在调用libusb_exit()之前,您也在开始时调用a.exec()

你的第一个电话可能发生在MainWindow构造函数中?

您可以改为继承QApplication,在构造函数中调用libusb_init(),在析构函数中调用libusb_exit()