gpt4 book ai didi

c++ - libusb callback_in 函数作为 C++ 中类的成员

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:51:37 25 4
gpt4 key购买 nike

当作为 C++ 类的成员调用时,我在 libusb_fill_bulk_transfer 中定义和使用回调函数时遇到问题。

这是类中的定义:

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*);
...

下面是类中的实现:

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;
}

我是这样调用它的:

...
...
libusb_fill_bulk_transfer( transfer_in, usb_dev, USB_ENDPOINT_IN,
in_buffer, LEN_IN_BUFFER, callback_in, NULL, 0);
...
...

我得到的错误如下:

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);

如何将回调函数作为类的成员以及如何调用它?

最佳答案

在 C++ 中,指向类成员函数的指针和指向函数的指针是不兼容的。

根据文档,回调的原型(prototype)是:

typedef void( * libusb_transfer_cb_fn) (struct libusb_transfer *transfer)

struct libusb_transferuser_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);
}

并在调用过程中传递this:

...
...
libusb_fill_bulk_transfer( transfer_in, usb_dev, USB_ENDPOINT_IN,
in_buffer, LEN_IN_BUFFER, callback_wrapper, this, 0);

关于c++ - libusb callback_in 函数作为 C++ 中类的成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36471504/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com