我正在 Swift 中开发一个程序(针对 macOS 应用程序),该程序使用 IOKit 从 USB 设备检索信息。 该应用程序崩溃了:
线程 1:EXC_BAD_ACCESS(代码=1,...
设置
CFDictionarySetValue
。
我使用了以下代码:
var matchingDict: CFMutableDictionary?
var val: NSNumber.IntegerLiteralType
var valRef: CFNumber?
matchingDict = IOServiceMatching(kIOHIDDeviceKey)
if let matchingDict {
val = 1917
valRef = CFNumberCreate(kCFAllocatorDefault, CFNumberType.sInt32Type, UnsafeMutableRawPointer?(&val))
CFDictionarySetValue(matchingDict, UnsafeRawPointer?(kIOHIDVendorIDKey), unsafeBitCast(valRef, to: UnsafeRawPointer.self))
我尝试了不同的
CFDictionarySetValue
配置:
valRef = CFNumberCreate(kCFAllocatorDefault, .sInt32Type, UnsafeMutableRawPointer?(&val))
这会发出警告(运行它会导致崩溃):
将“UnsafeRawPointer”形成为“Optional”类型的变量;这可能是不正确的,因为“可选”可能包含对象引用。
然后这个:
CFDictionarySetValue(matchingDict, unsafeBitCast(kIOHIDVendorIDKey, to: UnsafeRawPointer.self), unsafeBitCast(valRef, to: UnsafeRawPointer.self))
符合要求,但随后崩溃。
最后:
CFDictionarySetValue(matchingDict, UnsafeRawPointer?(kIOHIDVendorIDKey), unsafeBitCast(valRef, to: UnsafeRawPointer.self))
但无论如何它都会崩溃。
我做错了什么?
使用免费桥接到 Swift
CFMutableDictionary
比更新 Dictionary
要容易得多。添加字典值后,如果需要进一步调用,您可以将其转换回 CFDictionary
:
if var matchingDict = IOServiceMatching(kIOHIDDeviceKey) as? [String: Any] {
// Add values:
matchingDict[kIOHIDVendorIDKey] = 1917
let cfDict = matchingDict as CFDictionary
// ...
}