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

标签 swift zlib

我想从字符串中生成 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/

相关文章:

ios - 在制作自定义 UIButton 时,以 NSException 类型的未捕获异常终止

javascript - 膨胀 zlib 压缩数据

ios - 对 arc4random() 施加限制?

swift - 我可以复制一个SCNNode并保持规模吗

ios - 隐藏 View 时,自动布局中的 Swift 约束不会改变

c++ - 具有特定文件和特定缓冲区大小的 zlib Z_BUF_ERROR

c++ - Inflate HTML gZIP 内容时出现错误 `invalid distance too far back`

swift - 更改 NSStatusBar 字体颜色和大小

python-3.x - 如何使用 zlib.compressobj(..., zdict)

c - 为什么 zlib 努力只计算正指针差异?