CFDictionaryGetValue 抛出 EXC_BAD_ACCESS

CFDictionaryGetValue throws EXC_BAD_ACCESS

我在 Objective-C 中找到了从 Getting graphic card information in objective C 截取的代码,我目前正在尝试将其转换为 Swift。 我正在尝试从 CFMutableDictionary 中读取一个值(代码如下)。但是,当我调用函数 CFDictionaryGetValue 时,出现错误: "Thread 1: EXC_BAD_ACCESS (code=1, address=0x656d614e4f60)"

这是我当前的代码:

static func getGpuName() {
        var iterator: io_iterator_t = 0
        let errCode: kern_return_t  = IOServiceGetMatchingServices(kIOMasterPortDefault, IOServiceMatching("IOPCIDevice"), &iterator)
        if errCode != kIOReturnSuccess {
            fatalError("Could not retrieve the service dictionary of \"IOPCIDevice\"")
        }

        // iterate over the pci devices
        var device = IOIteratorNext(iterator)
        while device != 0 {
            var unmanagedServiceDictionary: Unmanaged<CFMutableDictionary>?
            if IORegistryEntryCreateCFProperties(device, &unmanagedServiceDictionary, kCFAllocatorDefault, 0) != kIOReturnSuccess {
                IOObjectRelease(device)
                continue
            }

            if let serviceDictionary: CFMutableDictionary = unmanagedServiceDictionary?.takeRetainedValue() {
                let name = CFDictionaryGetValue(serviceDictionary, "IOName")
            }

            // release the device
            IOObjectRelease(device)

            // get the next device from the iterator
            device = IOIteratorNext(iterator)
        }
}

有人知道我如何读取 CFMutableDictionary 的值吗?

谢谢:)

好的,经过更多研究后,我仍然不知道为什么会抛出错误。但是我通过将字典转换为 NSDictionary.

找到了解决方法

以下代码现在有效:

let serviceDictionary: NSDictionary = (unmanagedServiceDictionary?.takeRetainedValue())! as NSDictionary
if let name = serviceDictionary.value(forKey: "IOName") as? String {
    print(name)
}

处理 CoreFoundation API 真的很痛苦。

发生错误是因为您不能将文字 String 作为 CFDictionaryGetValue 的第二个参数传递,它必须是 UnsafeRawPointer.

但是解决方案非常简单。将字典转换为 Swift 字典

if let serviceDictionary = unmanagedServiceDictionary?.takeRetainedValue() as? [String:Any] {
    if let name = serviceDictionary["IOName"] as? String {
        print(name)
    }
}