2017-01-09 8 views
1

Swift 2.2では、unsafeAddressOfを使用して、VENDORとPRODUCT IDをUSBマッチング辞書に追加できます。USBマッチング辞書にベンダー/プロダクトIDを追加する方法

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

スウィフト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

あなたはどのようなエラーメッセージを得るのですか? – mlidal

+0

スレッド1:EXC_BAD_ACCESS(コード= 1、アドレス= 0x0) – WeiJay

答えて

2

を呼び出すときに、整数変数のアドレスは、財団のアドレスを期待する関数に渡されるので、あなたが試み スウィフト3コードでクラッシュが発生したクラッシュオブジェクト。しかし、CFDictionarySetValueと安全でない ポインタ操作をこのタスクに使用することを完全に避けることができます。

IOServiceMatching()はフリーダイヤル NSMutableDictionaryにブリッジであるCFMutableDictionaryを返します

let matchingDictionary: NSMutableDictionary = IOServiceMatching(kIOUSBDeviceClassName) 

今、あなたは、単にNSNumberオブジェクトとしてIDを追加することができます

let vendorID = 0x8564 
let productID = 0x5000 

matchingDictionary[kUSBVendorID] = vendorID as NSNumber 
matchingDictionary[kUSBProductID] = productID as NSNumber 
+0

本当に!!!!私に多くの時間を節約してくれてありがとう。 – WeiJay

関連する問題