[swift-users] proper syntax for inout array handling?

Joe Groff jgroff at apple.com
Thu Jun 9 23:37:21 CDT 2016


> On Jun 9, 2016, at 8:39 PM, Saagar Jha via swift-users <swift-users at swift.org> wrote:
> 
> Nevermind, I lied. Swift does allow direct pointer arithmetic:
> 
> import Foundation
> 
> var source = [UInt8](repeating: 0x1f, count: 32)
> var destination = [UInt8](repeating: 0, count: 64)
> 
> memcpy(&destination, source, 32) // the C function
> 
> memcpy(&destination + 3, source, 13) // the + operator works to offset

Arrays can indeed be used as pointer parameters, but the second one only works by accident. The pointer bridging has the same semantics as an 'inout' parameter, so the pointer is only valid for the duration of the immediate call, and since operators in Swift are also function calls, the pointer expires after the '+' operation. If you're doing anything with an array other than passing it off to a single C function, you should use withUnsafeMutableBufferPointer instead:

destination.withUnsafeMutableBufferPointer { p in
  memcpy(p.baseAddress, source, 32)
  memcpy(p.baseAddress + 3, source, 13)
}

In addition to not having undefined behavior, this will also probably be faster, since it'll only need to pin the array for pointer access once instead of twice.

-Joe


More information about the swift-users mailing list