在Swift 2.2中,我可以使用unsafeAddressOf
将VENDOR和PRODUCT ID添加到usb匹配字典中。
var serviceMatchingDictionary = IOServiceMatching(kIOUSBDeviceClassName)
private let VendorID = 0x8564
private let ProductID = 0x5000
let vendorIDString = kUSBVendorID as CFStringRef!
let productIDString = kUSBProductID as CFStringRef!
CFDictionarySetValue(serviceMatchingDictionary, unsafeAddressOf(vendorIDString), unsafeAddressOf(VendorID))
CFDictionarySetValue(serviceMatchingDictionary, unsafeAddressOf(productIDString), unsafeAddressOf(ProductID))
在Swift 3中,我使用withUnsafePointer(to arg: inout T, _ body: (UnsafePointer) throws -> Result) rethrows -> Result。
然而,它没有用。它可以打印出地址,但在调用CFDictionarySetValue
withUnsafePointer(to: &VendorID) { vendorIDPtr in
withUnsafePointer(to: &ProductID, { productIDPtr in
withUnsafePointer(to: &vendorIDString, { vendorIDStringPtr in
withUnsafePointer(to: &productIDString, { productIDStringPtr in
// Thread1: EXC_BAD_ACCESS(code=1, address=0x0)
CFDictionarySetValue(matchingDict, vendorIDStringPtr, vendorIDPtr)
CFDictionarySetValue(matchingDict, productIDStringPtr, productIDPtr)
})
})
})
}
答案 0 :(得分:3)
您尝试过的崩溃
发生Swift 3代码是因为整数变量的地址被传递给一个需要Foundation 对象地址的函数。但是你可以完全避免使用CFDictionarySetValue
和不安全
指针操作此任务。
IOServiceMatching()
会返回免费的CFMutableDictionary
桥接到NSMutableDictionary
:
let matchingDictionary: NSMutableDictionary = IOServiceMatching(kIOUSBDeviceClassName)
现在您只需将ID添加为NSNumber
个对象:
let vendorID = 0x8564
let productID = 0x5000
matchingDictionary[kUSBVendorID] = vendorID as NSNumber
matchingDictionary[kUSBProductID] = productID as NSNumber