libusb获取USB名字
时间: 2024-08-15 18:10:36 浏览: 166
`libusb` 是一个跨平台的 C 库,用于在 Linux、macOS 和 Windows 等操作系统上访问 USB 设备。如果你想要使用 `libusb` 获取 USB 设备的名称,你需要遵循这些步骤:
1. **包含库头文件**:
首先,在你的 C 或 C++ 源文件中添加 `libusb.h` 的头文件,这是库的基本接口声明。
```c
#include <libusb/libusb.h>
```
2. **初始化 libusb**:
初始化 libusb 并查找设备前,需要创建一个 `libusb_device_context` 对象。
```c
libusb_context *ctx;
libusb_init(&ctx);
```
3. **寻找 USB 设备**:
使用 `libusb_get_device_list` 函数列出所有连接到系统的 USB 设备,并选择你想操作的那个设备。
```c
libusb_device **devices;
int device_count = libusb_get_device_list(ctx, &devices);
if (device_count > 0) {
// devices 数组包含了所有设备的信息
}
```
4. **遍历设备并获取设备名**:
对于找到的每一个设备,调用 `libusb_get_device_string_descriptor` 来获取设备的字符串描述符,其中包含了设备名。
```c
libusb_device_descriptor desc;
for (int i = 0; i < device_count; ++i) {
if (libusb_get_device_descriptor(devices[i], &desc)) {
char name[256];
int ret = libusb_get_device_string(devices[i], desc.iProduct, name, sizeof(name));
if (ret > 0) {
printf("Device %d: Name - %s\n", i, name);
}
}
// 清理设备列表
libusb_free_device_list(devices, 1);
}
```
5. **清理资源**:
最后,别忘了关闭 `libusb_context`。
```c
libusb_exit(ctx);
```
阅读全文
相关推荐















