4

I am trying to use CommonCrypto (with the help of https://github.com/sergejp/CommonCrypto) for the first time with swift. Here is my code:

UnsafeRawPointer(ivData!.withUnsafeBytes
{(pointer) -> UnsafePointer<Any> in
    let ivBuffer = pointer
})

The error is:

Cannot convert value of type 'UnsafePointer' to expected argument type 'UnsafePointer<_>'

What does the <_> signify? What do I need to do? Thanks.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
ewizard
  • 2,801
  • 4
  • 52
  • 110
  • Its saying that you cannot convert the type UnsafePointer to a UnsafePointer with a type. I think you need to remove . Above that it is hard to know with out more code as context. – Nordeast Dec 04 '17 at 20:35
  • i get another error when I do this `Reference to generic type 'UnsafePointer' requires arguments in <...>` telling me to revert – ewizard Dec 04 '17 at 20:37

1 Answers1

7

It's pointer that it is complaining about. You need to cast it. Here's an example usage, part of creating an MD5 hash:

    var rawBytes = [UInt8](repeating: 0, count: Int(CC_MD5_DIGEST_LENGTH))
    let _ = data.withUnsafeBytes { (bytes: UnsafePointer<UInt8>) in
        CC_MD5(bytes, CC_LONG(data.count), &rawBytes)
    }
Don
  • 3,654
  • 1
  • 26
  • 47
  • great thanks that did it....are the `rawBytes` always able to be cast as `UInt8`? I am doing AES encryption – ewizard Dec 04 '17 at 20:56
  • You can cast it to whatever you want. To be clear, the reason that you have to cast it is because you are returning it, and `preBuffer` will be whatever type you are casting it to. Take a look at the Swift 3 answer using `Data` at https://stackoverflow.com/questions/37680361/aes-encryption-in-swift, it might provide more insight into how to use it. – Don Dec 04 '17 at 21:15
  • Side note: you should try to avoid using the force-unwrap operator `!` where you can, by using `if let` or `guard let` constructs. Colloquially, `!` is known as the "crash operator" – Don Dec 04 '17 at 21:19
  • yah im just figuring the optionals out...i have guard where i need it in most places except below i plan on putting that in – ewizard Dec 04 '17 at 22:10
  • great link...i was looking for something like that for a while to base my encryption function on – ewizard Dec 05 '17 at 00:21