gpt4 book ai didi

ios - 将 UnsafeMutablePointer 转换为 UnsafeMutableRawPointer

转载 作者:行者123 更新时间:2023-11-30 13:04:22 30 4
gpt4 key购买 nike

我在更新到 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)

此行会导致编译器错误“‘init’的使用不明确”

最佳答案

你的第一期,你可以这样写:

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

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

    var uuidBytes = uuid!.uuid
let data = Data(bytes: &uuidBytes, count: MemoryLayout.size(ofValue: uuidBytes))
<小时/>

您的第二期,在 Data.init(bytes:count:) ,第一个参数的类型为UnsafeRawPointer ,您可以向其传递任意类型的 Unsafe(Mutable)Pointer s。

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

检查 Pointers 的常量指针部分.

When a function is declared as taking an UnsafeRawPointer argument, it can accept the same operands as UnsafePointer<Type> for any type Type.

您无需强制转换指针类型。

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

关于ios - 将 UnsafeMutablePointer 转换为 UnsafeMutableRawPointer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39561300/

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