[英]libusb callback_in function as a member of a class in C++
I have a problem defining and using the callback function in libusb_fill_bulk_transfer
when called as a member of a class in C++. 当在C ++中作为类的成员调用时,我在
libusb_fill_bulk_transfer
定义和使用回调函数时libusb_fill_bulk_transfer
问题。
Here is the definition in the class: 这是类中的定义:
namespace usb_connector
{
class USBConnector
{
public:
USBConnector();
~USBConnector();
int connect(void);
void read(void);
void write(unsigned char *);
void disconnect(void);
void LIBUSB_CALL callback_in(struct libusb_transfer*);
...
Here is the implementation in the class: 这是类中的实现:
void LIBUSB_CALL usb_connector::USBConnector::callback_in(struct libusb_transfer *transfer)
{
if (transfer == NULL) {
cout << "No libusb_transfer..." << endl;
}
else {
cout << "libusb_transfer structure: " << endl;
cout << "actual_length = " << transfer->actual_length << endl;
for (int i = 0; i < transfer->actual_length; i++) {
cout << transfer->buffer[i];
}
cout << endl;
}
return;
}
And here is how I call it: 以下是我称之为:
...
...
libusb_fill_bulk_transfer( transfer_in, usb_dev, USB_ENDPOINT_IN,
in_buffer, LEN_IN_BUFFER, callback_in, NULL, 0);
...
...
The error I get is the following: 我得到的错误如下:
error: cannot convert 'usb_connector::USBConnector::callback_in' from type 'void (usb_connector::USBConnector::)(libusb_transfer*)' to type 'libusb_transfer_cb_fn {aka void ( )(libusb_transfer )}' in_buffer, LEN_IN_BUFFER, callback_in, NULL, 0);
错误:无法将'usb_connector :: USBConnector :: callback_in'从类型'void(usb_connector :: USBConnector ::)(libusb_transfer *)'转换为'libusb_transfer_cb_fn {aka void( )(libusb_transfer )}'in_buffer,LEN_IN_BUFFER,callback_in, NULL,0);
How can I have the callback function as a member of a class and how do I make a call to it? 如何将回调函数作为类的成员以及如何调用它?
A pointer to a class member function and a pointer to a function are incompatible in C++. 指向类成员函数的指针和指向函数的指针在C ++中是不兼容的。
According to documentation, the prototype for callback is: 根据文档,回调的原型是:
typedef void( * libusb_transfer_cb_fn) (struct libusb_transfer *transfer)
And struct libusb_transfer
has the user_data
field, which obviously fill in during you set callback, so you need a wrapper: 而
struct libusb_transfer
有user_data
字段,显然在你设置回调期间填写,所以你需要一个包装器:
void LIBUSB_CALL callback_wrapper(struct libusb_transfer *transfer)
{
usb_connector::USBConnector *connector = reinterpret_cast<usb_connector::USBConnector*>(transfer->user_data);
connector->callback_in(transfer);
}
And pass this
during the call: 并通过
this
通话过程中:
...
...
libusb_fill_bulk_transfer( transfer_in, usb_dev, USB_ENDPOINT_IN,
in_buffer, LEN_IN_BUFFER, callback_wrapper, this, 0);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.