gpt4 book ai didi

swift - 如何将供应商/产品 ID 添加到 USB 匹配字典

转载 作者:搜寻专家 更新时间:2023-11-01 06:36:02 24 4
gpt4 key购买 nike

在 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)
})
})
})
}

最佳答案

你尝试的崩溃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

关于swift - 如何将供应商/产品 ID 添加到 USB 匹配字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41543234/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com