gpt4 book ai didi

swift - zlib 的 crc32 函数在 swift 3 中失败 无法使用类型为 'UnsafePointer' 的参数列表调用类型为 '(UnsafeRawPointer)' 的初始化程序

转载 作者:可可西里 更新时间:2023-11-01 00:58:21 26 4
gpt4 key购买 nike

我想从字符串中生成 CRC32 哈希,所以我得到了 zlib 函数 crc32。

但在 Swift 3 中,这会产生问题。

代码如下所示:

func crc32HashString(_ string: String) {
let strData = string.data(using: String.Encoding.utf8, allowLossyConversion: false)
let crc = crc32(uLong(0), UnsafePointer<Bytef>(strData!.bytes), uInt(strData!.length))
}

编译器给我这个错误:

Cannot invoke initializer for type 'UnsafePointer<Bytef>' with an argument list of type '(UnsafeRawPointer)'

如何解决此错误?

致以最诚挚的问候,感谢您的帮助!

阿图尔

最佳答案

Data 的字节数使用

访问值
/// Access the bytes in the data.
///
/// - warning: The byte pointer argument should not be stored and used outside of the lifetime of the call to the closure.
public func withUnsafeBytes<ResultType, ContentType>(_ body: (UnsafePointer<ContentType>) throws -> ResultType) rethrows -> ResultType

方法。它调用一个带有指向字节的(类型化)指针的闭包:

let strData = string.data(using: .utf8)! // Conversion to UTF-8 cannot fail
let crc = strData.withUnsafeBytes { crc32(0, $0, numericCast(strData.count)) }

这里是 $0 的类型自动推断为 UnsafePointer<Bytef>从上下文。

更新:从 Swift 5 开始

public func withUnsafeBytes<ResultType>(_ body: (UnsafeRawBufferPointer) throws -> ResultType) rethrows -> ResultType

使用必须“绑定(bind)”到预期类型的​​“原始”缓冲区指针调用闭包 Bytef (又名 UInt8 ):

let strData = string.data(using: .utf8)! // Conversion to UTF-8 cannot fail
let crc = strData.withUnsafeBytes {
crc32(0, $0.bindMemory(to: Bytef.self).baseAddress, numericCast(strData.count))
}

关于swift - zlib 的 crc32 函数在 swift 3 中失败 无法使用类型为 'UnsafePointer<Bytef>' 的参数列表调用类型为 '(UnsafeRawPointer)' 的初始化程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39725022/

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