【问题标题】:Casting UnsafeMutablePointers to UnsafeMutableRawPointers将 UnsafeMutablePointers 转换为 UnsafeMutableRawPointers
【发布时间】:2016-09-18 18:40:54
【问题描述】:

我在更新到 swift 3.0 时遇到了一些问题。我有以下代码:

  // Retrieve the Device GUID
        let device = UIDevice.current
        let uuid = device.identifierForVendor
        let mutableData = NSMutableData(length: 16)
        (uuid! as NSUUID).getBytes(UnsafeMutablePointer(mutableData!.mutableBytes))

        // Verify the hash
        var hash = Array<UInt8>(repeating: 0, count: 20)
        var ctx = SHA_CTX()
        SHA1_Init(&ctx)
        SHA1_Update(&ctx, mutableData!.bytes, mutableData!.length)
        SHA1_Update(&ctx, (opaqueData1! as NSData).bytes, opaqueData1!.count)
        SHA1_Update(&ctx, (bundleIdData1! as NSData).bytes, bundleIdData1!.count)
        SHA1_Final(&hash, &ctx)
        let computedHashData1 = Data(bytes: UnsafePointer(&hash), count: 20)

我的第一个问题是代码行:

(uuid! as NSUUID).getBytes(UnsafeMutablePointer(mutableData!.mutableBytes))

mutableData!.mutableBytes 现在返回一个 UnsafeMutableRawPointer 并且编译器抱怨“无法使用类型为 '(UnsafeMutableRawPointer)' 的参数调用类型为 'UnsafeMutablePointer<_> 的初始化程序”现在我一直在尝试将它们强制转换为相同的类型但没有成功。

我的第二个问题是这条线:

let computedHashData1 = Data(bytes: UnsafePointer(&hash), count: 20)

这行导致编译器错误“Ambiguous use of 'init'”

【问题讨论】:

    标签: ios swift casting unsafe-pointers migrating


    【解决方案1】:

    你的第一个问题,你可以这样写:

        (uuid! as NSUUID).getBytes(mutableData!.mutableBytes.assumingMemoryBound(to: UInt8.self))
    

    但如果您可以接受具有相同原始 UUID 字节的 Data,您可以将其写为:

        var uuidBytes = uuid!.uuid
        let data = Data(bytes: &uuidBytes, count: MemoryLayout.size(ofValue: uuidBytes))
    

    你的第二个问题,在Data.init(bytes:count:)中,第一个参数的类型是UnsafeRawPointer,可以传入任意类型的Unsafe(Mutable)Pointers。

    Using Swift with Cocoa and Objective-C (Swift 3)

    检查Pointers 的常量指针部分。

    当函数被声明为采用UnsafeRawPointer 参数时, 对于任何类型,它都可以接受与 UnsafePointer&lt;Type&gt; 相同的操作数 Type.

    您无需转换指针类型。

        let computedHashData1 = Data(bytes: &hash, count: 20)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-01-17
      • 1970-01-01
      • 2014-07-20
      • 2017-01-27
      • 2013-05-10
      • 2020-09-28
      • 2013-07-26
      相关资源
      最近更新 更多