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

Ken Burgett kenb at iotone.io
Fri Jun 10 09:36:10 CDT 2016


On 2016-06-09 21:37, Joe Groff wrote:
>> 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

Thanks for the good answers, both Saager and Joe.  I like the way you 
both developed solutions and then improved them, and for good reasons.

I do have a situation in the ugly C code I am porting to Swift where a 
pointer gets passed down to a second function, so Joe's solution looks 
like the right approach.

Thanks again.
-- 
Ken Burgett
Principal Software Engineer
Email: kenb at iotone.io
Office: 530.693.4449
Mobile: 831.332.6846
URL: www.iotone.co


More information about the swift-users mailing list