【发布时间】:2018-06-01 22:40:30
【问题描述】:
这一定是我的一个简单错误,因此我犹豫使用“不工作”这个词。
这是我的代码,问题是从 io_name_t 变量到 char 数组的 strcpy 似乎不起作用,即没有复制数据。
定义结构以保存数据以供进一步使用:
static struct sUSBDevInfo {
char devName[200];
char svcPlane[200];
char othPlane[200];
int isScreen;
} USBDevInfo[99];
现在填充结构:
int getUSBDevices ()
{
int i = -1;
CFMutableDictionaryRef matchingDict;
io_iterator_t iter;
kern_return_t kr;
io_service_t device;
io_name_t deviceName;
io_string_t pathName;
matchingDict = IOServiceMatching(kIOUSBDeviceClassName);
if ( matchingDict == NULL)
{
return ( "No match" );
}
/* Now we have a dictionary, get an iterator.*/
kr = IOServiceGetMatchingServices(kIOMasterPortDefault, matchingDict, &iter);
if (kr != KERN_SUCCESS)
{
return (0);
}
/* iterate */
while ((device = IOIteratorNext(iter)))
{
/* do something with device, eg. check properties */
/***Display the device names ***/
kr = IORegistryEntryGetName(device, deviceName);
if (KERN_SUCCESS != kr)
{
deviceName[0] = '\0';
}
i++;
printf("\ndeviceName:%s",deviceName);
strcpy(USBDevInfo[i].devName, deviceName); /* !!! This and the following strcpy leave the dest variable unchanged !!! */
IORegistryEntryGetPath(device, kIOServicePlane, pathName);
strcpy(USBDevInfo[i].svcPlane, pathName);
IORegistryEntryGetPath(device, kIOUSBPlane, pathName);
strcpy(USBDevInfo[i].othPlane, pathName);
USBDevInfo[i].isScreen = isScreen(deviceName);
IOObjectRelease(device);
}
/* Done, release the iterator */
IOObjectRelease(iter);
return ( i );
}
当我调试时,它显示 deviceName 具有预期值(例如 deviceName:Root Hub Simulation Simulation),但 USBDevInfo[i].devName 的 strcpy 使目标保持不变('\0')。
编辑。
尝试过。复制到另一个局部变量有效,但不能复制到全局静态结构项:
char cpy[200]; /* local variable */
.
.
strcpy(cpy, deviceName); /* Works - copied to cpy */
strcpy(USBDevInfo[i].devName, deviceName); /* Not working */
USBDevInfo[i].devName[0] = deviceName[3]; /* Not working */
编辑 2
请看下面的答案。
【问题讨论】:
-
所以如果它现在对您的“编辑 2”更改有效,还有问题吗?
-
@Michael - 是的,它现在正在工作。