zlib的crc32函数在swift中失败3无法为类型为'UnsafePointer '的类型为'(UnsafeRawPointer)'的参数列表调用初始值设定项'

问题描述:

我想从字符串中创建一个CRC32哈希值,因此我得到了zlib函数crc32 。zlib的crc32函数在swift中失败3无法为类型为'UnsafePointer <Bytef>'的类型为'(UnsafeRawPointer)'的参数列表调用初始值设定项'

但在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>从上下文。

+0

谢谢你的答复! –

+0

很好的答案Martin。快速提问:为什么在这里使用'numericCast'而不是'strData.count'?这是用来防止溢出? – JAL

+1

@JAL:'strData.count'是一个'Int',但'crc32()'带有'uInt'参数。所以你必须将该值转换为'uInt(strData.count)',或者使用泛型函数'numericCast'来转换任意有符号和无符号整数类型。这是一个你挑选哪一个品味的问题。 –