Search code examples
swiftunsafe-pointers

How to convert Data to UnsafePointer<UInt8>?


In Swift I want to pass a data buffer (named data) of type Data to a C function (named do_something) that takes a pointer of type UnsafePointer<UInt8>.

Is the code example below correct? And if so, in this case is it OK to use assumingMemoryBound(to:) instead of bindMemory(to:capacity:)?

data.withUnsafeBytes { (unsafeBytes) in
  let bytes = unsafeBytes.baseAddress!.assumingMemoryBound(to: UInt8.self)
  do_something(bytes, unsafeBytes.count)
}

Solution

  • The correct way is to use bindMemory():

    data.withUnsafeBytes { (unsafeBytes) in
        let bytes = unsafeBytes.bindMemory(to: UInt8.self).baseAddress!
        do_something(bytes, unsafeBytes.count)
    }
    

    assumingMemoryBound() must only be used if the memory is already bound to the specified type.

    Some resources about this topic: