【问题标题】:How to add vendor/product ID to a USB matching dictionary如何将供应商/产品 ID 添加到 USB 匹配字典
【发布时间】:2017-05-23 10:21:41
【问题描述】:

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

【问题讨论】:

  • 你得到什么错误信息?
  • 线程 1:EXC_BAD_ACCESS(code=1, address=0x0)

标签: swift macos swift3


【解决方案1】:

您尝试的崩溃 发生 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-11
    • 2019-09-18
    相关资源
    最近更新 更多