Question

I am using libusb to interact with a usb device. I have created a Class and a member function will receive the input from the device and process it. I am using Asynchronous api. Now the libusb_fill_bulk_transfer() function call throws a compilation error:

void MyDeviceClass::on_connectButton_clicked()
{
   int r; //for return values
   ssize_t cnt; //holding number of devices in list
   r = libusb_init(&ctx); //initialize the library for the session we just declared
   if(r < 0) {
      qDebug()<<"Init Error "<<r<<endl; //there was an error
      return;
   }
   ...
   ...
   ...

   libusb_fill_bulk_transfer( transfer_in, dev_handle, USB_ENDPOINT_IN,
            inBuffer, LEN_IN_BUFFER,readDataFromBuffer,NULL,0);
   libusb_submit_transfer(transfer_in);
   QtConcurrent::run (this,&MyDeviceClass::eventThread);
}

The compiler suggests using &MyDeviceClass::readDataFromBuffer as a function pointer but that still throws an error. I tried using static members, and even static non-member functions but all in vain. Please help me in passing the callback to this function. I am using Qt, and probably won't like to use boost libraries. Please note that libusb_fill_bulk_transfer(...) is invoked inside a member function of MyDeviceClass.

Was it helpful?

Solution

I made the member function static and prototype needed to be modified:

 static void LIBUSB_CALL readDataFromBuffer(struct libusb_transfer *);

OTHER TIPS

what is the compile error when you use a non member function?

Edit: this should be LIBUSB_CALL:

    void LIBUSB_CALL BulkTransferCallback(struct libusb_transfer *transfer) {
        // This assumes that you set transfer::user_data to be a pointer to 
        // an instance of the MyDeviceClass class.
        MyDeviceClass* mdc = reinterpret_cast<MyDeviceClass*>(transfer->user_data);
        mdc->onBulkTransferCallback(transfer);
    }

Then when you set the pointer, use:

transfer.callback = &BulkTransferCallback;

As you answered yourself, actually it should be __stdcall which is defined by LIBUSB_CALL. Their documentation should include this in the function pointer typedef to remove the ambiguity.

The lib_usb api defines the function libusb_fill_bulk_transfer with:

static void     libusb_fill_bulk_transfer (struct libusb_transfer *transfer, libusb_device_handle *dev_handle, unsigned char endpoint, unsigned char *buffer, int length, libusb_transfer_cb_fn callback, void *user_data, unsigned int timeout)

It is possible to add a static class function to your class and call the non-static member-function of the class within this static function.

You this Object would be at the place of void *user_data.

In the static class function you would have to cast the member of transfer->user_data correctly to your class.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top